SpringMVC 5.3.1 + Thymeleaf 3.0.12 项目配置:3个关键依赖与2个XML文件详解

📅 2026/7/11 4:49:20
SpringMVC 5.3.1 + Thymeleaf 3.0.12 项目配置:3个关键依赖与2个XML文件详解
SpringMVC 5.3.1 Thymeleaf 3.0.12 现代化配置全解析1. 项目初始化与核心依赖设计在IDEA中创建Maven项目时建议选择maven-archetype-quickstart而非webapp模板这样可以获得更干净的项目结构。现代Java Web开发中我们推荐以下精简依赖组合dependencies !-- Spring MVC核心 -- dependency groupIdorg.springframework/groupId artifactIdspring-webmvc/artifactId version5.3.1/version /dependency !-- Thymeleaf整合 -- dependency groupIdorg.thymeleaf/groupId artifactIdthymeleaf-spring5/artifactId version3.0.12.RELEASE/version /dependency !-- 嵌入式服务器依赖 -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-tomcat/artifactId version2.4.5/version scopeprovided/scope /dependency /dependencies提示虽然我们使用传统配置方式但引入spring-boot-starter-tomcat可以自动解决版本兼容性问题避免常见的类冲突。关键依赖的作用域说明依赖项作用域必要性备注spring-webmvccompile必需核心调度器、注解支持等thymeleaf-spring5compile可选模板引擎整合spring-boot-starterprovided推荐解决容器相关依赖冲突项目结构应该调整为src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── example/ │ │ ├── config/ # 配置类包 │ │ ├── controller/ # 控制器包 │ │ └── Application.java # 启动类 │ ├── resources/ │ │ ├── static/ # 静态资源 │ │ ├── templates/ # 模板文件 │ │ └── application.properties │ └── webapp/ │ └── WEB-INF/ │ └── web.xml # 传统部署描述符2. 智能化的web.xml配置现代Spring项目虽然推荐使用Java Config但理解XML配置仍然重要。以下是优化后的web.xml?xml version1.0 encodingUTF-8? web-app xmlnshttp://xmlns.jcp.org/xml/ns/javaee xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd version4.0 !-- 动态注册Filter -- filter filter-nameencodingFilter/filter-name filter-classorg.springframework.web.filter.CharacterEncodingFilter/filter-class init-param param-nameencoding/param-name param-valueUTF-8/param-value /init-param init-param param-nameforceEncoding/param-name param-valuetrue/param-value /init-param /filter filter-mapping filter-nameencodingFilter/filter-name url-pattern/*/url-pattern /filter-mapping !-- 智能ContextLoader -- context-param param-namecontextConfigLocation/param-name param-value/WEB-INF/spring/root-context.xml/param-value /context-param listener listener-classorg.springframework.web.context.ContextLoaderListener/listener-class /listener !-- 现代DispatcherServlet配置 -- servlet servlet-namedispatcher/servlet-name servlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-class init-param param-namecontextConfigLocation/param-name param-value/WEB-INF/spring/dispatcher-servlet.xml/param-value /init-param init-param param-namethrowExceptionIfNoHandlerFound/param-name param-valuetrue/param-value /init-param load-on-startup1/load-on-startup /servlet servlet-mapping servlet-namedispatcher/servlet-name url-pattern//url-pattern /servlet-mapping /web-app关键改进点增加了forceEncoding参数确保响应编码强制统一使用throwExceptionIfNoHandlerFound启用404异常处理分离root-context和dispatcher-servlet配置采用Servlet 4.0规范3. Spring MVC XML配置进阶dispatcher-servlet.xml的现代化配置应该包含以下核心元素?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xmlns:contexthttp://www.springframework.org/schema/context xmlns:mvchttp://www.springframework.org/schema/mvc xsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd !-- 智能组件扫描 -- context:component-scan base-packagecom.example.controller use-default-filtersfalse context:include-filter typeannotation expressionorg.springframework.stereotype.Controller/ /context:component-scan !-- 现代MVC配置 -- mvc:annotation-driven mvc:message-converters bean classorg.springframework.http.converter.json.MappingJackson2HttpMessageConverter property nameobjectMapper bean classcom.fasterxml.jackson.databind.ObjectMapper property namedateFormat bean classjava.text.SimpleDateFormat constructor-arg valueyyyy-MM-dd HH:mm:ss/ /bean /property /bean /property /bean /mvc:message-converters /mvc:annotation-driven !-- 静态资源处理 -- mvc:resources mapping/static/** location/static/ cache-period3600/ !-- Thymeleaf高级配置 -- bean idtemplateResolver classorg.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver property nameprefix value/WEB-INF/templates// property namesuffix value.html/ property nametemplateMode valueHTML/ property namecharacterEncoding valueUTF-8/ property namecacheable value${thymeleaf.cache:true}/ property nameorder value1/ /bean bean idtemplateEngine classorg.thymeleaf.spring5.SpringTemplateEngine property nametemplateResolver reftemplateResolver/ property nameenableSpringELCompiler valuetrue/ property nameadditionalDialects set bean classnz.net.ultraq.thymeleaf.layoutdialect.LayoutDialect/ /set /property /bean !-- 视图解析器链 -- bean classorg.thymeleaf.spring5.view.ThymeleafViewResolver property nametemplateEngine reftemplateEngine/ property namecharacterEncoding valueUTF-8/ property nameorder value1/ property nameviewNames valuethymeleaf/*/ /bean /beans配置亮点使用use-default-filters精确控制扫描范围自定义Jackson日期格式Thymeleaf支持布局方言视图解析器支持多模式共存可配置的模板缓存开关4. 验证与调试技巧项目配置完成后建议按以下清单验证依赖树检查mvn dependency:tree | grep -E spring|thymeleaf配置验证端点RestController RequestMapping(/config) public class ConfigCheckController { Autowired private ApplicationContext context; GetMapping(/beans) public ListString listBeans() { return Arrays.stream(context.getBeanDefinitionNames()) .sorted() .collect(Collectors.toList()); } GetMapping(/thymeleaf) public String checkThymeleaf() { TemplateEngine engine context.getBean(TemplateEngine.class); Context ctx new Context(); ctx.setVariable(now, LocalDateTime.now()); return engine.process(check, ctx); } }常见问题排查表现象可能原因解决方案404错误控制器未扫描或URL映射错误检查component-scan基包模板解析失败前缀/后缀配置错误验证templateResolver配置中文乱码缺少编码过滤器检查CharacterEncodingFilter静态资源无法访问未配置resources映射添加mvc:resources配置注解不生效未启用annotation-driven添加mvc:annotation-driven日志配置建议在resources目录下添加logback.xmlconfiguration appender nameSTDOUT classch.qos.logback.core.ConsoleAppender encoder pattern%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n/pattern /encoder /appender logger nameorg.springframework levelDEBUG/ logger nameorg.thymeleaf levelINFO/ root levelINFO appender-ref refSTDOUT / /root /configuration5. 性能优化配置在springMVC.xml中添加以下优化配置!-- 异步支持 -- mvc:annotation-driven mvc:async-support default-timeout3000/ /mvc:annotation-driven !-- 视图缓存控制 -- bean idthymeleafViewResolver classorg.thymeleaf.spring5.view.ThymeleafViewResolver !-- ...其他配置... -- property namecache value${thymeleaf.view.cache:false}/ /bean !-- 静态资源版本化 -- mvc:resources mapping/static/** location/static/ mvc:resource-chain resource-cachetrue mvc:resolvers mvc:version-resolver mvc:content-version-strategy patterns/**/ /mvc:version-resolver /mvc:resolvers /mvc:resource-chain /mvc:resources对应的application.properties# 开发环境配置 thymeleaf.cachefalse thymeleaf.view.cachefalse # 生产环境配置 # thymeleaf.cachetrue # thymeleaf.view.cachetrue6. 安全增强措施虽然这不是安全专题但基础防护必不可少!-- 添加CSRF防护过滤器 -- filter filter-namecsrfFilter/filter-name filter-classorg.springframework.web.filter.DelegatingFilterProxy/filter-class /filter filter-mapping filter-namecsrfFilter/filter-name url-pattern/*/url-pattern /filter-mapping !-- 在dispatcher-servlet.xml中 -- bean idcsrfFilter classorg.springframework.security.web.csrf.CsrfFilter constructor-arg bean classorg.springframework.security.web.csrf.HttpSessionCsrfTokenRepository/ /constructor-arg /bean !-- 点击劫持防护 -- filter filter-nameheaderFilter/filter-name filter-classorg.springframework.web.filter.DelegatingFilterProxy/filter-class /filter filter-mapping filter-nameheaderFilter/filter-name url-pattern/*/url-pattern /filter-mapping !-- 对应的Java配置 -- bean idheaderFilter classorg.springframework.web.filter.OncePerRequestFilter property nameheaderWriter bean classorg.springframework.security.web.header.writers.StaticHeadersWriter constructor-arg valueX-Frame-Options/ constructor-arg valueDENY/ /bean /property /bean7. 现代化改造路径对于希望逐步迁移到Java Config的项目可以采用混合配置模式创建Java配置类Configuration EnableWebMvc ComponentScan(com.example.controller) public class WebConfig implements WebMvcConfigurer { Override public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer) { configurer.enable(); } Bean public ThymeleafViewResolver thymeleafViewResolver() { ThymeleafViewResolver resolver new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); resolver.setCharacterEncoding(UTF-8); return resolver; } // 其他配置方法... }修改web.xml使用注解配置servlet servlet-namedispatcher/servlet-name servlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-class init-param param-namecontextClass/param-name param-valueorg.springframework.web.context.support.AnnotationConfigWebApplicationContext/param-value /init-param init-param param-namecontextConfigLocation/param-name param-valuecom.example.config.WebConfig/param-value /init-param /servlet这种渐进式改造方式可以让项目平稳过渡到现代Spring架构同时保留原有的XML配置优势。