1. 程式人生 > 實用技巧 >web.xml 與 JavaBean 轉換

web.xml 與 JavaBean 轉換

將傳統的 web.xml 啟動方式修改為 springboot 啟動方式

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");
}