老的jsp项目迁移到springboot jar包方式启动 支持jsp
环境说明:spring版本 2.7.5
场景说明
老的jsp项目想要迁移到springboot,又不想改动过多的代码。
方案说明
springboot 以jar包方式启动默认是内嵌了一个tomcat,如果想要支持jsp只需要为内嵌的tomcat设置docBase即可
注意:WEB-INF下的lib包不会被内置的tomcat加载。lib下的jar包应该直接引入到spring项目内。
web.xml迁移
web.xml主要包括servlet、filter、listener因此只要在spring中动态创建这三个对象即可
代码示例
启动类
注意 需要使用@ServletComponentScan
注解和继承SpringBootServletInitializer
让spring支持servlet注解
@SpringBootApplication
@ServletComponentScan
public class ProductApplication extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception{
SpringApplication.run(ProductApplication.class, args);
}
}
动态创建servlet、filter、listener
/**
* 动态创建servlet、filter、listener
*/
@WebListener()
public class DynRegListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) { // ServletContext 创建时,容器调用该方法
// 通过ServletContext 对象就可以动态创建servlet、filter、listener
ServletContext servletContext = sce.getServletContext()
}
支持jsp
注意:因为springboot直接打成jar包方式运行,而jsp页面也是在jar包内,因此在程序运行时应该把jar包内的jsp文件复制出来一份。因为tomcat不支持解析jar包内的jsp页面
代码示例
@Configuration
public class TomcatConfig {
@Bean
public TomcatServletWebServerFactory servletWebServerFactory(){
return new TomcatServletWebServerFactory(){
@Override
protected void configureContext(Context context, ServletContextInitializer[] initializers) {
// jsp文件所在路径
context.setDocBase("E:\\code\\target\\war");
super.configureContext(context, initializers);
}
};
}
官方文档对于内嵌tomcat的说明https://docs.spring.io/spring-boot/docs/2.7.6/reference/html/web.html#web.servlet.embedded-container