步骤 1 : 视图支持
Springboot的默认视图支持是Thymeleaf(汤么李~~),本知识点记录如何让 Springboot 支持 jsp。
步骤 2 : 可运行项目
下载后解压,比如解压到 E:\project\springboot 目录下
步骤 3 : pom.xml
增加对JSP支持
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.ryan
springboot
0.0.1-SNAPSHOT
springboot
springboot
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
org.springframework.boot
spring-boot-starter-web
junit
junit
3.8.1
test
javax.servlet
javax.servlet-api
javax.servlet
jstl
org.apache.tomcat.embed
tomcat-embed-jasper
1.8
org.springframework.boot
spring-boot-maven-plugin
步骤 4 : application.properties
在src/main/resources 目录下增加 application.properties 文件,用于视图重定向jsp文件的位置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
步骤 5 : HelloController
修改 HelloController,把本来的 @RestController 改为 @Controller。
这时返回"hello"就不再是字符串,而是根据application.properties 中的视图重定向,到/WEB-INF/jsp目录下去寻找hello.jsp文件
package com.ryan.springboot.web;
import java.text.DateFormat;
import java.util.Date;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model m) {
m.addAttribute("now", DateFormat.getDateTimeInstance().format(new Date()));
return "hello";
}
}
步骤 6 : hello.jsp
在main目录下,新建 -> webapp/WEB-INF/jsp 目录。
随后新建 hello.jsp 文件,在其中使用 EL表达式 显示放在 HelloController 的model中的当前时间。
pageEncoding="UTF-8"%>
Hi JSP. 现在时间是 ${now}
步骤 7 : 启动测试
测试地址是:
注: 启动方式是 Springboot 特有的,直接运行类:com.ryan.springboot.Application 的主方法。