web访问资源

web根据资源名称去到class目录找到对应的文件,output输出屏幕

POM添加依赖

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>8.5.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-el</artifactId>
            <version>8.5.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>8.5.5</version>
        </dependency>

配置资源拦截器,同时classes\META-INF\services 目录下新建文件javax.servlet.ServletContainerInitializer 配置:xyz.luofu.www.app.MyServletContainerInitializer(tomcat会加载这里的文件)

public class MyServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        ServletRegistration.Dynamic myServletContainerInitializer =
            ctx.addServlet("myServletDispatcher", MyServletDispatcher.class);
        myServletContainerInitializer.addMapping("/");
        System.out.println(">>>>>>>>>>>>>> myServletDispatcher init");
    }
}

编写的tomcat,同时加载webapp

public class MySpringApplication {

    public void run() {

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(9090);
        try {
            String sourcePath = MySpringApplication.class.getResource("/").getPath();
            Context context = tomcat.addWebapp("/",new File("demo/src/main/webapp").getAbsolutePath());
            WebResourceRoot webResourceRoot = new StandardRoot(context);
            webResourceRoot.addPreResources(new DirResourceSet(webResourceRoot, "/WEB-INF/classes", sourcePath, "/"));
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

处理输出

public class MyServletDispatcher extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String requestURI = req.getRequestURI();

        String classPath = MySpringApplication.class.getResource("/").getPath();
        System.out.println(requestURI + ">>>>>" + classPath);
        String path = classPath + requestURI;
        FileInputStream is = new FileInputStream(new File(path));
        byte[] bytes = new byte[1024];
        is.read(bytes);
        is.close();
        resp.setContentType("text/html");
        System.out.println("++++++++++++++++++"+new String(bytes));
        resp.getWriter().write(new String(bytes)+"jjj");
    }
}

test类

public class Test {
    public static void main(String[] args) {
        new MySpringApplication().run();
    }
}

浏览器访问index.html(classes根目录下的文件) http://localhost:9090/index.html 可以成功显示

posted @ 2020-04-26 19:16  gsluofu  阅读(262)  评论(0编辑  收藏  举报