1.页面跳转
返回字符串形式:
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
返回ModelAndView对象:
@RequestMapping(value="/quick2")
public ModelAndView save2(){
//Model:模型,作用是封装数据
//View:视图,作用是展示数据
ModelAndView modelAndView=new ModelAndView();
//设置模型数据
modelAndView.addObject("username","itcast");
//设置视图:
modelAndView.setViewName("success");
return modelAndView;
}
<body>
<h1>Success!${username}</h1>
</body>
页面显示:
Success!itcast
方式2:
@RequestMapping(value="/quick3")
public ModelAndView save3(ModelAndView modelAndView){
modelAndView.addObject("username","heima");
modelAndView.setViewName("success");
return modelAndView;
}
页面显示:
Success!heima
方式3:
@RequestMapping(value="/quick4")
public String save4(Model model){
model.addAttribute("username","wowo");
return "success";
}
方法4:
@RequestMapping(value="/quick5")
public String save5(HttpServletRequest request){
request.setAttribute("username","haha");
return "success";
}
2.回写数据
方式一:
@RequestMapping(value="/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().print("hello ticast");
}
方式二:
@RequestMapping(value="/quick7")
@ResponseBody
public String save7() throws IOException {
return "hello ticast";
}
注:
@ResponseBody解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回。
方式三:
@RequestMapping(value="/quick8")
@ResponseBody
public String save8() throws IOException {
return "{\"username\":\"zhangsan\",\"age\":18}";
}
改进:
@RequestMapping(value="/quick9")
@ResponseBody
public String save9() throws IOException {
User user=new User();
user.setUsername("lisi");
user.setAge(18);
//使用json转换工具将对象转换为json格式字符串在返回
ObjectMapper objectMapper=new ObjectMapper();
String json=objectMapper.writeValueAsString(user);
return json;
}
方式四:返回对象和集合
spring-mvc.xml中加入如下配置:
<!--配置处理器映射器
-->
<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>
上述配置可用以下注解代替:
<!--mvc的注解驱动-->
<mvc:annotation-driven/>
@RequestMapping(value="/quick10")
@ResponseBody
//期望Springmvc自动将user转换为json格式的字符串
public User save10() throws IOException {
User user=new User();
user.setUsername("lisi");
user.setAge(18);
return user;
}