Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to create a filter to check for a cookie, then save object and reference from controllers

I want to create a filter that will execute before any of my spring mvc controller actions.

I want to check for the existence of a cookie, and then store an object somewhere for the current request only.

I then need to reference this object (if it exists) from within my controller action.

Suggestions on how to do this?

like image 789
Blankman Avatar asked Feb 09 '12 00:02

Blankman


1 Answers

to create the filter just make a class that implements javax.servlet.Filter, in your case can be something like this

public 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
    }
}

then declare the filter in your web.xml

<filter>
    <filter-name>CookieFilter</filter-name>
    <filter-class>
        my.package.CookieFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>CookieFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

at this point in your controller just check if the attibute exists in the request using request.getAttribute("myCoolObject")

like image 170
Daniel Camarda Avatar answered Oct 11 '22 13:10

Daniel Camarda