SpirngBoot 同时使用Thymeleaf与Jsp
程序员文章站
2024-01-03 11:32:16
...
SpirngBoot 同时使用Thymeleaf与Jsp
前提需要有一个搭建好的SpringBoot项目
项目图
1. pom.xml部分
<!-- thymeleaf依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- jsp依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- tomcat依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
导包 一个都不能少
2. appliction.yml部分
spring:
thymeleaf:
mode: LEGACYHTML5 #模板类型
cache: false #缓存
encoding: utf-8 #编码
mvc:
view:
#前缀
prefix: /WEB-INF/jsp/
# 后缀
suffix: .jsp
3. 创建ViewResolverConfiguration
/**
* @author liuyp
* @date 2020/10/22
* @des 模板配置
*/
@Configuration
public class ViewResolverConfiguration{
@Configuration//用来定义 DispatcherServlet 应用上下文中的 bean
@EnableWebMvc
@ComponentScan("com.liuyp.boot.controller")//扫描控制器组件
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
resolver.setViewNames("jsp/*");//当控制器返回的viewName符合规则时才使用这个视图解析器
resolver.setOrder(2);//设置优先级,数值越小优先级越高
return resolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
}
4. 创建controller
/**
* @author liuyp
* @date 2020/10/22
* @des 控制器
*/
@Controller
public class HelloController {
@RequestMapping("html")
public String a(){
return "index";//返回index.html页面(thymeleaf)
}
@RequestMapping("jsp")
public String b(){
return "jsp/index";//返回 /WEB-INF/jsp/index.jsp 页面(jsp)
}
}