1. 程式人生 > 其它 >1、SpringBoot整合之SpringBoot整合JSP

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目錄下

四、修改步驟三中的目錄結構

五、在核心配置檔案中新增檢視解析器的字首和字尾

檔案位置:src/main/resources/application.properties

spring.mvc.view.prefix=/jsps/

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