SpringBoot——02WEB
SpringBoot之WEB(跳转到一个页面或者获取一个Json数据)
模块结构:
1.返回json两种方式
@[email protected]
@Controller
@RequestMapping("/json")
public class JsonController {
@RequestMapping("/str")
@ResponseBody
public String json1(){
return "json001";
}
@RequestMapping("/obj")
@ResponseBody
public Person json2(){
return new Person(1L,"json2",new Date());
}
@RequestMapping("/list")
@ResponseBody
public List<Person> json3(){
return Arrays.asList(new Person(1L,"json2",new Date()),new Person(2L,"json2",new Date()),new Person(3L,"json2",new Date()));
}
}
@[email protected][email protected]
@RestController
@RequestMapping("/json2")
public class JsonController2 {
@RequestMapping("/str")
public String json1(){
return "json001";
}
@RequestMapping("/obj")
public Person json2(){
return new Person(1L,"json2",new Date());
}
@RequestMapping("/list")
public List<Person> json3(){
return Arrays.asList(new Person(1L,"json2",new Date()),new Person(2L,"json2",new Date()),new Person(3L,"json2",new Date()));
}
}
2.页面跳转
官方推荐使用模板引擎,不推荐jsp。这里我用的FreeeMarker
导包
org.springframework.boot spring-boot-starter-freemarker配置:application.properties
FreeeMarker 模板引擎配置
spring.freemarker.allow-request-override=false
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved
Controller
@Controller
public class IndexController {
@RequestMapping("/index")
public String json1(Model model){
model.addAttribute("msg","springboot");
return "index";
}
@RequestMapping("/index2")
@ResponseBody
public String json2(Model model){
model.addAttribute("msg","springboot");
return "index";
}
}
FreeeMarker模板
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1><span style="color: red">${msg}</span> </h1>
</body>
</html>
springboot----web结束