springboot jsp只能在webapp_SpringBoot 添加对JSP的支持(附常见坑点)

常见问题:1.修改JSP需重启才能生效:
在生产环境中,SpringBoot重新编译JSP可能会导致较大的性能损失,并且很难追查到问题根源,所以在最新的版本中,官方已经默认关闭此功能,详见JspServlet类的初始化参数。那么,如何解决这个问题呢?推荐两个解决办法:1.使用devtools 2. 添加配置(server.servlet.jsp.init-parameters.development=true)2.如何避免各种404:
1.导入Tomcat+JASPER+JSTL 2.必须创建webapp目录 3.推荐使用外置Tomcat


正文:SpringBoot 添加对JSP的支持

1. 搭建脚手架

首先使用 Spring Initializr 构建工程,选择war类型进行构建,整体结构图如下:

4473fb169786a190e4e9b3dbf837dd77.png

项目结构图

2. 在pom.xml 添加相关依赖

 <?xml version="1.0" encoding="UTF-8"?>4.0.0com.hehe springboot-web-jsp 0.0.1-SNAPSHOTwarorg.springframework.boot spring-boot-starter-parent 2.0.0.M4org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat org.apache.tomcat.embed tomcat-embed-jasper javax.servlet jstl org.springframework.boot spring-boot-devtools org.springframework.boot spring-boot-starter-test testspring-snapshotshttp://repo.spring.io/snapshottruespring-milestoneshttp://repo.spring.io/milestonespring-snapshotshttp://repo.spring.io/snapshotspring-milestoneshttp://repo.spring.io/milestoneorg.springframework.boot spring-boot-maven-plugin 

3. 启动类添加Servlet支持

@SpringBootApplicationpublic class SpringbootWarJspApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(SpringbootWarJspApplication.class); } public static void main(String[] args) { SpringApplication.run(SpringbootWarJspApplication.class, args); }}

4. 添加MVC映射

application.yml 配置如下:

spring: mvc: view: prefix: /WEB-INF/views/ # Read From Web Resources Dir suffix: .jsp

5. 编写JSP页面

在 WEB-INF/views 目录下新建一个JSP文件

 

Hello JSP !!

![](${pageContext.servletContext.contextPath}/doge.gif)

6.启动项目

启动方式1:在IDE启动WebJspApplication,然后打开项目地址。

启动方式2:部署到外置Tomcat,启动完成后,打开项目地址。这里需要注意的是,使用外置Tomcat部署的时候,需要将嵌入式容器调整为provided级别。(防止冲突)

 org.springframework.boot spring-boot-starter-tomcat providedorg.apache.tomcat.embed tomcat-embed-jasper provided

7.单元测试

@RunWith(SpringRunner.class)@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)@DirtiesContextpublic class WebJspApplicationTest { @Autowired private TestRestTemplate restTemplate; @Test public void testJspWithEl() throws Exception { ResponseEntity entity = restTemplate.getForEntity("/", String.class); assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getBody()).contains("Hello JSP"); }}

全文至此,有疑问的小伙伴可在评论下方进行交流。

我自己是一名从事了多年开发的Java老程序员,辞职目前在做自己的Java私人定制课程,今年年初我花了一个月整理了一份最适合2019年学习的Java学习干货,从最基础的JavaSE到Spring各种框架都有整理,送给每一位Java小伙伴,想要获取的可以关注我的头条号并在后台私信我:Java,即可免费获取。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值