Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
М_указания к лабам_230400.68_совр_тенденции.doc
Скачиваний:
0
Добавлен:
01.07.2025
Размер:
9.28 Mб
Скачать

6.3 Adding the greetings and the form to the jsp template

In guestbook/src/main/webapp, edit guestbook.jsp. Add the following lines to the imports at the top:

<%@ page import="com.example.guestbook.Greeting" %> <%@ page import="com.example.guestbook.Guestbook" %> <%@ page import="com.googlecode.objectify.Key" %> <%@ page import="com.googlecode.objectify.ObjectifyService" %>

Just above the line <form action="/guestbook.jsp" method="get">, add the following code:

<%     // Create the correct Ancestor key       Key<Guestbook> theBook = Key.create(Guestbook.class, guestbookName);     // Run an ancestor query to ensure we see the most up-to-date     // view of the Greetings belonging to the selected Guestbook.       List<Greeting> greetings = ObjectifyService.ofy()           .load()           .type(Greeting.class) // We want only Greetings           .ancestor(theBook)    // Anyone in this book           .order("-date")       // Most recent first - date is indexed.           .limit(5)             // Only show 5 of them.           .list();     if (greetings.isEmpty()) { %> <p>Guestbook '${fn:escapeXml(guestbookName)}' has no messages.</p> <%     } else { %> <p>Messages in Guestbook '${fn:escapeXml(guestbookName)}'.</p> <%       // Look at all of our greetings         for (Greeting greeting : greetings) {             pageContext.setAttribute("greeting_content", greeting.content);             String author;             if (greeting.author_email == null) {                 author = "An anonymous person";             } else {                 author = greeting.author_email;                 String author_id = greeting.author_id;                 if (user != null && user.getUserId().equals(author_id)) {                     author += " (You)";                 }             }             pageContext.setAttribute("greeting_user", author); %> <p><b>${fn:escapeXml(greeting_user)}</b> wrote:</p> <blockquote>${fn:escapeXml(greeting_content)}</blockquote> <%         }     } %> <form action="/sign" method="post">     <div><textarea name="content" rows="3" cols="60"></textarea></div>     <div><input type="submit" value="Post Greeting"/></div>     <input type="hidden" name="guestbookName" value="${fn:escapeXml(guestbookName)}"/> </form>

When the user loads the page, the template performs a datastore query for all Greeting entities that use the same Guestbook in their key. The query is sorted by date in reverse chronological order ("-date"), and results are limited to the five most recent greetings. The rest of the template displays the results as HTML, and also renders the form that the user can use to post a new greeting.

6.4 Creating the form handling servlet

The web form sends an HTTP POST request to the /sign URL. Let's create a servlet to handle these requests.

In guestbook/src/main/java/com/example/guestbook, create a file named SignGuestbookServlet.java, and give it the following contents:

package com.example.guestbook; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import java.util.Date; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.googlecode.objectify.ObjectifyService; /**  * Form Handling Servlet  * Most of the action for this sample is in webapp/guestbook.jsp, which displays the  * {@link Greeting}'s. This servlet has one method  * {@link #doPost(<#HttpServletRequest req#>, <#HttpServletResponse resp#>)} which takes the form  * data and saves it.  */ public class SignGuestbookServlet extends HttpServlet {   // Process the http POST of the form   @Override   public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {     Greeting greeting;     UserService userService = UserServiceFactory.getUserService();     User user = userService.getCurrentUser();  // Find out who the user is.     String guestbookName = req.getParameter("guestbookName");     String content = req.getParameter("content");     if (user != null) {       greeting = new Greeting(guestbookName, content, user.getUserId(), user.getEmail());     } else {       greeting = new Greeting(guestbookName, content);     }     // Use Objectify to save the greeting and now() is used to make the call synchronously as we     // will immediately get a new page using redirect and we want the data to be present.     ObjectifyService.ofy().save().entity(greeting).now();     resp.sendRedirect("/guestbook.jsp?guestbookName=" + guestbookName);   } }

This servlet is the POST handler for the greetings posted by users. It takes the the greeting (content) from the incoming request and stores it in Datastore as a Greeting entity. Its properties include the content of the post, the date the post was created, and, if the user is signed in, the author's ID and email address. For more information about entities in App Engine, see Entities, Properties, and Keys.

Finally, in guestbook/src/main/webapp/WEB-INF/, edit web.xml and ensure the new servlets have URLs mapped. The final version should look like this:

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">     <servlet>       <servlet-name>sign</servlet-name>       <servlet-class>com.example.guestbook.SignGuestbookServlet</servlet-class>     </servlet>     <servlet-mapping>       <servlet-name>sign</servlet-name>       <url-pattern>/sign</url-pattern>     </servlet-mapping>     <welcome-file-list>         <welcome-file>guestbook.jsp</welcome-file>     </welcome-file-list>     <filter>       <filter-name>ObjectifyFilter</filter-name>       <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>     </filter>     <filter-mapping>       <filter-name>ObjectifyFilter</filter-name>       <url-pattern>/*</url-pattern>     </filter-mapping>     <listener>       <listener-class>com.example.guestbook.OfyHelper</listener-class>     </listener> </web-app>