语言:javaEE
框架:springboot+thymeleaf、jsp模板引擎
背景:学习springboot过程中想同时使用thymeleaf和jsp访问(官方不建议)
步骤:
1) 在pom.xml中加入依赖
jsp:
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
thymeleaf:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2) 创建视图解析器
方法:新建ViewResolverConfiguration类
@Configuration public class ViewResolverConfiguration{ @Configuration//用来定义 DispatcherServlet 应用上下文中的 bean @EnableWebMvc @ComponentScan("cn.test.book_j2ee")//扫描控制器组件 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; } } }
3) 编写控制器
@Controller public class indexController{ @RequestMapping("example") public String a(){ return "example";//返回classpath:templates/example.html页面(thymeleaf) } @RequestMapping("index") public String b(){ return "jsp/index";//返回 /WEB-INF/jsp/index.jsp 页面(jsp) } }
注:此时thymeleaf的访问路径还是默认的 classpath:templates/ ,后缀为 .html 。如需修改,请到 application.properties 配置。还可以修改viewName
参考博文:
https://blog.csdn.net/weixin_41063560/article/details/80313327
https://blog.csdn.net/e_Inch_Photo/article/details/80201272
https://blog.csdn.net/qq_19408473/article/details/71214972(使用配置文件来配置视图解析器)