spring boot中使用JSP

spring boot没有直接支持jsp,官方建议使用thymeleaf、freeMarker模板作为前端的视图,不过我们可以通过配置来使用jsp。

添加依赖

先将jsp相关的依赖加入

<!--引入Spring Boot内嵌的Tomcat对JSP的解析包-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->

<!-- jsp依赖jar包start -->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
</dependency>
<!-- jsp依赖jar包end -->

<!--jstl标签依赖的jar包start -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<!--jstl标签依赖的jar包end -->

修改配置文件

spring boot中默认的视图解析器是.html,这里改成.jsp

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

pom中添加下面内容

改配置主要是将jsp编译到META-INF里面,这样就可以访问到jsp了

<resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
    </resources>

创建jsp

在src/main 下创建一个webapp目录,然后在该目录下新建jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<html>
    <body>
    <h2>Hello World!</h2>
    ${msg}
    </body>
</html>

创建相应的controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class JspController {

    @RequestMapping("/jsp")
    public String jsp(Model model) {
        model.addAttribute("msg", "你好");
        return "index";
    }
}