java-springmvc4-几种获取 HttpServletRequest 对象的方式
以下的 request 实例都编号了,一共 4 种 方式
1.@Autowired 方式
2.public void Test(HttpServletRequest request1, HttpServletResponse resp,HttpSession session1) 方式
3.((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 方式
4.Global.getHttpServletRequest(); 方式,该方式基于 第三种做的封装
方法4 最灵活,不需要每个 action 中都定义 HttpServletRequest 参数。
LoginController.java
@Controller
@RequestMapping("/demo")
public class LoginController{
@Autowired
private HttpServletRequest request2;
@RequestMapping("test")
@ResponseBody
public void Test(HttpServletRequest request1, HttpServletResponse resp,HttpSession session1){
resp.setCharacterEncoding("UTF=8");
resp.setContentType("text/html;charset=UTF-8");
String key = "test_date";
HttpSession session = request1.getSession();
session.setAttribute(key, new Date());
String sessionId = session.getId();
Date time = (Date)session.getAttribute(key);
HttpServletRequest request3 = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletRequest request4 = Global.getHttpServletRequest();
//判断session是不是新创建的
try {
if (session.isNew()) {
resp.getWriter().print(java.text.MessageFormat.format(
"【{0}】session创建成功,session的id是:</br>{1}</br>{2}</br>{3}</br>{4}</br>{5}"
, StringExtend.getString(time)
, sessionId
, session1.getId()
, request2.getSession().getId()
, request3.getSession().getId()
, request4.getSession().getId()));
}else {
resp.getWriter().print(java.text.MessageFormat.format(
"【{0}】服务器已经存在该session了,session的id是:</br>{1}</br>{2}</br>{3}</br>{4}</br>{5}"
, StringExtend.getString(time)
, sessionId
, session1.getId()
, request2.getSession().getId()
, request3.getSession().getId()
, request4.getSession().getId()));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Global.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 使用该类必须在 web.xml 中添加监听(org.springframework.web.context.request.RequestContextListener)
* 该作用域仅适用于WebApplicationContext环境
*/
public class Global {
static String _loginSessionKey="login_session";
/**
* 获取当前请求session
* @return
*/
public static HttpServletRequest getHttpServletRequest(){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder
.getRequestAttributes())
.getRequest();
return request;
}
/**
* 获取当前请求session
* @return
*/
public static HttpSession getHttpSession(){
return getHttpServletRequest().getSession();
}
}
web.xml 加入监听
<!-- 5. spring 注册监听,获取上下文中的 HttpServletRequest 对象(对 Global 支持) -->
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>