You want to create a filter to check the cookie, and then save the object and link from the controllers

I want to create a filter that will be executed before any of my mwc spring controller actions.

I want to check for a cookie, and then save the object somewhere just for the current request.

Then I need to reference this object (if it exists) from my action with the controller.

Suggestions on how to do this?

+4
source share
1 answer

to create a filter, just create a class that implements javax.servlet.Filter, in your case there might 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 a 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 on your controller just check if attutute exists in the request using request.getAttribute ("myCoolObject")

+11
source

Source: https://habr.com/ru/post/1395524/


All Articles