Spring Boot 切换至 JSP 视图模板引擎 及与 Thymeleaf 共存
package com.example;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication public class Hi { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
@Controller class HelloWorld { @RequestMapping("/") public String welcome() { return "index"; // 多引擎共存要写明文件后缀:index.jsp index.html等 } }
@Configuration // Thymeleaf 与 JSP 共存配置; 无需在application.yml中配置spring mvc view了 public class OurSpringWebMvcConfigurer implements WebMvcConfigurer { @Autowired WebApplicationContext webApplicationContext; @Bean public SpringResourceTemplateResolver thymeleafTemplateResolver() { var templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(webApplicationContext); templateResolver.setOrder(9); templateResolver.setPrefix("classpath:/templates/"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine() { var springTemplateEngine = new SpringTemplateEngine(); springTemplateEngine.setTemplateResolver(thymeleafTemplateResolver()); springTemplateEngine.setEnableSpringELCompiler(true); return springTemplateEngine; } @Bean public ThymeleafViewResolver thymeleafViewResolver() { var viewResolver = new ThymeleafViewResolver(); viewResolver.setViewNames(new String[]{"*.html"}); viewResolver.setExcludedViewNames(new String[]{"*.jsp"}); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setCharacterEncoding("UTF-8"); return viewResolver; } @Bean public InternalResourceViewResolver jspViewResolver() { var viewResolver = new InternalResourceViewResolver(); viewResolver.setOrder(10); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setViewNames("*.jsp"); //viewResolver.setViewClass(JstlView.class); return viewResolver; } }
plugins {
id 'application'
id "org.springframework.boot" version "3.0.0"
id "com.google.cloud.tools.jib" version "3.3.1"
}
repositories {
mavenCentral()
}
dependencies {
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '3.0.0'
implementation 'org.apache.tomcat:tomcat-jasper:10.1.2'
//implementation group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '3.0.0' // 共存时引入
}
application {
mainClass = 'springjsp.App'
}
jar.into('META-INF/resources') {
from('src/main/webapp')
}
jib{
from {
image = 'eclipse-temurin:19-jre'
}
to {
image = 'registry.cn-hangzhou.aliyuncs.com/x/our-spring-jsp'
auth {
username = 'u'
password = System.getenv('IMAGE_PASSWORD')?System.getenv('IMAGE_PASSWORD'):""
}
containerizingMode = "packaged"
}
}
运行:gradle bootRun