首页 > 编程语言 > 详细

web.xml 与 JavaBean 转换

时间:2020-08-27 12:20:00      阅读:58      评论:0      收藏:0      [点我收藏+]

将传统 web.xml 的 tomcat 启动,修改为类似 springboot 的 embedded tomcat 启动

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0" metadata-complete="true">
    <display-name>demo</display-name>

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.yofc.common.config.root.MainConfig</param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <async-supported>true</async-supported>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.yofc.common.config.mvc.WebMvcConfig</param-value>
        </init-param>
        <init-param>
            <param-name>dispatchOptionsRequest</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

 

对应 JaveBean 配置

import com.yofc.common.config.mvc.WebMvcConfig;
import com.yofc.common.config.root.MainConfig;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class SpisWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{MainConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebMvcConfig.class};
    }

    @Override
    protected Filter[] getServletFilters() {
        DelegatingFilterProxy securityFilterChain = new DelegatingFilterProxy("springSecurityFilterChain");
        return new Filter[]{securityFilterChain};
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setLoadOnStartup(1);
        registration.setAsyncSupported(true);
    }


    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.setInitParameter("spring.profiles.active", "dev");
    }

    // @Override
    // protected WebApplicationContext createRootApplicationContext() {
    //     WebApplicationContext context = super.createRootApplicationContext();
    //     ((ConfigurableEnvironment) context.getEnvironment()).setActiveProfiles("la");
    //     return context;
    // }

    @Override
    protected String[] getServletMappings() {
        // /* 拦截所有,/ 会排除 *.jsp 文件
        return new String[]{"/"};
    }
}

DelegatingFilterProxy 也可以用这种方式初始化

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpisWebSecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

 

tomcat 启动类

public static void main(String[] args) throws Exception {
    disableAccessWarnings();

    // 项目目录,随意
    String userDir = System.getProperty("user.dir") + File.separatorChar + "spis-server" + File.separatorChar + "target";
    // tomcat 目录,随意
    String tomcatBaseDir = userDir + File.separatorChar + "tomcat";
    // 编译后的 class 类路径
    String webappDir = userDir + File.separatorChar + "classes";

    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir(tomcatBaseDir);

    Connector connector = new Connector();
    connector.setPort(8080);
    connector.setURIEncoding("UTF-8");
    tomcat.getService().addConnector(connector);

    StandardContext ctx = (StandardContext) tomcat.addWebapp("/demo", webappDir);
    StandardJarScanner jarScanner = (StandardJarScanner) ctx.getJarScanner();
    jarScanner.setScanManifest(false);

    tomcat.start();
    tomcat.getServer().await();
}

@SuppressWarnings("unchecked")
public static void disableAccessWarnings() {
    try {
        Class unsafeClass = Class.forName("sun.misc.Unsafe");
        Field field = unsafeClass.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        Object unsafe = field.get(null);

        Method putObjectVolatile = unsafeClass.getDeclaredMethod("putObjectVolatile", Object.class, long.class, Object.class);
        Method staticFieldOffset = unsafeClass.getDeclaredMethod("staticFieldOffset", Field.class);

        Class loggerClass = Class.forName("jdk.internal.module.IllegalAccessLogger");
        Field loggerField = loggerClass.getDeclaredField("logger");
        Long offset = (Long) staticFieldOffset.invoke(unsafe, loggerField);
        putObjectVolatile.invoke(unsafe, loggerClass, offset, null);
    } catch (Exception ignored) {
    }
}

依赖

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-core</artifactId>
</dependency>

 

启动会有个错误提示,没有 jsp 解析,一般不需要 jsp 解析,修改下源代码,注释掉相关代码

org.apache.catalina.startup.Tomcat

public static void initWebappDefaults(Context ctx) {
    // Default servlet
    Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    // servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    // servlet.addInitParameter("fork", "false");
    // servlet.setLoadOnStartup(3);
    // servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMappingDecoded("/", "default");
    // ctx.addServletMappingDecoded("*.jsp", "jsp");
    // ctx.addServletMappingDecoded("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);

    // MIME type mappings
    addDefaultMimeTypeMappings(ctx);

    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    // ctx.addWelcomeFile("index.jsp");
}

 

web.xml 与 JavaBean 转换

原文:https://www.cnblogs.com/jhxxb/p/13564329.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!