SpringBoot之WEB(跳轉到一個頁面或者獲取一個Json數據)html
模塊結構:java
1.返回json兩種方式
@Controller+@ResponseBodyweb
@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())); } }
@RestController=@Controller+@ResponseBody spring
@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.頁面跳轉json
官方推薦使用模板引擎,不推薦jsp。這裏我用的FreeeMarkerspringboot
導包session
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
配置:application.propertiesapp
# 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
Controllerjsp
@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模板ide
<!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結束