SpringMVC主要有两种数据响应方式:页面跳转和数据回写
- 页面跳转:故名思意就是使请求方的页面进行跳转,有请求转发和重定向的方式
- 数据回写:类似JavaWeb学的resp.getWriter().print(),往页面中写入一些数据
一、页面跳转
页面跳转又分为两种方式:返回字符串的形式和返回ModelAndView的形式
1. 返回字符串的形式:
@RequestMapping(value = "/success")
public String success(){
return "redirect:/success.jsp"; // forward:表示请求转发,redirect:表示重定向
}
使用这种方式,客户端发到/success请求时,会进入这个success函数
这里返回的success.jsp就是在指定要跳转的视图
前缀加forward:表示以请求转发的方式跳转
前缀加redirect:表示以重定向的方式跳转
2. 返回ModelAndView对象的形式:
主要是通过modelAndView对象的addObject()方法来增加数据,用setViewName()方法来指定视图
@RequestMapping("/mav2")
public ModelAndView testMAV2(ModelAndView mav){
mav.addObject("username", "传参的ModelAndView");
mav.setViewName("/success.jsp");
return mav;
}
@RequestMapping("/mav")
public ModelAndView testMAV(){
ModelAndView mav = new ModelAndView();
mav.addObject("username", "LongXiaolan");
mav.setViewName("/success.jsp"); // 设置视图名称
return mav;
}
二、回写数据
1.直接返回字符串
1.1 通过JavaWeb学的resp.getWriter().write()方法:
但是这种方法需要使用到Servlet的参数,不利于解耦合,所以通常用1.2的加注解的方法。
@RequestMapping("/resp1")
public void testResponse(HttpServletResponse resp) throws IOException {
resp.setContentType("text/html;charset=UTF-8");
// resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("我通过HttpServletResponse resp.getWriter().write()方法写了这句话");
}
1.2 通过@ResponseBody告知SpringMVC,我需要的是回写字符串而不是页面跳转
@RequestMapping("/resp2")
@ResponseBody
public String testResponse2(){
return "通过ResponseBody注解告诉SpringMVC,我要回写数据而不是进行页面跳转。。。";
}
1.3 使用json的转换工具jackson将对象转换为字符串后再返回
首先要导入jackson的三个坐标:jackson-core, jackson-databind, jackson-annotations
@RequestMapping("/resp3")
@ResponseBody
public String testResponse3() throws JsonProcessingException {
User user = new User();
user.setUsername("LongXiaolan");
user.setAge(21);
// 使用json的转换工具jackson将对象转换成字符串再返回
ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(user);
return result;
}
1.4 实际上根本不需要像上面这么麻烦得去操作!!!
只需要在spring-mvc.xml中配置mvc的注解驱动:mvc:annotation-driven/
但是必须先引入mvc的命名空间,具体做法和引入context命名空间是一样的。
下面这段代码虽然是返回对象,但是mvc的注解驱动会自动把它转换成json数据格式的字符串:
@RequestMapping("/resp4")
@ResponseBody
public User testResponse4(){
User user = new User();
user.setUsername("LongXiaolan");
user.setAge(21);
return user;
}