📄 webapp-overview.xtp
字号:
<p>The offending java.lang.Throwable describing the error that occurredis stored in the javax.ServletRequest instance for the client requestusing the putAttribute() method, using the namejavax.servlet.jsp.jspException. Names starting with the prefixes javaand javax are reserved by the different specifications of the Javaplatform; the javax.servlet prefix is used by the Servlet and JSPspecifications. If the errorPage attribute of a page directive namesa URL that refers to another JSP, and that JSP indicates that it is anerror page (by setting the page directive's isErrorPage attribute totrue) then the exception implicit scripting language variable of thatpage is initialized to the offending Throwable reference.</p></blockquote></s2></s1> <!-- errors --><s1 name="architecture" title="Architecture"><p>There are many ways to use the capabilities that are offered byJSP -- different models apply to different applications.</p><s2 title="Simple JSP"><p>The simplest model is to use JSP as an add-on to existing webpages. At the top of each page is the Java code that is necessary forthe display of the page, and at the bottom is the markup that is to beoutput, with appropriate insertion of any dynamically generatedvariables.</p><p>Note the seperation of the different logical parts. It is a very goodidea to keep the presentation section as Java-less as possible. Setupall of the values in the logic part, and then use only simple<code><%= var %></code> and <code>if</code> statements in thepresentation part.</p><example title="SimpleJSP.jsp - the logic and display code in one page"><%-- urls --%><% // store your target urls in String variables%><%-- incoming parameters --%><% // store form values from the request object in variables%><%-- logic --%><% // we all make decisions with logic, right?%><%-- presentation --%><markup> <forthebrowser> </forthebrowser></markup></example><p>This seems like a sensible approach. However, imagine that later it isdecided that a different set of HTML is needed for the output if thereis no news available. As well, support of WML output is required. Nowwe need to put the display code for 4 different types of output intoone page. Maybe we need to go to different places as well, forexample an administrator might get a different display page, or weneed to check the users profile to see what is apporiate to display.This is too much complication to put all in one place.</p><p>This type of implementation, because of it's limitiations and it'sinability to change without exponentially increasing the complexity,should be avoided.</p></s2><s2 title="Seperating the logic into another JSP"><p>To address some of the disadvantages of the Simple JSP method, it ispossible to seperate the `logic' and the `presentation' into twodifferent JSP files.</p><p>In this model, instead of a link pointing directly to the page thatdoes the display, it points to a page that handles the incomingrequest. This 'logic' page contains the Java code that is responsiblefor preparing the values that will be used for displaying. It storesthese prepared values as attributes of the <code>request</code> object,and then <var>forwards</var> to the appropriate display page. The displaypage then pulls the information it needs out of the request object anddisplays it.</p><example title="SeperateJsp.jsp - The logic JSP that prepares the data for display"><% /** -- incoming parameters -- */ String strJuiceType = request.getParameter("juiceType"); String strQuantity = request.getParameter("juiceQuantity");/** -- logic -- */Double cost;String strCost;here we might do a check to make sure mandatory fieldshave values.Here we might do a database lookup to determine the price, andset the cost value to the price * quanitityNow we might format the cost double into a two-decimal number and store it in strCost/** -- set outgoing parameters -- forward to display page -- *//** note that here we put juiceType in as a request attribute, even though the display page could get it from the request parameters. This helps us keep the interface between the logic and the presentation cleaner */request.setAttribute("cost", strCost);request.setAttribute("juiceType", strJuiceType);request.setAttribute("quantity", strQuantity);if (isWML) pageContext.forward("SeperateJspPresentationWML.jsp");else pageContext.forward("SeperateJspPresentationHTML.jsp");%></example><example title="SeperateJspPresentationHTML.jsp - The JSP that presents the prepared information in HTML format"><%-- urls --%><%-- prepared objects --%><%String cost = (String) request.getAttribute("cost");String juiceType = (String) request.getAttribute("juiceType");String quantity = (String) request.getAttribute("quantity");%><%-- presentation --%>Hey, if you want <%= quantity %> bottles of <%= juiceType => juice, it is going to costyou $<%= cost %></example><p>Here we have introduced a new thing: <code>pageContext.forward</code>.</p></s2><s2 title="pageContext.forward"><p>The <code>pageContext.forward(String url)</code> forwards the processing to adifferent JSP page. That is, it passes control over to anotherpage. This page is then executed, inheriting the current request andresponse objects. It is important that this is the last thingthat a JSP page does.</p></s2><s2 title="Seperating the business logic into beans"><p>Even the seperation of all logic into a different JSP can get a bit muddled.You can seperate the `logic' into two types of logic, business logicand presentation logic. </p><p>Presentation logic is logic that is part of the presentation.Examples are form validation and formatting of numbers into strings.</p><p>Business logic is programming that involves your data. If you canseparate something in your mind from the presentation, it doesn'tdepend on the presentation in any way, that's business logic.Examples are database lookups and shopping cart manipulation.</p><p>Your application will be cleaner and easier to manage if you put yourbusiness logic in Java classes (beans) which hide thecomplexities. You then use these classes in the logic.jsp.</p></s2><s2 title="Model 2 (preferred)"><p>The final approach discussed here is called the `Model 2' approach. Thisapproach requires a level of sophistication that is usually notwarranted unless you use a library that supports it, however it is thecleanest way to implement an application.</p><p>In this approach there is a special Servlet called a controllerservlet. The controller maps an incoming request to a Java class thattakes care of all of the 'business logic'. This Java class returns a resultthat indicates to the controller where it should go next. The controller thendispatches to the appropriate place. </p><p>The flow of a request moves through these `business logic' pieces, finallyending up at a `view'. The logic pieces are responsible for examing thesubmitted information (such as parameters from forms), managing logical flow,and preparing objects for the <var>view</var>. The objects for the view are storedas attributes of the request (or sometimes, the session).</p><p>The view is responsible for preparing a response for the user using theprepared objects now available as request or session objects. This is whereJSP is often used, it works very well as the view component of a Model 2architecture.</p><p>The developer tells the controller what the flow for each request isby specifying it an external (usually XML) file.</p><p>This approach is by far the cleanest approach to using Servlets and JSP. Mostapplications of any significant complexity use a Model 2 architecture. </p></s2></s1> <!-- architecture --><s1 name="security" title="Security"><p>JSP inherits the Servlet security mechanism. Using the two fundamentalconcepts of <var>Principals</var> and <var>Roles</var>, JSP providesdeclarative and programmatic security.</p><p>In addition, there is builtin support for various HTTP methods oflogin that establish a Principal and it's Roles based on a user loginand password.</p><s2 title="Principals"><p>A Principal is established in association with a Session. There is aone to one correspondence between the two. Usually the Principal is auser, a real live honest to goodness person sitting at a computersomewhere and accessing the Web Application.</p><p>The Application may require that the User go through a login process,a successful login will establish a Principal, which will have acertain set of Roles.</p></s2><s2 title="Roles"><p>Servlet 2.2 Specification states:</p><blockquote>A role is an abstract logical grouping of users that is defined by theApplication Developer or Assembler. When the application is deployed,these roles are mapped by a Deployer to security identities, such asprincipals or groups, in the runtime environment.</blockquote><p>Roles are similar to groups in Unix security. As an example, youmight have a "member" role for users who have a membership, and an"admin" role for administrators. </p><p>Principals can have more than one role -- a user might be both a"member" and an "admin".</p></s2><s2 title="Declarative Security"><p>Servlet 2.2 Specification states:</p><blockquote>Declarative security refers to the means of expressing anapplication's security structure, including roles, access control, andauthentication requirements in a form external to the application. Thedeployment descriptor is the primary vehicle for declarative securityin web applications.</blockquote><p>Basically what this means in real terms is that you can specifycertain paths in web.xml that require certain roles. For example, youcan say that to access any page in the "/accountsetup/" subdirectory,the user must have a role of "admin".</p></s2><s2 title="Programmatic Security"><p>Servlet 2.2 Specification states:</p><blockquote>Programmatic security is used by security aware applications whendeclarative security alone is not sufficient to express the securitymodel of the application. </blockquote><p>Programmatic security lets you decide in some Java code what to do,based on the role that a user has. For example, you might make acertain button appear in the button bar only for an "admin" user.</p><deftable title="Programmatic Security API"><tr><th>Method</th><th>Description</th></tr><tr><td><a href="javadoc|javax.servlet.http.HttpServletRequest|getRemoteUser()">request.getRemoteUser()</a>return the name of an authenticated user.</td></tr><tr><td><a href="javadoc|javax.servlet.http.HttpServletRequest|isUserInRole(String)">request.isUserInRole(String role)</a></td><td>return true if the current user is in a given security role.</td></tr><tr><td><a href="javadoc|javax.servlet.http.HttpServletRequest|getUserPrincipal()">request.getUserPrincipal()</a></td><td>return the <a href="javadoc|java.security.Principal|"/> associated with thecurrent user.</td></tr></deftable></s2><s2 title="When does Resin require a login?"><p>The resources in an Application are by default open to the public, anddo not require a login. As soon as the User attempts to access aresource that has been declared to require a role in the web.xml,Resin will insert in the process a login of some kind beforecontinuing on to the resource that was originally requested.</p><p>For example, if the "/members/*" area has been declared to require a"member" role, as soon as the user tries to access anything in"/members/" Resin will check to see if the user has logged inyet. If the user has logged in, then the roles for the user arechecked to see if "member" is a role that user can take. If the userhas not logged in, Resin inserts a login procedure and thenchecks the roles.</p></s2><s2 title="The login procedure"><p>The Servlet Specification details numerous methods for getting useridentification and password information from the user.</p><p>The example below shows usage of "Form Based Authentication", whichallows you to specify a login page to be sent to the user when needed,and an error page that will be displayed if the user login fails.</p><p>The login page should submit a form to the url<code>j_security_check</code> with the parameters <code>j_username</code> and <code>j_password</code> set to appropriate values.</p><p>Resin recognizes the special url <code>j_security_check</code> andauthenticates the username and password.</p></s2><s2 title="Lifecycle of a Principal"><p>The Servlet authentication associates a <var>principal</var> with a <a href="#session">session</a>. The principal will only last as long as theSession; as soon as the Session is gone then the user will no longer be loggedin.</p><p>As a result, invalidation of the Session will also cause a logout:</p><example>session.invalidate();</example><p>You can also cause a logout without invalidating the whole Session. Otherobjects in the session will remain available but the principal will benull:</p><example>session.logout();</example></s2><s2 title="Authenticating the User"><p>Once the user information is collected, the password must be verifiedand the roles determined. Unfortunately, the Servlet specificationdoes not indicate a standard way for this to occur.</p><p>What that means is that every Container is likely to do thisdifferently, and you will have to refer to Container specificdocumentation and examples.</p></s2><s2 title="Example usage of Security"><p>The Resin documentation on <a href="security.xtp">Security</a> includes acomprehensive discussion, and the <a href="../examples/security-basic/index.xtp">BasicSecurity Tutorial</a> is a good starting point as well.</p></s2></s1> <!-- security --></body></document>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -