2.13. 前端界面
2.13.1. JSP集成
一般来说springboot不建议直接使用jsp页面,但不排除有些公司的项目依然使用jsp做前端界面。
springboot内置的tomcat并没有集成对jsp的支持,也没有对EL表达式的支持,因此要使用jsp应该先把相关的依赖集成进来
在pom文件里面新增
<!--JavaServer Pages Standard Tag Library,JSP标准标签库-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--内置tocat对Jsp支持的依赖,用于编译Jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
由于要springmvc解析jsp,要配置试图解析器,在applicaiton.properties 里面新增
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
在resources里面新建WEB-INF文件夹,在里面放一个index.jsp页面
内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>享学课堂</title>
</head>
<body>
<h1>这是个jsp页面!!</h1>
</body>
</html>
最后新建一个controller,注意这里的注解是@Controller,千万不能用@RestController
package cn.enjoy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/jsp")
public class JspController {
@RequestMapping("/hi")
public String sayHello() {
return "index";
}
}
在浏览器上输入:localhost:8080/jsp/hi,可以看到JSP页面。
2.13.2. 模
目录
板引擎
SpringBoot 推荐使用模板引擎来渲染html,如果你不是历史遗留项目,一定不要使用JSP,常用的模板引擎很多,有freemark,thymeleaf等,其实都大同小异
其中springboot 强烈推荐的是用thymeleaf
pom文件种添加thymeleaf的支持,并且删除JSP的支持
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
删除application.properties文件里面视图解析器内容
#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp
新建Controller内容如下
package cn.enjoy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/tpl")
public class ThymeleafController {
@RequestMapping("/testThymeleaf")
public String testThymeleaf(ModelMap map) {
// 设置属性
map.addAttribute("name", "enjoy");
// testThymeleaf:为模板文件的名称
// 对应src/main/resources/templates/testThymeleaf.html
return "testThymeleaf";
}
}
Springboot默认的模板配置路径为:src/main/resources/templates
在resources目录里面新建一个templates目录,在目录里面新建testThymeleaf.html文件
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head lang="en">
<meta charset="UTF-8" />
<title>enjoy</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>
在浏览器上输入:localhost:8080/tpl/testThymeleaf,可以看到页面。
2.14. 集成Swagger2构建API文档
Swagger2 的作用
l 随项目自动生成强大RESTful API文档,减少工作量
l API文档与代码整合在一起,便于同步更新API说明
l 页面测试功能来调试每个RESTful API
修改pom文件,添加swagger2的相关依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<gro