官方不推荐使用jsp作为前端页面开发,jar包项目不支持jsp使用,jsp需要运行在servletContext中,war包需要运行在server服务器中如tomcat;官方推荐使用thymeleaf,freemarker等模版引擎。这里仅作为了解。
1、创建一个maven且web项目,添加pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--使用外部tomcat,排除内置tomcat-->
<!--<exclusions>-->
<!--<exclusion>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--外置tomcat访问时war使用,spring boot tomcat jsp 支持开启,idea的pom里面识别不了provided的,所以必须注释掉-->
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--<!–<scope>provided</scope>–>-->
<!--</dependency>-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
2、在classpath下创建application.properties或者application.yml,添加:
application.yml:
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
application.properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
这样controller就会去找/WEB-INF/jsp/目录下的jsp文件
3、编写一个controller:
@Controller
public class PageController {
@RequestMapping(value = {"/","index"},method = RequestMethod.GET)
public String index(Map<String, Object> model){
model.put("time", new Date());
model.put("message", "hello world springboot!");
return "page";
}
}
4、在WEB-INF/page/下编写一个page.jsp:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Spring Boot Sample</title>
</head>
<body>
<h2 align="center">
Time: ${time}
<br>
Message: ${message}
</h2>
</body>
</html>
5、从浏览器访问:http://localhost:8080 或 http://localhost:8080/index