|
@@ -0,0 +1,49 @@
|
|
|
|
|
+package space.anyi.config;
|
|
|
|
|
+
|
|
|
|
|
+import org.springframework.web.WebApplicationInitializer;
|
|
|
|
|
+import org.springframework.web.context.ContextLoaderListener;
|
|
|
|
|
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
|
|
|
|
+import org.springframework.web.filter.CharacterEncodingFilter;
|
|
|
|
|
+import org.springframework.web.servlet.DispatcherServlet;
|
|
|
|
|
+
|
|
|
|
|
+import javax.servlet.FilterRegistration;
|
|
|
|
|
+import javax.servlet.ServletContext;
|
|
|
|
|
+import javax.servlet.ServletException;
|
|
|
|
|
+import javax.servlet.ServletRegistration;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * @fileName: WebAppInitializer
|
|
|
|
|
+ * @projectName: SSM_template
|
|
|
|
|
+ * @package: space.anyi.config
|
|
|
|
|
+ * @author: 杨逸
|
|
|
|
|
+ * @date:2026/4/24 14:18
|
|
|
|
|
+ * @description: Web容器初始化类替代web.xml
|
|
|
|
|
+ */
|
|
|
|
|
+public class WebAppInitializer implements WebApplicationInitializer {
|
|
|
|
|
+ @Override
|
|
|
|
|
+ public void onStartup(ServletContext servletContext) throws ServletException {
|
|
|
|
|
+ // 1. 创建Spring容器
|
|
|
|
|
+ AnnotationConfigWebApplicationContext springContext = new AnnotationConfigWebApplicationContext();
|
|
|
|
|
+ springContext.register(SpringConfig.class);
|
|
|
|
|
+
|
|
|
|
|
+ // 2. 配置Spring监听器
|
|
|
|
|
+ servletContext.addListener(new ContextLoaderListener(springContext));
|
|
|
|
|
+
|
|
|
|
|
+ // 3. 创建Spring MVC容器
|
|
|
|
|
+ AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
|
|
|
|
|
+ mvcContext.register(SpringMvcConfig.class);
|
|
|
|
|
+
|
|
|
|
|
+ // 4. 配置DispatcherServlet
|
|
|
|
|
+ ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
|
|
|
|
|
+ "dispatcherServlet", new DispatcherServlet(mvcContext));
|
|
|
|
|
+ dispatcher.setLoadOnStartup(1);
|
|
|
|
|
+ dispatcher.addMapping("/");
|
|
|
|
|
+
|
|
|
|
|
+ // 5. 配置字符编码过滤器
|
|
|
|
|
+ FilterRegistration.Dynamic encodingFilter = servletContext.addFilter(
|
|
|
|
|
+ "encodingFilter", new CharacterEncodingFilter());
|
|
|
|
|
+ encodingFilter.setInitParameter("encoding", "UTF-8");
|
|
|
|
|
+ encodingFilter.setInitParameter("forceEncoding", "true");
|
|
|
|
|
+ encodingFilter.addMappingForUrlPatterns(null, false, "/*");
|
|
|
|
|
+ }
|
|
|
|
|
+}
|