How do I create a servlet filter to make secure cookies?

The CookieFilter class in this example is a servlet filter. Servlet filters in Java web applications are used to perform tasks such as request/response modification, authentication, logging, and more. In the context of managing cookies, a CookieFilter can be used to intercept requests and responses to handle cookie-related operations, such as setting secure attributes on cookies or checking cookie values for authentication purposes.

Here’s an example of how you can implement a CookieFilter class in Java:

package org.kodejava.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class CookieFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code, if needed
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // Check if a session exists
        HttpSession session = httpRequest.getSession(false);
        if (session != null) {
            // Example: Set secure attribute on session cookie
            sessionCookieSecure(httpRequest, httpResponse);
        }

        // Continue the request chain
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }

    private void sessionCookieSecure(HttpServletRequest request, HttpServletResponse response) {
        // Assuming the session cookie name
        String cookieName = "JSESSIONID"; 
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    // Set the secure attribute on the session cookie
                    cookie.setSecure(true);
                    // Update the cookie in the response
                    response.addCookie(cookie); 
                    break;
                }
            }
        }
    }
}

In this example:

  • The CookieFilter class implements the Filter interface, which requires implementing methods like init, doFilter, and destroy.
  • Inside the doFilter method, it checks if a session exists for the incoming request.
  • If a session exists, it calls the sessionCookieSecure method to set the secure attribute on the session cookie.
  • The sessionCookieSecure method iterates through cookies in the request, finds the session cookie (e.g., JSESSIONID), and sets its secure attribute to true.

You can modify this filter implementation based on your specific cookie management requirements, such as setting secure attributes on specific cookies or performing additional cookie-related tasks.

How do I configure secure cookies using web.xml?

To configure secure cookies using web.xml, you typically need to set the secure attribute on your cookie definitions. This ensures that the cookie is only sent over HTTPS connections, enhancing security by protecting sensitive information from being transmitted over unencrypted channels. Here’s how you can do it:

1. Define Your Servlet Filter (Optional but Recommended):

If you don’t have a servlet filter for managing cookies, you can create one. This filter can intercept requests and responses to handle cookie-related operations.

<filter>
    <filter-name>CookieFilter</filter-name>
    <filter-class>org.kodejava.servlet.CookieFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CookieFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Replace org.kodejava.servlet.CookieFilter with the actual class that implements your cookie handling logic.

2. Configure Secure Cookie in web.xml:

Inside your web.xml, you can define cookie configurations using <session-config> and <cookie-config> elements.

<session-config>
   <cookie-config>
      <!-- Recommended to prevent client-side script access -->
      <http-only>true</http-only>
      <!-- Set all cookies to be secure -->
      <secure>true</secure>
    </cookie-config>
</session-config>
  • <secure>true</secure>: This line ensures that all cookies are marked as secure, meaning they will only be sent over HTTPS connections.
  • <http-only>true</http-only>: This line makes cookies accessible only through HTTP headers, preventing client-side scripts (like JavaScript) from accessing them. It adds another layer of security against certain types of attacks.

3. Deploy and Test:

After making these changes, deploy your web application and test it over HTTPS. Verify that cookies are being set with the secure flag by checking your browser’s developer tools (usually under the “Application” or “Storage” tab).

By following these steps, you can configure secure cookies in your Java web application using web.xml.

Notes: Setting the secure attribute in web.xml configures the default behavior for cookies created by the servlet container. However, for custom cookies that your application creates programmatically, you need to explicitly call setSecure(true) on the Cookie object to make them secure.

How to create JSP error page to handle exceptions?

In this example you will learn how to handle exceptions in JSP page. JSP have a build-in mechanism for error handling which is a special page that can be used to handle every error in the web application. To define a page as an error page we use the page directive and enable the isErrorPage attribute by setting the value to true.

Here is an example of a JSP error page:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Error Page</title>
</head>
<body>
<h1>An error has occurred.</h1>

<div style="color: #F00;">
    Error message: <%= exception.toString() %>
</div>
</body>
</html>

We have defined the error page. The next steps is how to tell other JSP pages to use the error page to handle errors when uncaught exception occurred. To do this we again use the page directive. Set the errorPage attribute of this directive to point to the error page. For instance in the example below we set it to errorPage.jsp.

If we try to access the errorTest.jsp as shown in the snippet below. It will throw an exception because we try to convert an invalid string into a number. Because we are not handling the error in the page the error page will come up and show the exception messages.

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ page errorPage="/errorPage.jsp" %>
<html lang="en">
<head>
    <title>My Sample Page</title>
</head>
<body>
<h1>This page throws an error:</h1>

<%
    int number = Integer.parseInt("Hello, World!");
%>
</body>
</html>
JSP Error Page Demo

JSP Error Page Demo

How to include page dynamically in JSP page?

In this example we are going to learn how to use <jsp:include> action. This action can be used to include resource dynamically to our JSP pages. For example the resource can be another JSP page, a servlet or event a static html pages. But to make it enable to be processed as a JSP page, such as accepting parameters, we must use the .jsp as the file extension. If we use other extension such as .jspf, it will be processed as a static page.

The other things to note is that using the <jsp:include> action will process the page inclusion at the request time. This is why we can pass parameters to the included page using the <jsp:param>. The value can be read by obtaining the parameter from the request object or using expression language variable param.

But if we use the <%@ include %> directive the inclusion of the page happen when it translated into a Servlet. See the following example about the <%@ include %> directive: How do I include a page fragment into JSP?

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Include Demo</title>
</head>
<body>

Lorem Ipsum

<jsp:include page="jspf/footer.jsp">
    <jsp:param name="year" value="2021"/>
</jsp:include>

</body>
</html>

Below is the content of our footer.jsp page. In this page we display the footer information with a parameter read from the request object.

<%@ page contentType="text/html;charset=UTF-8" %>
<hr/>
Copyright © ${param["year"]} Kodejava.org. All rights reserved.

This example will give you the following result in the browser:

JSP Include Action Demo

JSP Include Action Demo

How do I forward request to another page in JSP?

To forward a request from one page to another JSP page we can use the <jsp:forward> action. This action has a page attribute where we can specify the target page of the forward action. If we want to pass parameter to another page we can include a <jsp:param> in the forward action. But make sure that the forward page is a JSP page to enable the parameters to be processed.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Forward Demo</title>
</head>
<body>

<jsp:forward page="message.jsp">
    <jsp:param name="message" value="Welcome!"/>
</jsp:forward>

</body>
</html>

And here is how to read the parameters in the message.jsp.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Message: ${param["message"]}</title>
</head>
<body>
Message: ${param["message"]}
</body>
</html>
jsp:forward Demo

jsp:forward Demo

When you access the jspForward.jsp page in the web browser what you will see is the content of the message.jsp page. This is because the <jsp:forward> action forward your request to the message.jsp before returning the response back to the browser for display.