直接返回字符串方式:此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转。
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running ...");
return "success";
}
@RequestMapping("/quick2")
public ModelAndView save2(){
// model:模型,封装数据
// view:视图,展示数据
ModelAndView modelAndView = new ModelAndView();
// 设置模型数据
modelAndView.addObject("username","itcast");
// 设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping("/quick3")
public ModelAndView save3(ModelAndView modelAndView){
// 设置模型数据
modelAndView.addObject("username","itcast");
// 设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
@RequestMapping("/quick4")
public String save4(Model model){
model.addAttribute("suername","博学谷");
return "success";
}
@RequestMapping("/quick5")
public String save5(HttpServletRequest request){
request.setAttribute("username","库定义");
return "success";
}
@RequestMapping("/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().println("hello speingMVC");
}
@RequestMapping("/quick7")
@ResponseBody//告知springMVC不是视图跳转,直接进行数据相应
public String save7() throws IOException {
return "hello speingMVC";
}
@RequestMapping("/quick8")
@ResponseBody//告知springMVC不是视图跳转,直接进行数据相应
public String save8() throws IOException {
return "{usernmae:\"zhanghan\"}";
}
com.fasterxml.jackson.core
jackson-core
2.11.0
com.fasterxml.jackson.core
jackson-databind
2.11.0
com.fasterxml.jackson.core
jackson-annotations
2.11.0
代码
@RequestMapping("/quick9")
@ResponseBody//告知springMVC不是视图跳转,直接进行数据相应
public String save9() throws IOException {
User user = new User();
user.setUsername("liliang");
user.setAge(20);
// 使用json转化工具转化成为json格式字符串
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}
@RequestMapping("/quick10")
@ResponseBody//告知springMVC不是视图跳转,直接进行数据相应
// 期望SpringMVC自动将User转化为json格式
public User save10() throws IOException {
User user = new User();
user.setUsername("liliang");
user.setAge(20);
return user;
}