前言:最近在试着从eclipse的ssm项目,转向使用idea的springboot来开发ssm项目。
1、eclipse的ssm项目使用jsp来写动态页面。
2、springboot项目不推荐使用jsp来写动态页面,而是使用templates。
spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录。
但是还是可以自己配置webapp目录的,编写jsp页面,只不过springboot不推荐这么使用。
动态页面
动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。
在pom.xml 中添加Thymeleaf组件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
TemplatesController.java
package hello;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@Controller
public class TemplatesController {
@GetMapping("/templates")
String test(HttpServletRequest request) {
//逻辑处理
request.setAttribute("key", "hello world");
return "/index";
}
}
@RestController:上一篇中用于将返回值转换成json
@Controller:现在要返回的是一个页面,所以不能再用@RestController,而用普通的@Controller/
request.setAttribute("key", "hello world"):这是最基本的语法,向页面转参数 key和value。
return "/index": 跳转到 templates/index.html动态页面,templates目录为spring boot默认配置的动态页面路径。
index.html 将后台传递的key参数打印出来
<!DOCTYPE html>
<html>
<span th:text="${key}"></span>
</html>
这只是一个最基本的传参,templates标签和JSP标签一样,也可以实现条件判断,循环等各种功能。不过我在上一篇讲过,建议用静态html+rest替代动态页面,所以关于templates在此不做详细介绍