We talked about the request in the last article. After SpringMVC receives the request and data, it performs some processing. Of course, this processing can be forwarded to the Service, and the Service layer calls the Dao layer to complete. In any case, after processing, it needs Informing the user of the result means giving the user a response.
For the response, it mainly includes two parts:
- response page
- Response data (text data,json data )
response page
The SpringMVC response page is very simple, return "page name" in string format (String).
response data
response text data
@ResponseBody (if not added, it will be treated as a response page)
//响应文本数据
//返回值为String类型,设置返回值为任意字符串信息,即可实现返回指定字符串信息,需要依赖@ResponseBody注解
@RequestMapping("/toText")
@ResponseBody
public String toText(){
System.out.println("返回纯文本数据");
return "response text";
}
response json data
//响应POJO对象
//返回值为实体类对象,设置返回值为实体类类型,即可实现返回对应对象的json数据,需要依赖@ResponseBody注解和@EnableWebMvc注解
@RequestMapping("/toJsonPOJO")
@ResponseBody
public User toJsonPOJO(){
System.out.println("返回json对象数据");
User user = new User();
user.setName("itcast");
user.setAge(15);
return user;
}
//响应POJO集合对象
//返回值为集合对象,设置返回值为集合类型,即可实现返回对应集合的json数组数据,需要依赖@ResponseBody注解和@EnableWebMvc注解
@RequestMapping("/toJsonList")
@ResponseBody
public List<User> toJsonList(){
System.out.println("返回json集合数据");
User user1 = new User();
user1.setName("黑予督");
user1.setAge(15);
User user2 = new User();
user2.setName("张鑫乐");
user2.setAge(12);
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
return userList;
}
Did you find that it is very similar to the returned text, indeed,But to be clear, the text return string josn return class is pojo
name | @ResponseBody |
---|---|
type | Method\Class Annotation |
Location | Above the SpringMVC controller method definition and on the control class |
effect | Set the return value of the current controller as the response body and write it on the class. All methods of this class have this annotation function |
related attributes | pattern: Specifies the date and time format string |
illustrate:
- This annotation can be written on the class or on the method
- Written on the class means that all methods under the class have the @ReponseBody function
- When the method is annotated with @ReponseBody
- The return value of the method is a string, which will be directly responded to the front end as text content
- The return value of the method is an object, which will convert the object into a JSON response to the front end
- Object to Json data (POJO -> json)
- Collection to Json data (Collection -> json)
Converter这个接口专门来做数据类型转换的,很多都是通过它,没事可以看看