How to force HTTPS use in a Java Web Application

If you want to force the users to always use https:// even if they typed in http:// url, Applying Security Constraint in Web.xml can help.

      <security-constraint>
          <display-name>HTTPS-redirect</display-name>
          <web-resource-collection>
              <web-resource-name>secured-environments</web-resource-name>
              <description>Do HTTPS redirect so that the connection is secured</description>
              <url-pattern>/*</url-pattern>
          </web-resource-collection>
          <user-data-constraint>
              <transport-guarantee>CONFIDENTIAL</transport-guarantee>
          </user-data-constraint>
      </security-constraint>

The above constraint re-directs the user to https URL.

JSP useBean and Scope Types

The beans can be declared in JSP as following:

<jsp:useBean id=”name” class=”mypackage.MyClass” scope=”request”/>

Scope parameter indicates the context in which the bean should be made available. There are four different possible kinds of useBean scope, “page” scope being the default one.

“page”
Availability: The bean is only available on the current page
Storage: The bean is stored in the PageContext of the current page

“request”
Availability: The bean is only available for the current client request
Storage: The bean is stored in the ServletRequest object

“session”
Availability:The object is available to all pages during the life of the current HttpSession.
Storage: The bean is stored in HttpSession object

“application”
Availability: The bean available to all pages that share the same context.
Storage: The bean is stored in ServletContext object

The Servlet Basic Structure

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Created on 19th July 2008
 */
package com.kushal.servlets;
/*
 * This is a basic servlet class that shows how
 * servlet can be structured.
 */
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyFirstServlet extends HttpServlet {

/**
 * This is GET method. Request has parameters, 
 * and we write back using response.
 */	
public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
      
    PrintWriter out = response.getWriter();
    
    out.write("Hello, this is my first servlet");    
  }

/**
 * This is another kind of request with POST
 * kind of submission. We can simply reroute
 * the request to doGetmethod as below.
 */
public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
	  doGet(request, response);	  
  }
}

/**
 * In order to be able to run this servlet, you have
 * to setup a proper application server and deploy
 * the servlet. Discussing those steps is out of
 * scope in this post.
 */