我想创建一个在我的任何spring mvc控制器操作之前执行的过滤器.
我想检查cookie的存在,然后只为当前请求存储一个对象.
然后我需要从我的控制器动作中引用这个对象(如果它存在).
关于如何做到这一点的建议?
最佳答案
创建过滤器只是创建一个实现javax.servlet.Filter的类,在你的情况下可以是这样的
原文链接:https://www.f2er.com/spring/431630.htmlpublic class CookieFilter implements Filter {
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException {
HttpServletRequest request = (HttpServletRequest) req;
Cookie[] cookies = request.getCookies();
if (cookies != null){
for (Cookie ck : cookies) {
if ("nameOfMyCookie".equals(ck.getName())) {
// read the cookie etc,etc
// ....
// set an object in the current request
request.setAttribute("myCoolObject",myObject)
}
}
chain.doFilter(request,res);
}
public void init(FilterConfig config) throws ServletException {
// some initialization code called when the filter is loaded
}
public void destroy() {
// executed when the filter is unloaded
}
}
然后在web.xml中声明过滤器
此时在您的控制器中,只需使用request.getAttribute(“myCoolObject”)检查请求中是否存在attibute