首先在pom.xml文件中添加jsp的依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
创建HelloController类
package org.hx.springboot_jsp_demo11;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model){
model.addAttribute("index","hello hx");
return "hello";
}
}
在main目录下创建webapp目录,在webapp下创建WEB-INF目录,在WEB-INF目录下创建hello.jsp
<%--
Created by IntelliJ IDEA.
User: 64557
Date: 2021/3/5
Time: 10:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>hello.jsp</h1>
<h1>${index}</h1>
</body>
</html>
配置web
可以在application.properties中配置jsp路径或者用java配置类配置jsp路径
application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
java配置类
package org.hx.springboot_jsp_demo11;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class HelloConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/",".jsp");
}
}