在SpringBoot项目中使用JSP标签
##引子
最近接手公司内部一个比较老的项目,使用的很久以前的技术选型,其中就包括大量的JSP页面。
在维护过程中,当习惯了springboot的便捷性之后,很难再去接受老项目的配置--大量的xml文件,大量的properties配置文件。 甚至,项目中的不同环境切换还采用了手动注释的方式,每次发测试环境/生产环境,都要去修改大量的配置文件,所以就萌生了将项目最小化的去优化一些,尽可能的兼容老代码的前提下,引入更便捷的引入方式。
当然,这里只是简单的记录了在重构过程中使用springboot项目兼容JSP页面的过程。
SpringBoot支持JSP,但不建议使用
在spring官方文档中对于JSP的支持有这么一段描述:
27.4.5 JSP Limitations
When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.
With Jetty and Tomcat, it should work if you use war packaging. An executable war will work when launched with java -jar, and will also be deployable to any standard container. JSPs are not supported when using an executable jar.
Undertow does not support JSPs.
Creating a custom error.jsp page does not override the default view for error handling. Custom error pages should be used instead.
There is a JSP sample so that you can see how to set things up.
大致意思就是springboot虽然可以支持JSP页面,但是有一定的限制:
-
- 请将项目打成
war
包,jar
包不支持JSP。 - 使用Undertow不支持JSP。
- 对于error.jsp需要手动去处理。 同时springboot 提供了一个简单的JSP支持示例.
- 请将项目打成
引入依赖
war
org.springframework.boot
spring-boot-dependencies
2.0.1.RELEASE
pom
import
org.springframework.boot
spring-boot-starter-web
javax.servlet
jstl
org.springframework.boot
spring-boot-starter-tomcat
provided
org.apache.tomcat.embed
tomcat-embed-jasper
provided
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-surefire-plugin
false
编写Start启动类
对于这个starter类没有特殊要求,标准的springboot启动类即可。
@SpringBootApplication
public class WebStarter extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(WebStarter.class, args);
}
}
编写application.yml文件
主要实在配置文件中,对spring mvc进行配置
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
针对页面编写对应的Controller
结束,部署到tomcat下。
END
其实添加JSP支持相对还是很容易的,记录一下,避免下次踩坑。