Spring Boot 整合 JSP 主要涉及以下几个基础概念:
pom.xml
文件中添加 JSP 和 Servlet 相关依赖。application.properties
中配置 JSP 的视图解析路径。src/main/webapp/WEB-INF/jsp/
目录下创建 JSP 页面。以下是一个简单的 Spring Boot 整合 JSP 的示例:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
在 application.properties
中添加:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
在 src/main/webapp/WEB-INF/jsp/
目录下创建一个 index.jsp
文件:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello, Spring Boot with JSP!");
return "index";
}
}
原因:可能是视图解析器配置错误或 JSP 文件路径不正确。 解决方法:
application.properties
中的 spring.mvc.view.prefix
和 spring.mvc.view.suffix
是否正确。src/main/webapp/WEB-INF/jsp/
目录下。原因:不同版本的库之间可能存在冲突。 解决方法:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
通过以上步骤和方法,可以有效解决 Spring Boot 整合 JSP 过程中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云