SpringBoot添加对jsp的支持

时间:2023-01-18 15:41:35

1、在pom.xml添加如下内容:

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <scope>provided</scope>
        </dependency>        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>            
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <scope>provided</scope>
        </dependency>

我的pom.xml之前有这么一段依赖代码,需要注释掉,我试了一下,不注释也不影响(重复引用?):

<!--         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency> -->

要注意的是scope需要指定为provided

不添加这些对应的引用会出现各种错误,404找不到文件,或者直接把jsp页面下载等等

2、在springboot的配置文件application.properties添加如下内容:

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

3、编写测试代码

Test2Controller.java

@Controller
public class Test2Controller {
    
    @GetMapping("test20")
    public String test20() {
        return "test20";
    }

}

test20.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>
test20
</body>
</html>

我的目录结构:

SpringBoot添加对jsp的支持