In springboot integration thymeleaf, often receives json data from the server in an HTML page, and then json data processing and rendering on the page. So how do return json type of data in the server?
1. @ResponseBody comment
The annotation for the object Controller method returns, by converting the specified interface format HttpMessageConverter
Data such as: json, xml, etc., in response to the client by Response
Increase @RespongBody on the method of controller
@RequestMapping ( "/ findAll.do" ) @ResponseBody public List <SysCategory> the findAll () { // query classification information, the specific method of service layer slightly List <SysCategory> CategoryList = categoryService.findAll (); System.out.println (CategoryList); return CategoryList; }
Java console print out the results are as follows:
Next, the data is returned in json receiving server front end
$.get("/category/findAll.do",{},function (data) {
console.log(data);
},"json");
Printed page in the console as follows:
You can see the server returns the type of data is indeed json
2. Use @RestController comment
@RestController a combination of both @ResponseBody and @Controller, which eliminates the need to use this annotation after those two notes.
@RestController @RequestMapping("/category") public class CategoryController { @Autowired private CategoryService categoryService; @RequestMapping("/findAll.do") public List<SysCategory> findAll(){ List<SysCategory> categoryList = categoryService.findAll(); System.out.println(categoryList); return categoryList; } }
Request sent by the service logic controller as in the first layer, and a method.
Printed page in the console as follows:
3. Use the response write data back to the client (not recommended)
String obj = "[SysCategory{id=1, name='JavaSe'}, SysCategory{id=2, name='JavaEE'}, SysCategory{id=3, name='前端'}, SysCategory{id=4, name='其他'}]"
ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),obj);
Printed page in the console as follows: