springmvc 得到HttpServletRequest、HttpServletResponse、HttpSession
正常情况下,springmvc的controller就已经满足需求了,但是,最近在做一个验证是否登录的功能。在制作的过程中使用了spring的aop,本来是想采用filter的,但是filter在控制上,不是特别的灵活。所以还是采用aop的方式。
下面说一下遇到的问题,就是在正常的页面跳转的时候,由于代码的分层结构,需要在serviceImpl层进行Session的添加处理,同时,最开始制作的时候想使用切面中直接利用response返回的方式,仍然需要方便的使用response。
在网上查了一圈,发现下面的这种方式个人觉得比较优雅。当然,这种方式是借用struts1的思想。好了,下面上货:
1、首先定义一个类,用户获取HttpServletRequest、HttpServletResponse和HttpSession。
2、
2、新建一个filter
package com.xueyou.ssm.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Created by wuxueyou on 16/10/2.
*/
public class SysContent {
private static ThreadLocal<HttpServletRequest> requestLocal = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>();
public static HttpServletRequest getRequest() {
return (HttpServletRequest) requestLocal.get();
}
public static void setRequest(HttpServletRequest request) {
requestLocal.set(request);
}
public static HttpServletResponse getResponse() {
return (HttpServletResponse) responseLocal.get();
}
public static void setResponse(HttpServletResponse response) {
responseLocal.set(response);
}
public static HttpSession getSession() {
return (HttpSession) ((HttpServletRequest) requestLocal.get()).getSession();
}
}
2、新建一个filter
package com.xueyou.ssm.utils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by wuxueyou on 16/10/2.
*/
@WebFilter(filterName = "GetContent")
public class GetContent implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
SysContent.setRequest((HttpServletRequest)req);
SysContent.setResponse((HttpServletResponse)resp);
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
3、在web.xml中配置这个filter
<filter>
<filter-name>getContent</filter-name>
<filter-class>com.xueyou.ssm.utils.GetContent</filter-class>
</filter>
<filter-mapping>
<filter-name>getContent</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4、下面是使用HttpSession
HttpSession session = SysContent.getSession();
session.setAttribute("username",params.get("username").toString());
session.setAttribute("password",params.get("password").toString());
总结一下这样做的好处,其实springmvc有自己的HttpServletRequest和HttpServletResponse。但是,软件分层之后,不能再controller层得到的Session放在参数里一直传下去吧。所以,这样直接保存一下 HttpServletRequest、HttpServletResponse和HttpSession相对来讲还是很划算的。