最近在学习SpringBoot框架,发现官方并不推荐使用JSP,但是目前本人作为小白,还是很多地方需要使用到JSP的。
网上找过很多对于SpringBoot支持JSP的文章,发现比较杂乱,现针对自己所遇到的问题整理一下。
废话不多说。
准备工作:
工具使用Spring Tool 3.9.2.RELEASE
使用Spring Tool 工具采用直接建立Spring Starter Project项目
1、建立好的Spring Boot项目默认对JSP不支持,需要在pom.xml中添加依赖
<!--jsp支持 -->
<!-- servlet 依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- tomcat 的支持. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
2、需要在配置文件application.properties中添加如下配置项
#返回的前缀 目录对应src/main/webapp下 spring.mvc.view.prefix: / #返回后缀 spring.mvc.view.suffix: .jsp
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class testController { @RequestMapping("/") public String home(Map<String, Object> map) { map.put("nowDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); return "manage/index"; } }
4、编写对应的JSP文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="/js/bootstrap.min.js"></script> <link href="/css/bootstrap.min.css" type="text/css"></link> <link href="/css/bootstrap-theme.min.css" type="text/css"></link> </head> <body> <h1>hello spring boot!</h1> <h2>现在时间是:${nowDate}</h2> </body> </html>
发现问题:
1、如果没有在pom.xml中添加依赖,直接return JSP视图时无法解析,弹出下载窗口;
2、在测试期间,无数据库支持时,启动Spring Boot,需要在WebApplication.java文件中@SpringBootApplication注解中添加exclude = { DataSourceAutoConfiguration.class }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); } }
本人为小白,只是记录自己出现的问题,如有错误,请大牛们批评指证,感谢!