传统Servlet响应方式
在方法中注入HttpServletRequest、HttpServletResponse、HttpSession对象来共享数据和响应页面。
@RequestMapping("/method1")
public void method1(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("username", "brick");
req.getRequestDispatcher("/WEB-INF/response/response.jsp").forward(req, resp);
}
访问地址: http://localhost:8080/springmvc/response/method1.do
ModelAndView方式
SpringMVC提供的第一种方式:使用ModelAndView对象。
–数据共享:ModelAndView对象的addObject(attrName, attrValue)方法。
–页面跳转:ModelAndView对象的setViewName(uri)方法。
注意事项:ModelAndView方式,默认页面跳转方式是请求转发。
@RequestMapping("/method2")
public ModelAndView method2() {
ModelAndView mv = new ModelAndView();
mv.addObject("username", "brick");
mv.setViewName("/WEB-INF/response/response.jsp");
return mv;
}
访问地址: http://localhost:8080/springmvc/response/method2.do
Model方式
SpringMVC提供了Model对象用于数据共享和页面跳转。Model对象可以直接通过方法参数的形式获取。
–数据共享:Model对象的方法addAttribute(attrName, attrValue)。
–页面跳转:方法的返回值。
注事事项:Model方式,默认页面跳转方式也是请求转发,但是可以设置为重定向。
@RequestMapping("/method3")
public String method3(Model m) {
m.addAttribute("username", "brick");
return "/WEB-INF/response/response.jsp";
}
Model方式的重定向
前面介绍的三种方式中:注入Servlet原生对象方式和ModelAndView方法都只能是请求转发,但是唯有Model方式既可以是请求转发,又可以是重定向,所以说很有必要来研究一下Model方法如何实现重定向。
首先,我们要请求,SpringMVC是如何解释视图路径的,这时我们需要去看下ViewResolver的实现类UrlBasedViewResolver,源码中有一下两句代码:
/**
* Prefix for special view names that specify a redirect URL (usually
* to a controller after a form has been submitted and processed).
* Such view names will not be resolved in the configured default
* way but rather be treated as special shortcut.
*/
public static final String REDIRECT_URL_PREFIX = "redirect:";
/**
* Prefix for special view names that specify a forward URL (usually
* to a controller after a form has been submitted and processed).
* Such view names will not be resolved in the configured default
* way but rather be treated as special shortcut.
*/
public static final String FORWARD_URL_PREFIX = "forward:";
通过注释的意思,我们可以知道只要在返回的uri路径前加上“redirect”,就代表重定向,加上“forward”,就代表请求转发。
案例代码
–自定义请求转发页面跳转的地址 : forward: 跳转的地址
@RequestMapping("/method4")
public String method4(Model m) {
m.addAttribute("username", "brick");
return "forward:/WEB-INF/views/index.jsp";
}
–自定义重定向页面跳转的地址 redirect: 跳转的地址
@RequestMapping("/method5")
public String method5(Model m) {
m.addAttribute("username", "brick");
return "redirect:http://www.jd.com";
}
–注意事项:WEB-INF目录下的资源,只能通过请求转发访问!!!
配置视图解析器
我们发现,在跳转页面的uri中,在某些情况下(根据实际需求),有些部分是重复不变的,如:“/WEB-INF/response”、“xxx.jsp”,那么我们是否可以避免掉这些重复冗余的代码呢?
答:配置视图解析器。
代码分析图
视图解析器的配置
<!-- 配置SpringMVC的视图解析器: 配置前缀和后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置视图跳转的前缀 -->
<property name="prefix" value="/WEB-INF/response/"/>
<!-- 配置视图跳转的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
配置视图解析器后的代码
Controller方法返回字符串表示逻辑视图名,通过视图解析器解析为物理视图地址。
此时默认的物理视图地址为:视图前缀+返回值+视图后缀。
@RequestMapping("/method2")
public ModelAndView method2() {
ModelAndView mv = new ModelAndView();
mv.addObject("username", "brick");
//没有配置视图解析器之前的写法
//mv.setViewName("/WEB-INF/response/response.jsp");
//配置视图解析器之后的写法
mv.setViewName("response");
return mv;
}
-----------------------------------------------------------------
@RequestMapping("/method3")
public String method3(Model m) {
m.addAttribute("username", "brick");
return "response";
}
注意:配置完视图解析器以后,必须保证,前缀目录下面必须有对应逻辑视图名称所在的页面,否则可能会报404错误。
Pojo方式
方法不返回ModelAndView也不返回String类型对应的逻辑视图名称,而是直接返回一个Pojo对象。
–数据共享:使用SpringMVC提供的@ModelAttribute注解。
–页面跳转:使用这种方式必须要求项目配置了视图解析器InternalResourceViewResolver,并且借助@RequestMapping注解来确定页面uri。
–@ModelAttribute作用如下:
1、设置请求参数绑定到Model对象中并传到视图页面的key名。
2、将共享数据绑定到Model对象中并传到视图页面。
代码分析图
转换JSON数据
在web开发中,前台页面经常会发送ajax请求到后台请求数据,ajax请求给前台的数据一般都是json 数据。
SpringMVC支持自动将对象转换JSON格式的数据响应给客户端。
SpringMVC默认使用的是 jackson作为对象转json的工具。
转换步骤
–开启MVC高级功能(支持json)需要开启MVC注解驱动。
< mvc:annotation-driven/>
–导入jackson的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
–标注@ResponseBody到JSON转换的方法上
@Controller
public class JsonController {
@RequestMapping("/getUserJson")
@ResponseBody //把响应的内容设为普通字符串
public User getUserJson() {
User user = new User();
user.setUsername("东方姑娘");
user.setPassword("dfgn");
user.setEmail("dfgn@qq.com");
user.setPhone("234234234324");
return user;
}
@RequestMapping("/getUserJsonList")
@ResponseBody
public List<User> getUserJsonList() {
User user = new User();
user.setUsername("东方姑娘");
user.setPassword("dfgn");
user.setEmail("dfgn@qq.com");
user.setPhone("234234234324");
List<User> list = new ArrayList<>();
list.add(user);
list.add(user);
list.add(user);
list.add(user);
return list;
}
}
–注意事项:Ajax请求,仅仅只是请求数据,无需指定跳转页面,所以我们只需返回一个对象或者集合,接着使用在方法上标注@ResponseBody注解,SpringMVC就是自动的帮我们将对象或者集合转换为JSON字符串返回给ajax请求方。