目录
SpringMVC的数据响应方式
1)页面跳转
- 直接返回字符串:此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转。
- 通过ModelAndView对象返回
@RequestMapping("/quick2")
public ModelAndView quickMethod2(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:index.jsp");
return modelAndView;
}
@RequestMapping("/quick3")
public ModelAndView quickMethod3(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
return modelAndView;
}
在进行转发时,往往要向request域中存储数据,在jsp页面中显示,那么Controller中怎样向request 域中存储数据呢?
@RequestMapping("/quick")
public String quickMethod(HttpServletRequest request){
request.setAttribute("name","zhangsan");
return "index";
}
@RequestMapping("/quick3")
public ModelAndView quickMethod3(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/WEB-INF/views/index.jsp");
modelAndView.addObject("name","lisi");
return modelAndView;
}
2)回写数据
- 直接返回字符串:Web基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要使用response.getWriter().print(“hello world”) 即可,那么在Controller中想直接回写字符串该怎样呢?
@RequestMapping("/quick4")
public void quickMethod4(HttpServletResponse response) throws IOException {
response.getWriter().print("hello world");
}
@RequestMapping("/quick5")
@ResponseBody
public String quickMethod5() throws IOException {
return "hello springMVC!!!";
}
1.在pom.xml中导入jackson坐标。
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
2.通过jackson转换json格式字符串,回写字符串。
@RequestMapping("/quick7")
@ResponseBody
public String quickMethod7() throws IOException {
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
return s;
}
-
返回对象或集合
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
@RequestMapping("/quick8")
@ResponseBody
public User quickMethod8() throws IOException {
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
return user;
}
3)配置注解驱动
<!--在spring-mvc.xml中配置mvc的注解驱动-->
<mvc:annotation-driven/>
4)知识要点
SpringMVC的数据响应方式
1) 页面跳转
直接返回字符串
通过ModelAndView对象返回
2) 回写数据
直接返回字符串
返回对象或集合