10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

checking the provided role name against the list of all security roles defined for the web<br />

application. Using the default method instead of using the element<br />

limits your flexibility to change role names in an application without also recompiling the<br />

servlet making the call.<br />

For example, during application assembly, the assembler creates security roles for the<br />

application and associates these roles with available security mechanisms. <strong>The</strong> assembler then<br />

resolves the security role references in individual servlets and JSP pages by linking them to roles<br />

defined for the application. For example, the assembler could map the security role reference<br />

cust to the security role with the role name bankCustomer using the <br />

element of the deployment descriptor.<br />

Declaring Roles Using Annotations<br />

<strong>The</strong> preferred method of declaring roles referenced in an application is to use the<br />

@DeclareRoles annotation. <strong>The</strong> following code sample provides an example that specifies that<br />

the roles of j2ee and guest will be used in the application, and verifies that the user is in the role<br />

of j2ee before printing out Hello World.<br />

import java.io.IOException;<br />

import java.io.PrintWriter;<br />

import javax.annotation.security.DeclareRoles;<br />

import javax.servlet.ServletException;<br />

import javax.servlet.http.HttpServlet;<br />

import javax.servlet.http.HttpServletRequest;<br />

import javax.servlet.http.HttpServletResponse;<br />

@DeclareRoles({"j2ee", "guest"})<br />

public class Servlet extends HttpServlet {<br />

}<br />

public void service(HttpServletRequest req, HttpServletResponse resp)<br />

throws ServletException, IOException {<br />

resp.setContentType("text/html");<br />

PrintWriter out = resp.getWriter();<br />

}<br />

out.println("Servlet Output<br />

");<br />

if (req.isUserInRole("j2ee") && !req.isUserInRole("guest")) {<br />

out.println("Hello World");<br />

} else {<br />

out.println("Invalid roles");<br />

}<br />

out.println("");<br />

Checking Caller Identity Programmatically<br />

Chapter 30 • SecuringWeb Applications 843

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!