Skip to main content

Spring Boot 使用 JSP

· One min read
Alan

Ref Spring Boot With JavaServer Pages (JSP)

以下代码是在 start.spring.io 站点生成的Spring Boot Web项目基础上改造的.

添加引用

pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.44</version>
<scope>provided</scope>
</dependency>

新增控制器

src/main/java/com/alanwei/spb/demo/controllers/BasicController.java
package com.alanwei.spb.demo.controllers;

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

@Controller
public class BasicController {
@RequestMapping("/welcome-view")
public String welcomeView() {
return "welcome";
}
}

新增JSP

src/main/webapp/WEB-INF/jsp/welcome.jsp
<html>
<head>
<title>Welcome</title>
</head>
<body>
<p>Welcome! This is coming from a view - a JSP</p>
</body>
</html>

更新配置

src/main/application.properties
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

运行

执行以下脚本查看效果:

mvn spring-boot:run