Example: Secure Web applications code

This example illustrates a Web application (a servlet) that uses the programmatic security model. The example is one way to use the programmatic security model but not necessarily the only way. The application can use the information that is returned by the getUserPrincipal(), isUserInRole() and getRemoteUser() methods in any way that is meaningful to that application. However, it is strongly recommended that you use the declarative security model whenever possible.

  import javax.servlet.*;

  public class HelloServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
      String s = "Hello";
      
      // get remote user using getUserPrincipal()
      java.security.Principal principal = request.getUserPrincipal();
      String remoteUserName = "";
      
      if (principal != null) {
        remoteUserName = principal.getName();
      }
      
      // get remote user using getRemoteUser()
      String remoteUser = request.getRemoteUser();
      
      // check if remote user is granted Mgr role
      boolean isMgr = request.isUserInRole("Mgr");
      
      // display Hello username for managers and bob.
      if (isMgr || remoteUserName.equals("bob")) {
        s = "Hello " + remoteUserName;
      }
      String message = "<html> \n" +
        "<head><title>Hello Servlet</title></head>\n" +
        "<body> \n" +
        "<h1> " + s + "</h1>\n ";
      byte[] bytes = message.getBytes();
      
      // displays "Hello" for ordinary users and
      // displays "Hello username" for managers and "bob."
      response.getOutputStream().write(bytes);
    }
  }

After you develop the servlet, you can create a security role reference for the HelloServlet as show below:

  <security-role-ref>
    <description>Manager</description>
    <role-name>Mgr</role-name>
  </security-role-ref>