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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With