首先看一下如何获得request对象、session对象:
普通的Controller类,示例代码如下:
@Controller @RequestMapping(value = "user") public class UserController { @RequestMapping(value = "/reg2") public String reg2(String uname,HttpServletRequest req,ModelMap map){ req.setAttribute("a", "aa"); req.getSession().setAttribute("b", "bb"); return "index"; } }
ModelMap:
是map的实现,可以在其中存放属性,作用域同request。下面这个示例,我们可以在modelMap中放入数据,然后在forward的页面上显示这些数据。
通过el表达式、JSTL、java代码均可。
代码如下:
package com.sxt.web; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; @Controller @RequestMapping(value = "user") public class UserController extends MultiActionController { @RequestMapping(value = "/reg") public String reg(String uname,ModelMap map){ map.put("a", "aaa"); return "index"; } }
JSP页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head></head> <body> <h1>${requestScope.a}</h1> <c:out value="${requestScope.a}"></c:out> </body> </html>
请求转发和重定向:
package com.sxt.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @RequestMapping(value = "user") public class UserController { @RequestMapping(value = "/reg4") public String reg4(ModelMap map) { System.out.println("HelloController.handleRequest()"); // return "forward:index.jsp"; // return "forward:user.do?method=reg5"; //转发 // return "redirect:user.do?method=reg5"; //重定向 return "redirect:http://www.baidu.com"; //重定向 } @RequestMapping(value = "/reg5") public String reg5(@RequestParam("uname") String uname,ModelMap map) { System.out.println("HelloController.handleRequest()"); System.out.println(uname); return "index"; } }
这样如果是请求转发(forward)的话传值可以用request和modelMap传递。