1)页面跳转
直接返回字符串

通过ModelAndView对象返回
//方式三(model和view拆开)
@RequestMapping("/quick4")
public String save4(Model model){
model.addAttribute("username","lisi3");
return "success";
}
//方式二
@RequestMapping("/quick3")
public ModelAndView save3(ModelAndView modelAndView){
modelAndView.addObject("username","lisi2");
modelAndView.setViewName("success");
return modelAndView;
}
//方式一
@RequestMapping("/quick2")
public ModelAndView save2(){
/*
* Model: 模型 作用为封装数据
* View: 视图 作用为展示数据
* */
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","lisi");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
2)回写数据
直接返回字符串
Web基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要使用response.getWriter0).print("hello world")即可,那么在Controller中想直接回写字符串该怎样呢?
① 通过SpringMVC框架注入的response对象,使用response.getWriter0.print("hello world")回写数
据,此时不需要视图跳转,业务方法返回值为void。
② 将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回。
//回写数据(解耦)
@RequestMapping("/quick7")
@ResponseBody//告诉SPring框架, 不进行视图跳转, 直接进行数据响应
public String save7() throws IOException {
return "hello,SpringMVC";
}
//回写数据
@RequestMapping("/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().print("hello,SpringMVC");
}
回写json格式字符串
@RequestMapping("/quick8")
@ResponseBody//告诉SPring框架, 不进行视图跳转, 直接进行数据响应
public String save8() throws IOException {
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
//使用json转换工具将对象转换成json字符串在进行返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
//手写json不切实际
//return "{\"username\":\"zhangsan\",\"age\":18}";
}
//简写
@RequestMapping("/quick9")
@ResponseBody//告诉SPring框架, 不进行视图跳转, 直接进行数据响应
public User save9() throws IOException {
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
return user;
}
<!-- 配置处理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
返回对象或集合
在方法上添加@ResponseBody就可以返回json格式的字符串,但是这样配置比较麻烦,配置的代码比较多因此,我们可以使用mvc的注解驱动代替上述配置,