The returned json is annotated with "@ResponseBody". "@ResponseBody" is applied to the method. "@ResponseBody" means that the return result of the method is directly written into the "HTTP response body".
#This article will introduce two examples to demonstrate the JSON return annotation method.
Example 1
@ResponseBody acts on the method. @ResponseBody means that the return result of the method is directly written into the HTTP response body, and the data is generally obtained asynchronously. When using [that is, AJAX], after using @RequestMapping, the return value is usually parsed as a jump path, but after adding @ResponseBody, the return result will not be parsed as a jump path, but will be written directly into the HTTP response body. For example, if you obtain json data asynchronously and add @ResponseBody, the json data will be returned directly. @RequestBody Inserts the HTTP request body into the method, using an appropriate HttpMessageConverter to write the request body to an object.
The following parts are located in Spring-mvc.xml or dispatcherServlet-servlet.xml (ServletName-servlet.xml replaced Spring-mvc.xml in Spring 3.0)
<!-- 用于将对象转换为 JSON --> <bean> <property> <list> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> <bean></bean> <bean> <property> <list> <ref></ref> <ref></ref> </list> </property> </bean>
In the corresponding Controller Medium:
@RequestMapping(value="/login",method=RequestMethod.POST) public @ResponseBody User login(String username,String password){ User user = userService.login(username, password); return user; }
Here I use the jackson package:
(1) jackson-core 2.5.0
(2) jackson-databind 2.5.0
(3)jackson-annotations 2.5.0
Build path after import;
Warning: If you use the pojo class generated by orm tools such as hibernate, one-to-one, one-to-many, etc. relationships may be An infinite loop of json will be output:
You need to import com.fasterxml.jackson.annotation.JsonIgnore in the pojo class, and add the @JsonIgnore annotation to the class that needs to be shielded, so that the annotated attributes will not appear. in json.
Example 2
@ResponseBody @RequestMapping(value = "/login") public ModelAndView ajaxLogin(Model model,User user,HttpServletRequest request, HttpSession session){ String errorMessage=loginCommon(model, user, request, session); Map map=new HashMap(); if(ValueWidget.isNullOrEmpty(errorMessage)){ map.put(Constant2.AJAX_LOGIN_RESULT, "success"); }else{ map.put(Constant2.AJAX_LOGIN_RESULT, "failed"); } map.put("error", errorMessage); model.addAttribute("user", null); return new ModelAndView(new MappingJacksonJsonView(),map); }
or
model.addAttribute("user", user1);
operation result:
The above is the detailed content of What annotations are used to return json?. For more information, please follow other related articles on the PHP Chinese website!