Example: Web applications code

The following example depicts a Web application or servlet using the programmatic security model. The following example is one usage and not necessarily the only usage of the programmatic security model. The application can use the information returned by the getUserPrincipal(), isUserInRole() and getRemoteUser() methods in any other way that is meaningful to that application. Using the declarative security model whenever possible is strongly recommended.

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 +"
"<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 developing the servlet, one can create a security role reference for the HelloServlet as shown in the following example:

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