70 lines
2.7 KiB
HTML
70 lines
2.7 KiB
HTML
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
|
||
|
<html>
|
||
|
<head>
|
||
|
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||
|
<LINK rel="stylesheet" type="text/css" href="../../../rzahg/ic.css">
|
||
|
|
||
|
<title>Example: Secure Web applications code </title>
|
||
|
</head>
|
||
|
|
||
|
<BODY>
|
||
|
<!-- Java sync-link -->
|
||
|
<SCRIPT LANGUAGE="Javascript" SRC="../../../rzahg/synch.js" TYPE="text/javascript"></SCRIPT>
|
||
|
|
||
|
<h4><a name="secdwebx"></a>Example: Secure Web applications code </h4>
|
||
|
|
||
|
<p>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.</p>
|
||
|
|
||
|
<pre> 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);
|
||
|
}
|
||
|
}</pre>
|
||
|
|
||
|
<p>After you develop the servlet, you can create a security role reference for the HelloServlet as show below:</p>
|
||
|
|
||
|
<pre> <security-role-ref>
|
||
|
<description>Manager</description>
|
||
|
<role-name>Mgr</role-name>
|
||
|
</security-role-ref></pre>
|
||
|
|
||
|
|
||
|
</body>
|
||
|
</html>
|
||
|
|