+

Search Tips   |   Advanced Search

 

Example: Using a programmatic security model for a Web application

 

The following example depicts a Web application or servlet using the programmatic security model.

This example illustrates one use and not necessarily the only use of the programmatic security model. The application can use the information that is returned by the getUserPrincipal, isUserInRole, and the getRemoteUser methods in any other way that is meaningful to that application. Use the declarative security model whenever possible.

File : HelloServlet.java

public class HelloServlet extends javax.servlet.http.HttpServlet {

  public void doPost(
    javax.servlet.http.HttpServletRequest request,
    javax.servlet.http.HttpServletResponse response)
    throws javax.servlet.ServletException, java.io.IOException {
  } public void doGet(
    javax.servlet.http.HttpServletRequest request,
    javax.servlet.http.HttpServletResponse response)
    throws javax.servlet.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 +"
        "<h2> "  +s+ </h2>/n " + 
    byte[] bytes = message.getBytes();
    
    // displays "Hello" for ordinary users 
        // and displays "Hello username" for managers and "bob".
        response.getOutputStream().write(bytes);
  }

}
After developing the servlet, you can create a security role reference for the HelloServlet servlet as shown in the following example:

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



 

Related tasks


Developing with programmatic security APIs for Web applications

 

Related Reference


getRemoteUser and getAuthType methods

 

Reference topic