一、 通过Request.setAttribute("key","vlaue")
@RequestMapping(value="showUserInfo" ) public String showUserInfo(User user , HttpServletRequest req ) { req.setAttribute("user",user.toString()); System.out.println(user.toString()); return "index.jsp"; }
视图端调用方法 ${user}
二、Model
/***
* 通过model 方式向视图页面传递值
* @param model
* @return
*/
@RequestMapping("/model")
public String sentValue(Model model)
{
model.addAttribute("user","model传值");
return "index";
}
三、ModelMap
/***
* 通过ModelMap传值
* @param mm
* @return
*/
@RequestMapping("/ModelMap")
public String ModelMap(ModelMap mm)
{
mm.addAttribute("user","ModelMap传值");
return "index";
}
四、map 传值
/***
* map 传值
* @param map
* @return
*/
@RequestMapping("/map")
public String map(Map map)
{
map.put("user" ,"map传值 123");
return "index";
}
五、ModelView
@RequestMapping("/modelandview")
public ModelAndView modelandview()
{
ModelAndView mv=new ModelAndView("index");// 1.指定视图第一种方式
mv.setViewName("index" );//或者 通过 setviewName 指定视图第二种方式
mv.addObject("user" ,"modelandView 传值 ");
return mv;
}
六、Session
@RequestMapping("/session")
public String session( HttpServletRequest req)
{
req.getSession().setAttribute("user"," session 传值!!");
return "index";
}
或
@RequestMapping("/session01")
public String session01( HttpSession session)
{
session.setAttribute("user"," session 传值!!");
return "index";
}
七,页面调用3种方式
<textarea> ${user} <!-- request session 都可以 --> </textarea>
<div>
${requestScope.user}
</div>
获取session 数据 用
<div>
${sessionScope.user} 或者 ${user}
</div>
八、@SessionAttributes("user") 作用
主要从model 找 key 为user 的值 并拷贝一份存入session
如: 建立HomeController
@SessionAttributes("key") @Controller public class HomeController { @RequestMapping("/main") public String main( Model m) { m.addAttribute("key","计算机"); return "Home"; } }
Home.jsp页面
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>Title</title> 5 </head> 6 <body> 7 session中 key 值::${sessionScope.key} 8 </body> 9 </html>
结果 session中 key 值:: 计算机