天天看點

六、SpringBoot整合JSP視圖

​ SpringBoot對JSP的支援度不高,因為它本身不推薦使用JSP視圖。但是項目中還是可以在SpringBoot中使用JSP視圖。本節我們來學習一下SpringBoot中是如何整合JSP視圖。

1、引入Maven依賴

​ SpringBoot整合JSP視圖是需要引入外部tomcat的依賴支援。

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!--外部tomcat依賴 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>
           

2、配置視圖路徑

application.properties中加入視圖解析路徑

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
           

3、編寫控制器

/**
 * @author 小吉
 * @description SpringBoot整合JSP視圖
 * @date 2020/5/28
 */
@Controller
public class IndexController {

    @RequestMapping("index")
    public String index(HttpServletRequest request){
        request.setAttribute("title","SpringBoot整合JSP視圖");
        return "index";
    }

}
           
/**
 * @author 小吉
 * @description springboot啟動類
 * @date 2020/5/28
 */
@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class,args);
    }
}
           

4、建立JSP

1、在src\main中建立webapp\WEB-INF\jsp目錄

六、SpringBoot整合JSP視圖

2、在jsp目錄中建立index.jsp

<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Insert title here</title>
</head>
<body>
    <h1><%=request.getAttribute("title")%></h1>
</body>
</html>
           

3、在pom.xml中聲明打包方式為war

<groupId>org.example</groupId>
    <artifactId>springbootdemo6</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
           

4、在WEB-INF下建立web.xml,目的是防止pom.xml檔案檢測到web項目沒有web.xml檔案而報錯。

5、啟動應用

六、SpringBoot整合JSP視圖