Set cookie in every request - SPRING

Viewed 2628

Im now developing simple spring boot web app.. Is there something in spring(filter) that check every request(headers).. I want to check if there is cookie.. If there is cookie- nothing happend.. But if there is not it would create cookie... Do i have to do this manually, so i put this in every function? Or can i do something like global function, that got executed with every other request?

Thanks for help.

1 Answers

yes you have to use filters you can try doing something like this

public class MyCookieFilter extends GenericFilterBean {

    public static final String MY_COOKIE_NAME = "your-cookie-name";


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        checkCookie(httpServletRequest, httpServletResponse);

        filterChain.doFilter(servletRequest, servletResponse);
    }

    private void checkCookie(HttpServletRequest request, HttpServletResponse servletResponse) {
        boolean cookieExists = Arrays.stream(request.getCookies()).anyMatch(cookie -> cookie.getName().equalsIgnoreCase(MY_COOKIE_NAME));
        if (!cookieExists) {
            String cookieValue = "your-cookie-value";
            Cookie newCookie = new Cookie(MY_COOKIE_NAME, cookieValue);
            servletResponse.addCookie(newCookie);
        }
    }
}

then add it in your security config

    @Override
    public void configure(HttpSecurity http) throws Exception {
    http
     ...
       .addFilter(new MyCookieFilter())
     ...
    }
Related