jsp-templates.xtp

来自「RESIN 3.2 最新源码」· XTP 代码 · 共 425 行

XTP
425
字号
<document>  <header>    <product>resin</product>    <type>article</type>    <title>JSP Templates</title>    <date>Aug 31, 1999</date>    <author>Scott Ferguson</author>    <description>      <p>      JSP templates encourage the clear and flexible      model-view-controller architecture.  It's an example of the old      JSP spec's "model 2."  This tutorial works through a simple      guest book example using JSP templates.      </p>    </description>  </header>  <body><summary/><s1 title="Introduction"><p>A powerful advantage of JSP is the ability to separate an application'sbusiness logic from its presentation.  Using Smalltalk object-orientedterminology, JSP encourages MVC (model-view-controller) web applications.JSP classes or beans are the model, JSP is the view, and a servlet isthe controller.</p><p>The example is a simple guest book.  Users log in and addcomments.  </p><deftable><tr><th>Role</th><th>Implementation</th></tr><tr><td>Model</td><td>A <code>GuestBook</code> of <code>Guests</code>.</td></tr><tr><td>View</td><td>login.jsp for new users<br/>add.jsp for logged-in users.</td></tr><tr><td>Controller</td><td><code>GuestJsp</code>, a servlet to manage the state.</td></tr></deftable></s1><s1 title="Template Skeleton: Hello, World"><p>The GuestJsp skeleton forwards a "Hello, World" string to a login.jsppage.  The skeleton establishes the architecture for the guest book.The details will be filled in below.</p><p>When the example is compiled, browse</p><def>http://localhost:8080/servlet/jsp.GuestJsp</def><p>And you should see a page like:</p><results>Hello, world</results><p>JSP templates start with servlet processing and then forward theresults to a JSP page for formatting.  </p><p>Forwarding uses a Servlet 2.1 feature of the ServletContext,getRequestDispatcher().  The request dispatcher lets servlets forwardand include any subrequests on the server.  It's a more flexiblereplacements for SSI includes.  The RequestDispatcher can include theresults of any page, servlet, or JSP page in a servlet's page.GuestJsp will use dispatcher.forward() to pass control to the JSP pagefor formatting.</p><example title="GuestJsp.java: Skeleton">package jsp.GuestJsp;import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;/** * GuestJsp is a servlet controlling user * interaction with the guest book. */public class GuestJsp extends HttpServlet {  /**   * doGet handles GET requests   */  public void doGet(HttpServletRequest req,                    HttpServletResponse res)    throws ServletException, IOException  {    // Save the message in the request for login.jsp    req.setAttribute("message", "Hello, world");    // get the application object    ServletContext app = getServletContext();    // select login.jsp as the template    RequestDispatcher disp;    disp = app.getRequestDispatcher("login.jsp");    // forward the request to the template    disp.forward(req, res);  }}</example><p>The servlet and the jsp page communicate with attributes in theHttpRequest object.  The skeleton stores "Hello, World" in the "message"attribute.  When login.jsp starts, it will grab the string and print it.</p><p>Since Resin's JavaScript understands extended Bean patterns, ittranslates the <code>request.getAttribute("message")</code> into theJavaScript equivalent <code>request.attribute.message</code>.</p><example title="login.jsp: Skeleton">&lt;%@ page language=javascript %&gt;&lt;head&gt;&lt;title&gt;&amp;lt%= request.attribute.message %&gt;&lt;/title&gt;&lt;/head&gt;&lt;body bgcolor='white'&gt;&lt;h1&gt;&amp;lt%= request.attribute.message %&gt;&lt;/h1&gt;&lt;/body&gt;</example><s2 title="Servlet Review"><p>For those coming to JSP from an ASP or CGI background, Servlets replaceCGI scripts taking advantage of Java's strength in dynamic classloading.  A servlet is just a Java class which extends Servlet orHttpServlet and placed in the proper directory. Resin willautomatically load the servlet and execute it.</p><ul><li><img src="folder.gif"/>&#160;doc<ul>  <li><img src="file.gif"/>&#160;index.html  </li><li><img src="jsp.gif"/>&#160;login.jsp  </li><li><img src="jsp.gif"/>&#160;add.jsp  </li><li><img src="folder.gif"/>&#160;WEB-INF  <ul>    <li><img src="folder.gif"/>&#160;classes    <ul>    <li><img src="folder.gif"/>&#160;jsp      <ul>      <li><img src="bean.gif"/>&#160;GuestJsp.class      </li><li><img src="bean.gif"/>&#160;GuestBook.class      </li><li><img src="bean.gif"/>&#160;Guest.class      </li></ul>    </li></ul>  </li></ul></li></ul></li></ul><p>The url /servlet/<var>classname</var> forwards the request to theServlet <em>Invoker</em>. The Invoker will dynamically load the Java class<var>classname</var> from doc/WEB-INF/classes and try to execute theServlet's <code>service</code> method.</p><p>Resin checks the class file periodically to see if the class haschanged.  If so, it will replace the old servlet with the new servlet.</p></s2></s1><s1 title="Displaying the Guest Book"><p>The next step, after getting the basic framework running, is to createthe model.</p><s2 title="The GuestBook model"><p>The guest book is straightforward so I've just included the API here.It conforms to Bean patterns to simplify the JavaScript.  The same APIwill work for HashMap, file-based, and database implementations.</p><p>JSP files only have access to public methods.  So a JSP filecannot create a new GuestBook and it can't add a new guest.  That'sthe responsibility of the GuestJsp servlet.</p><example title="jsp.Guest.java API">package jsp;public class Guest {  Guest();  public String getName();  public String getComment();}</example><p>Resin's JavaScript recognizes Bean patterns.  So JSP pages usingJavaScript can access <code>getName()</code> and <code>getComment()</code> asproperties.  For example, you can simply use <code>guest.name</code> and<code>guest.comment</code></p><example title="jsp.GuestBook.java API">package jsp;public class GuestBook {  GuestBook();  void addGuest(String name, String comment);  public Iterator iterator();}</example><p>Resin's JavaScript also recognizes the iterator() call, so you canuse a JavaScript <code>for ... each</code> to get the guests:</p><example>for (var guest in guestBook) {  ...}</example></s2><s2 title="GuestBook as application attribute"><p>To keep the example simple, GuestJsp stores the GuestBook in theapplication (ServletContext).  As an example, storing data in theapplication is acceptable but for full-fledged applications, it'sbetter just to use the application to cache data stored elsewhere.</p><example title="jsp.GuestJsp.java">// get the application objectServletContext app = getServletContext();GuestBook guestBook;// The guestBook is stored in the applicationsynchronized (app) {  guestBook = (GuestBook) app.getAttribute("guest_book");  // If it doesn't exist, create it.  if (guestBook == null) {    guestBook = new GuestBook();    guestBook.addGuest("Harry Potter", "Griffindor rules");    guestBook.addGuest("Draco Malfoy", "Slytherin rules");    app.setAttribute("guest_book", guestBook);  }}RequestDispatcher disp;disp = app.getRequestDispatcher("login.jsp");// synchronize the Application so the JSP file // doesn't need to worry about threadingsynchronized (app) {  disp.forward(req, res);}</example><p>The JSP file itself is simple.  It grabs the guest book fromthe application and displays the contents in a table.  Normally,application objects need to be synchronized because several clientsmay simultaneously browse the same page.  GuestJsp has taken care ofsynchronization before the JSP file gets called.</p><example title="login.jsp: Display Guest Book">&lt;%@ page language=javascript %&gt;&lt;head&gt;&lt;title&gt;Hogwarts Guest Book&lt;/title&gt;&lt;/head&gt;&lt;body bgcolor='white'&gt;&lt;h1&gt;Hogwarts Guest Book&lt;/h1&gt;&lt;table&gt;&lt;tr&gt;&lt;td width='25%'&gt;&lt;em&gt;Name&lt;/em&gt;&lt;td&gt;&lt;em&gt;Comment&lt;/em&gt;&lt;%var guestBook = application.attribute.guest_bookfor (var guest in guestBook) {  out.writeln("&lt;tr&gt;&lt;td&gt;" + guest.name + "&lt;td&gt;" + guest.comment);}%&gt;&lt;/table&gt;&lt;/body&gt;</example><results>&lt;h1>Hogwarts Guest Book&lt;/h1>&lt;table>&lt;tr>&lt;td>&lt;em>Name&lt;/em>&lt;/td>&lt;td>&lt;em>Comment&lt;/em>&lt;/td>&lt;/tr>&lt;tr>&lt;td>Harry Potter&lt;/td>&lt;td>Griffindor Rules&lt;/td>&lt;/tr>&lt;tr>&lt;td>Draco Malfoy&lt;/td>&lt;td>Slytherin Rules&lt;/td>&lt;/tr>&lt;/table></results></s2></s1><s1 title="Guest book logic"><p>The guest book logic is simple.  If the user has not logged in, shesees comments and a form to log in.   After login, she'll see thecomments and a form to add a comment.  login.jsp formats the loginpage and add.jsp formats the add comment page.</p><p>GuestJsp stores login information in the session variable.</p><deftable><tr><th>Form Variable</th><th>Meaning</th></tr><tr><td>action</td><td>'login' to login or 'add' to add a comment</td></tr><tr><td>name</td><td>user name</td></tr><tr><td>password</td><td>user password</td></tr><tr><td>comment</td><td>comment for the guest book</td></tr></deftable><example title="Guest book logic">...// name from the sessionString sessionName = session.getValue("name");// action from the formsString action = request.getParameter("action");// name from the login.jsp formString userName = request.getParameter("name");// password from the login.jsp formString password = request.getParameter("password");// comment from the add.jsp formString comment = request.getParameter("comment");// login stores the user in the sessionif (action != null &amp;&amp; action.equals("login") &amp;&amp;    userName != null &amp;&amp;    password != null &amp;&amp; password.equals("quidditch")) {  session.putValue("name", userName);}// adds a new guestif (action != null &amp;&amp; action.equals("add") &amp;&amp;    sessionName != null &amp;&amp;    comment != null) {  guestBook.addGuest(sessionName, comment);}String template;// if not logged in, use login.jspif (session.getValue("name") == null)  template = "login.jsp";// if logged in, use add.jspelse  template = "add.jsp";RequestDispatcher disp;disp = app.getRequestDispatcher(template);...</example><p>login.jsp and add.jsp just append different forms to the displaycode in the previous section.</p><example title="login.jsp">&lt;%@ page language=javascript %&gt;&lt;head&gt;&lt;title&gt;Hogwarts Guest Book: Login&lt;/title&gt;&lt;/head&gt;&lt;body bgcolor='white'&gt;&lt;h1&gt;Hogwarts Guest Book&lt;/h1&gt;&lt;table&gt;&lt;tr&gt;&lt;td width='25%'&gt;&lt;em&gt;Name&lt;/em&gt;&lt;td&gt;&lt;em&gt;Comment&lt;/em&gt;&lt;%var guestBook = application.attribute.guest_bookfor (var guest in guestBook) {  out.writeln("&lt;tr&gt;&lt;td&gt;" + guest.name + "&lt;td&gt;" + guest.comment);}%&gt;&lt;/table&gt;&lt;hr&gt;&lt;form action='GuestJsp' method='post'&gt;&lt;input type=hidden name='action' value='login'&gt;&lt;table&gt;&lt;tr&gt;&lt;td&gt;Name:&lt;td&gt;&lt;input name='Name'&gt;&lt;tr&gt;&lt;td&gt;Password:&lt;td&gt;&lt;input name='Password' type='password'&gt;&lt;tr&gt;&lt;td&gt;&lt;input type=submit value='Login'&gt;&lt;/table&gt;&lt;/form&gt;&lt;/body&gt;</example></s1><s1 title="Conclusion"><p>The Resin demo shows a few ways to extend the guest book, includingadding some intelligence to the form processing.</p></s1>    </body></document>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?