步骤 1 : 视图支持
Springboot的默认视图支持是Thymeleaf,本知识点记录如何让 Springboot 支持 jsp。
步骤 2 : 可运行项目
首先下载一个简单的可运行项目作为演示:链接
下载后解压,比如解压到 E:projectspringboot 目录下
步骤 3 : pom.xml
增加对JSP支持
4.0.0 com.ryan springboot0.0.1-SNAPSHOT springboot springboot org.springframework.boot spring-boot-starter-parent1.5.9.RELEASE org.springframework.boot spring-boot-starter-webjunit junit3.8.1 test javax.servlet javax.servlet-apijavax.servlet jstlorg.apache.tomcat.embed tomcat-embed-jasper1.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中的当前时间。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Hi JSP. 现在时间是 ${now}
步骤 7 : 启动测试
测试地址是:
http://127.0.0.1:8080/hello
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



