Search code examples
javajspservletscookiesscriptlet

Deleting Java cookie in .JSP file


I'm using the following function to create a cookie which is set in a Java Servlet. I am trying to delete it in a scriptlet in a .JSP file. However it is not deleting the cookie, any ideas as to why?

This is the function that I am using to create the cookie in the Servlet:

    for(String classId :request.getParameterValues("classId")){
        optionCookie = new Cookie("componentSearchOptionSelect",classId);
        response.addCookie(optionCookie);
    }

This is the code I am using to delete the cookie in the scriptlet:

Cookie[] cookies = null;
        cookies = request.getCookies();
        if(cookies != null){
            for(int i = 0; i < cookies.length; i++){
                 Cookie cookie = cookies[i];
                 if(cookie.getName().equals("componentSearchOptionSelect")){

                     selectedClass = cookie.getValue();
                     cookie.setMaxAge(0);
                     response.addCookie(cookie);
                 }
             }
        }

Solution

  • JSP as being a view technology is responsible for generating the HTTP response body. Cookies have to go in the HTTP response headers. So if you put that cookie code halfway in a JSP and JSP has at that point already genrated that much of HTML which caused that the response is already committed, then it's simply too late to set a HTTP response header. The HTTP response headers have already been sent to the client, which is a point of no return. If you have paid attention to the server logs, then you should have noticed an IllegalStateException with a pretty self-explaining message and trace.

    So, to fix your problem, just make sure that you delete the cookie when the response isn't committed yet. Put the scriptlet containing all the business logic in the very top of the JSP page, long before the JSP writes anything to the HTTP response body.

    <%
        // Business logic here.
    %>
    <!DOCTYPE html>
    <html>
        ... (presentation logic here)
    </html>
    

    Actually, JSP is the wrong place to perform business logic (read: you should not be using scriptlets at all). You should be using a servlet or servlet filter for this. In your particular case, I think you just need a servlet with doGet() as demonstrated in Calling a servlet from JSP file on page load.