Spring MVC之数据响应
一、数据响应方式
1.页面跳转
直接返回字符串
无返回值void
通过ModelAndView对象返回
转发和重定向
2.回写数据
直接返回字符串
返回对象或集合
二、页面跳转
1.返回字符串
Controller方法返回字符串可以指定逻辑视图的名称,根据视图解析器为物理视图的地址。
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>Spring MVC success.jsp</h3>
</body>
</html>
@RequestMapping("/testString")
public String testString(Model model){
User user = new User();
user.setUsername("admin");
user.setPassword("123");
user.setAge(22);
model.addAttribute("user",user);
return "success";
}
@RequestMapping(value="/testString")
public String testString(HttpServletRequest request){
request.setAttribute("username","admin");
return "success";
}
2.无返回值void
如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到。例如请求是@RequestMapping(value=“/getUser”) ,则 默认会跳转到getUser.jsp页面。可以使用请求转发或者重定向跳转到指定的页面。
1 、使用 request 转向页面
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) {
// 使用 request 转向页面
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
return;
}
2.通过 response 页面重定向
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) {
// 通过 response 页面重定向
response.sendRedirect(request.getContextPath()+"/index.jsp");
return;
}
3.ModelAndView
ModelAndView对象是Spring提供的一个对象,可以用来调整具体的JSP视图
1.在Controller中方法返回ModelAndView对象,并且设置视图名称
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>Spring MVC success.jsp</h3>
${requestScope.username}
</body>
</html>
/**
* Model:模型 作用封装数据
* View:视图 作用展示数据
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
// 创建ModelAndView对象
ModelAndView mv = new ModelAndView();
User user = new User();
user.setUsername("admin");
user.setPassword("123");
user.setAge(22);
// 把user对象存储到mv对象中,也会把user对象存入到request对象
mv.addObject("user",user);
// 跳转页面
mv.setViewName("success");
return mv;
}
2.在Controller中方法形参上直接声明ModelAndView,无需在方法中自己创建,在方法中直接使用该对象设置视图,同样可以跳转页面。
@RequestMapping(value="/testModelAndView")
public ModelAndView save3(ModelAndView modelAndView){
modelAndView.addObject("username","admin");
modelAndView.setViewName("success");
return modelAndView;
}
4.转发和重定向
SpringMvc默认采用服务器内部转发的形式展示页面信息,同样也支持重定向页面。
forward 转发
controller方法在提供了String类型的返回值之后,默认就是请求转发。formward :路径必须写成实际视图 url,不能写逻辑视图。
相当于 request.getRequestDispatcher("/WEBINF/pages/success.jsp").forward(request,response);
使用请求转发,既可以转发到 jsp,也可以转发到其他的控制器方法。
@RequestMapping("/testForward")
public String testForward(){
// 请求的转发
return "forward:/WEB-INF/pages/success.jsp";
}
使用ModelAndView转发到视图
@RequestMapping("/testForward")
public ModelAndView testForward(RedirectAttributes attr){
ModelAndView mv=new ModelAndView();
mv.setViewName("index.jsp");
mv.addObject("username", "李白");
mv.addObject("age", "20");
return mv;
}
转发到controller,页面值获取: ${username}
、${age}
@RequestMapping("/testForward")
public ModelAndView testForward(HttpServletRequest request){
ModelAndView mv=new ModelAndView();
mv.setViewName("forward:user/test?username=李白&age=20");
return mv;
}
Redirect 重定向
contrller方法提供了一个 String类型返回值之后,它需要在返回值里使用:redirect:
相当于response.sendRedirect(request.getContextPath()+"/index.jsp");
如果是重定向到 jsp 页面,则 jsp 页面不能写在 WEB-INF 目录中,否则无法找到。
@RequestMapping("/testRedirect")
public String testRedirect(){
// 重定向到jsp,中文会出现乱码
return "redirect:/index.jsp?username=李白&age=20";
}
解决中文乱码解决
@RequestMapping("/testRedirect")
public String testRedirect(RedirectAttributes attr){
attr.addAttribute("username", "李白");
attr.addAttribute("age, "20");
return "redirect:index.jsp";
}
使用ModelAndView进行重定向
@RequestMapping("/testRedirect")
public ModelAndView testRedirect(RedirectAttributes attr){
ModelAndView mv=new ModelAndView();
attr.addAttribute("username", "李白");
attr.addAttribute("age, "20");
mv.setViewName("redirect:index.jsp");
return mv;
}
ModelAndView携带参数
@RequestMapping("/testRedirect")
public ModelAndView testRedirect(){
ModelAndView mv=new ModelAndView();
mv.setViewName("redirect:index.jsp");
mv.addObject("username", "李白");
mv.addObject("age", "20");
return mv;
}
重定向到Controller 并传递参数
@RequestMapping("/testRedirect")
public String testRedirect(RedirectAttributes attr){
attr.addAttribute("username", "李白");
attr.addAttribute("age, "20");
return "redirect:/user/test";
}
重定向到Controller的modelandview,重定向页面值获取: ${param.username}
、${param.age}
@RequestMapping("/testRedirect")
public ModelAndView testRedirect(RedirectAttributes attr){
ModelAndView mv=new ModelAndView();
mv.setViewName("redirect:/user/test");
mv.addObject("username", "李白");
mv.addObject("age", "20");
return mv;
}
三、数据回写
1.直接返回字符串
通过 response 指定响应结果
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 设置中文乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 通过 response 指定响应结果
response.getWriter().print("spring mvc");
return;
}
2.ResponseBody响应json数据
1.手动拼接json格式字符串返回。
@RequestMapping(value="/testResponseBody")
@ResponseBody
public String testResponseBody() {
return "{\"username\":\"admin\",\"age\":22}";
}
2.@RequestBody注解
json字符串和JavaBean对象互相转换的过程中,需要使用jackson的jar包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.10.3</version>
</dependency>
使用@RequestBody注解把json的字符串转换成JavaBean的对象
使用@ResponseBody注解把JavaBean对象转换成json字符串,直接响应
使用 <mvc:annotation-driven />注解驱动 默认底层就会集成jackson进行对象或集合的json格式字符串的转换
@RequestMapping("/testResponseBody")
@ResponseBody
public User testResponseBody(@RequestBody User user){
// 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
System.out.println(user);
// 做响应,将user对象转成json响应
return user;
}
如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器
<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>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137120.html