1、SpringBoot整合之SpringBoot整合JSP
SpringBoot整合JSP
一、创建SpringBoot项目,仅选择Web模块即可
二、在POM文件中添加依赖
<!-- 添加servlet依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- 添加jstl标签库依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--添加tomcat依赖模块.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
三、创建目录:webapp/WEB-INF、webapp/jsps
注意:一定要在main目录下,与 /java 同级
四、修改步骤三中的目录结构
五、在核心配置文件中添加视图解析器的前缀和后缀
文件位置:src/main/resources/application.properties
spring.mvc.view.prefix=/jsps/ //设定视图解析器的前缀,这里的前缀根据你jsp文件的位置进行选择
spring.mvc.view.suffix=.jsp //设定视图解析器的后缀
六、创建JSP
文件位置:webapp/jsps/test.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hello, test.jsp</h1><br/>
1+1=${1+1}<br/>
${requestScope.time}<br/>
</body>
</html>
七、创建一个action进行测试
package cn.byuan.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller
@RequestMapping("/test")
public class JavaServicePagesTest {
private static final String datePattern="yyyy-MM-dd E HH:mm:ss";
@RequestMapping("/m1.action")
public String methodOne(HttpServletRequest request){
request.setAttribute("time", new SimpleDateFormat(datePattern).format(new Date()));
return "test";
}
}
八、配置web resources directorys
九、运行项目,打开浏览器输入URL
http://localhost:8080/text/m1.action
源码地址:https://github.com/byuan98/springboot-integration/tree/master/test001_springboot_jsp