之前的博客介绍了搭建一个基本的springmvc运行环境:
搭建springmvc项目之HelloWorld
下面介绍处理器向页面返回数据的几种方法
使用ModelAndView
- 处理器
package com.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/helloWorld")
public class HelloWorldController {
@RequestMapping("/sayHello.do")
public ModelAndView sayHello(){
ModelAndView mav = new ModelAndView("success");
mav.addObject("name", "小明");
return mav;
}
}
- 首先new一个ModelAndView实例并指定返回的页面名称
- 然后使用addObject()设置需要像页面传输的数据
- 前台可以通过EL表达式${name}获取数据
- success.jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>访问成功!</h1>
<h2>helloWorld!我的名字叫:${name}</h2>
</body>
</html>
- 测试页面 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="helloWorld/sayHello.do">HelloWorld!</a>
</body>
</html>
使用Model
相同代码省略…
@RequestMapping("/sayHello.do")
public String sayHello(Model model){
model.addAttribute("name", "小明");
return "success";
}
- 设置一个Model方法参数,使用addAttribute设置要传输的数据。
- 返回值就是页面名称。
- 这种方式比较常用
使用Map
相同代码省略…
@RequestMapping("/sayHello.do")
public String sayHello(Map map){
map.put("name", "小明");
return "success";
}
- 设置一个Map方法参数,使用put设置要传输的数据。
- 返回值就是页面名称。
向request中直接设置值
相同代码省略…
@RequestMapping("/sayHello.do")
public String sayHello(HttpServletRequest request){
request.setAttribute("name", "小明");
return "success";
}
上面提供了四种方法: ①ModelAndView ② Model ③Map ④通常用的request方法
前三种是spring封装的,其本质还是request方法
原理:
当处理器处理完请求后,将视图名放入ModelAndView的view属性中,将数据放入ModelAndView的model属性中。然后将这个ModelAndView交给前端控制器DispartcherServlet,前端控制器根据配置的ViewResolver解析这个ModelAndView:
- 取出页面名称,根据配置定位页面资源。
- 然后将model中的数据放入request中,然后使用request.getRequestDispatcher(“xxx.jsp”).forward(request,
response); 跳转到相应的页面。