ibm-information-center/dist/eclipse/plugins/i5OS.ic.rzatz_5.4.0.1/51/sec/secdwebx.htm

70 lines
2.7 KiB
HTML
Raw Normal View History

2024-04-02 14:02:31 +00:00
<!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 = &quot;Hello&quot;;
// get remote user using getUserPrincipal()
java.security.Principal principal = request.getUserPrincipal();
String remoteUserName = &quot;&quot;;
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(&quot;Mgr&quot;);
// display Hello username for managers and bob.
if (isMgr || remoteUserName.equals(&quot;bob&quot;)) {
s = &quot;Hello &quot; + remoteUserName;
}
String message = &quot;&lt;html&gt; \n&quot; +
&quot;&lt;head&gt;&lt;title&gt;Hello Servlet&lt;/title&gt;&lt;/head&gt;\n&quot; +
&quot;&lt;body&gt; \n&quot; +
&quot;&lt;h1&gt; &quot; + s + &quot;&lt;/h1&gt;\n &quot;;
byte[] bytes = message.getBytes();
// displays &quot;Hello&quot; for ordinary users and
// displays &quot;Hello username&quot; for managers and &quot;bob.&quot;
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> &lt;security-role-ref&gt;
&lt;description&gt;Manager&lt;/description&gt;
&lt;role-name&gt;Mgr&lt;/role-name&gt;
&lt;/security-role-ref&gt;</pre>
</body>
</html>