- 前面学习了SpringMvc项目的简单搭建
- 今天天学springmvc的数据响应
- 代码地址
直接返回
//直接返回jsp页面方式
@RequestMapping("/s1")
public String show() {
return "hello";
}
模型和视图返回
//模型和视图返回
@RequestMapping("/s2")
public ModelAndView show2(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("hello");
modelAndView.addObject("username","xiaoming");
return modelAndView;
}
模型和视图注入返回
//模型和视图注入返回
@RequestMapping("/s3")
public ModelAndView show3(ModelAndView modelAndView){
modelAndView.setViewName("hello");
modelAndView.addObject("username","xiaogang");
return modelAndView;
}
模型返回
//模型返回
@RequestMapping("/s4")
public String show4(Model model){
model.addAttribute("username","xiaohong");
return "hello";
}
request方式返回
//request 方式返回
@RequestMapping("/s5")
public String show5(HttpServletRequest request){
request.setAttribute("username","xiaoxu");
return "hello";
}
response返回数据
//response返回数据
@RequestMapping("/s6")
public void show6(HttpServletResponse response) throws IOException {
response.getWriter().print("Hello World");
}
直接返回字符串非模板
//直接返回字符串非模板
@RequestMapping("/s7")
@ResponseBody
public String show7(){
return "xiaoming";
}
返回json数据
//直接json数据
@RequestMapping("/s8")
@ResponseBody
public String show8(){
return "{"username":"zhangsan","age":18}";
}
使用json包对象转json
com.fasterxml.jackson.core
jackson-core
2.9.0
com.fasterxml.jackson.core
jackson-databind
2.9.0
com.fasterxml.jackson.core
jackson-annotations
2.9.0
//使用json包对象转json
@RequestMapping("/s9")
@ResponseBody
public String show9() throws JsonProcessingException {
User user = new User();
user.setUsername("xiaoming");
user.setAge(23);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writevalueAsString(user);
return json;
}
使用spring容器方式进行返回json
//spring容器返回对象集合
@RequestMapping("/s10")
@ResponseBody
public User show10() {
User user = new User();
user.setUsername("xiaohong");
user.setAge(23);
return user;
}
- 在xml文件我们可以配置mvc注解驱动,可以默认去使用json包,不再去配置