1 / 55

CGS – 4854 Summer 2012

CGS – 4854 Summer 2012 . Instructor: Francisco R. Ortega Chapter 5. Web Site Construction and Management. Today’s Lecture. Chapter 7. Final Exam. Chapter 4 All Sections except 4.1 Chapter 5 (ALL) Chapter 6 6.2,6.4-6.12 Chapter 7 7.5 to 7.9 (except for 7.9.5)

tanith
Download Presentation

CGS – 4854 Summer 2012

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CGS – 4854 Summer 2012 Instructor: Francisco R. Ortega Chapter 5 Web Site Construction and Management

  2. Today’s Lecture • Chapter 7

  3. Final Exam • Chapter 4 • All Sections except 4.1 • Chapter 5 (ALL) • Chapter 6 • 6.2,6.4-6.12 • Chapter 7 • 7.5 to 7.9 (except for 7.9.5) • Possible Extra Credit ( 6.1-6.3, 7.1-7.4)

  4. Examples Chapter 7 • Check the examples for Chapter 7 • http://bytesizebook.com/guide/?/guide/Examples_include.jsp

  5. Finding a Row • getListData(Class classBean, String strKey, Object Value) • getListData(Class classBean, String strKey1, Object Value1, String strKey2, Object Value2) • Code in page 247 and Shared Package. • Uses “Like” for criteria • Criteria c = criteria.add(Restrictions.like(strKey1,value1);

  6. Criteria • You can add other criterias Criteria.add( Restrictions.or( Restriction.and ( Restrictions.gt( “age”,13), Restrictions.lt(“age”,18) ), Restrictions.eq(“withParent”,true) ) );

  7. More Hibernate!!!

  8. Get First Match • getFirstMatch(Class classBean,StringstrKey, Object value) • Returns first match found. • This will retrieve a row in the bean. If it exist, it will be added to the session Object dataPersistent =HibernateHelper.getFirstMatch(data, ”accountNumber”, data.getMovieID()); If (dataPersistent != null) { data = (RequestDataAccount) dataPersistent; }

  9. Validating a Single Property • Just to make sure the property exist Public booleanisValidProperty(String name) { String msg = errorMap.get(name); return msg == null || msg.equals(“”); } … setErrors(data); If (isValidProperty(“accountNumber”)) {…}

  10. Account Login - JavaBean @Entity public class RequestDataAccountextends shared.PersistentBaseimplements Serializable { … protected String accountNumber; @Pattern(regexp="[a-zA-Z]{2}\\d{3}", message="must be in the format AA999.") @NotNull public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } ... }

  11. Login.jsp <p>Please enter your account number to access your data.</p< <form method="POST" action="Controller"> <p> Account Number ${helper.errors.accountNumber} <input type="text" name="accountNumber" value="${helper.data.accountNumber}"> <input type="submit" name="loginButton" value="Login"> </p> </form>

  12. Controller Helper @ButtonMethod(buttonName="loginButton") public String loginMethod() { String address; fillBeanFromRequest(data); setErrors(data); if (isValidProperty("accountNumber")) { Object dataPersistent = HibernateHelper.getFirstMatch(data, "accountNumber", data.getAccountNumber()); if (dataPersistent != null) { data = (RequestDataAccount)dataPersistent; } clearErrors(); address = "Edit.jsp"; } else { address = "Login.jsp"; } return jspLocation(address); }

  13. ControllerHelper • See the entire ControllerHelper from the site.

  14. Removing Rows • void removeDB(Object obj) • Attempts to remove a row from from DB

  15. Process.jsp <form method="POST" action="Controller"> <p>Edit the current record. <input type="submit" name="editButton" value="Edit"> Remove the current record. <input type="submit" name="removeButton" value="Remove"> </p> </form> <form method="GET" action="Controller"> <p> Log on as a new user. <input type="submit" name="newUserButton" value="New User"> </p> </form>

  16. ControllerHelper: Account Removal @ButtonMethod(buttonName="removeButton") public String removeMethod() { //data is your bean HibernateHelper.removeDB(data); data = new ch7.accountLogin.RequestDataAccount(); return jspLocation("Login.jsp"); }

  17. Cookies • Server asks browser to store info • Browser stores info • Browser sends back information next time • Cookies store in a “cookie jar” • A cookie is a row in the “cookie jar” • Primary key is URL • All cookies by given URL and path are sent back to server • Browser will delete cookies that are expired

  18. Cookies

  19. Cookie Class • Java.servlet.http.cookie • Cookie team = new Cookie(“team”,”marlins”);

  20. Cookie Class • SetName/GetName • SetValue/GetValue • SetMaXAge,GetMaxAge • Default is -1 seconds (delete when browser closes) • MaXAge = 0 (delete immediately) • MaxAge > 0 : Number of seconds • setDomain/GetDomain • Must be valid and belonging to the site • setPath/getPath • setSecure/getSecure • Default can be sent via any type of connection

  21. Remember <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="core" %>

  22. Cookies : JSP (SHOW COOKIES) <table> <tr><th>Name<th>Value <core:forEachvar="element" items="${cookie}"> <tr><td>${element.value.name} <td>${element.value.value} </core:forEach> </table>

  23. Let’s test the COOKIES <input type="submit" name="showCookieButton" value="Show Cookies"> <input type="submit" name="setCookieButton" value="Set Cookies"> <input type="submit“ name="deleteCookieButton" value="Delete Cookie"> <input type="submit" name="findCookieButton" value="Find Cookie">

  24. Set Cookies @ButtonMethod(buttonName="setCookieButton") public String setMethod() { Cookie dolphins = new Cookie("dolphins", "The Dolphins are here to stay"); dolphins.setPath("/"); response.addCookie(dolphins); Cookie marlins = new Cookie("marlins", "The Marlins will be gone soon"); marlins.setMaxAge(15); marlins.setPath("/"); response.addCookie(marlins); return jspLocation("ShowCookies.jsp"); }

  25. Deleting Cookies @ButtonMethod(buttonName="deleteCookieButton") public String deleteMethod() { Cookie marlins = new Cookie("marlins", "bye-bye"); marlins.setMaxAge(0); marlins.setPath("/"); response.addCookie(marlins); return jspLocation("ShowCookies.jsp"); }

  26. Finding Cookies @ButtonMethod(buttonName="findCookieButton") public String findMethod() { Cookie[] cookieArray = request.getCookies(); Cookie marlins = null; if (cookieArray != null) { for (Cookie cookie : cookieArray) { if (cookie.getName().equals("marlins")) { marlins = cookie; } } } String result = "The Marlins have left town"; if (marlins != null) { result = marlins.getValue(); } request.setAttribute("marlins",result); return jspLocation("ShowCookies.jsp"); }

  27. Show Cookies!!! public String showMethod() { return jspLocation("ShowCookies.jsp"); }

  28. Cookie Utils: Find Cookie Static public Cookie findCookie( HttpServletRequestrequest,Stringname) { if (request.getCookies() == null) return null; for(Cookie cookie : request.getCookies()) { if (cookie.getName().equals(name)) return cookie; } return null; }

  29. Find Cookie Values static public String findCookieValue( HttpServletRequestrequest,Stringname) { Cookie cookie = findCookie(request, name); if (cookie != null) { return cookie.getValue(); } return null; }

  30. Path Specific Cookies • Path / • All servlet will receive the cookies • If not specified • Only the servlet in the given path will get it

  31. Set Specific @ButtonMethod(buttonName="setSpecificCookieButton") public String setSpecificMethod() { Cookie specific = new Cookie("specific", "Not all pages can see this cookie"); specific.setMaxAge(15); response.addCookie(specific); return jspLocation("ShowCookies.jsp"); }

  32. Shopping Cart • See examples in book • /ch7/catalogue/ • For example • http://bytesizebook.com/guide/?/guide/ViewClass/ch7/catalogue/CatalogueItem.java • We will only covered Session Cart. • Persistent is left for your own discovery! • Extra credit if is persistent

  33. Shopping Cart • A Cart has • Items • Book uses Catalogue Item that has • Name • Description • A Price • An Item ID @Entity public class CatalogueItem extends shared.PersistentBase implements Serializable {…}

  34. Constructors Public CatalogueItem() { this(null,””,””,0.00”) ; } Public CatalogueItem(String itemId, String name, String description, double price) { this.itemId = itemId; this.Name = name; this.Description = description; this.price = price; }

  35. Catalogue Item Fields • See the book for correct imports • If you want to specify the length of db text field • @Length(min =1, max = 50) • If nothing specifies, default is 255 • If the object is extremely large use • @Lob • @NotNull, Another look: • The database will not allow null @NotNull @Length(min=1,max=100); public String getItemId() { ….}

  36. Create Catalog Database • See Page 272,273 • See Code (Next Slide) • Complete code in web site or page 273

  37. @WebServlet(urlPatterns={"/ch7/catalogue/CreateCatalogue"}) public class CreateCatalogue extends HttpServlet { public void init() { HibernateHelper.createTable(CatalogueItem.class); HibernateHelper.initSessionFactory(CatalogueItem.class); } static final List<CatalogueItem> itemList = new ArrayList<CatalogueItem>(); static { itemList.add(new CatalogueItem("A1", "The Foundation Trilogy", "A very fine book. Why not buy one?", 1.11)); itemList.add(new CatalogueItem("T2", "The Hobbit", "A very fine book. Why not buy two?", 2.22)); itemList.add(new CatalogueItem("Y3", "Light on Yoga", "A very fine book. Why not buy three?", 3.33)); itemList.add(new CatalogueItem("M4", "Blue Monkey ","A very fine book.Whynot buy four?",4.44)); }; protected void doGet(HttpServletRequest request, HttpServletResponse response) …{ HibernateHelper.updateDB(itemList); response.getWriter().print("Catalogue Created"); destroy(); } }

  38. Shopping Cart BEAN public class ShoppingCart<Item> { … } then protected ShoppingCart<CatalogueItem> cart= new ShopingCart<CatalogueItem>();

  39. Cart Structure Private List<Item> items; public final void resetItems() { items = new ArrayList<Item>(); … } Public ShoppingCart() { resetItems(); |

  40. Accesing Items public List<Item> getItems() { return items; } public void addItem(Item item) { items.add(item); }

  41. Currency private static NumberFormat currency = NumberFormat.getCurrencyInstance(); You can do currency.format(total); which returns a string in currency format

  42. Total and Count public void setTotal(double total) { this.total = total; } public double getTotal() { return total; } public void setCount(int count) { this.count= count; } public intgetCount(){ return count; } public void addTotal(double amount) { total += amount;} public String getTotalAsCurrency(){ return currency.format(total);} public void incrCount() { count++;}

  43. Complete Shopping Cart • See the book site or page 276-277

  44. Cart: Controller helper //instance variables protected CatalogueItem item = new CatalogueItem(); protected ShoppingCart<CatalogueItem> cart= new ShoppingCart<CatalogueItem();

  45. Cart: Controller Helper public Object getItem(){ return item; } public Object getCart() { return cart; }

  46. Copy from Session public void copyFromSession(Object sessionHelper) { if (sessionHelper.getClass() == this.getClass()) { … // also copy item and cart item = ((ControllerHelper)sessionHelper).item; cart = ((ControllerHelper)sessionHelper).cart; } }

  47. Default Button @ButtonMethod(isDefault=true) public String methodDefault() { //Make all the catalog items available from the BrowseLoop.jsp. java.util.List list = HibernateHelper .getListData(CatalogueItem.class); request.setAttribute("allItems", list); return jspLocation("BrowseLoop.jsp"); }

  48. AddCart and EmptyCart @ButtonMethod(buttonName="addCart") public String methodAddCart() { cart.addItem(item); item = new CatalogueItem(); return methodDefault(); } @ButtonMethod(buttonName="emptyCart") public String methodEmptyCart() { cart.resetItems(); return methodDefault(); }

  49. View Item @ButtonMethod(buttonName="viewItem") public String methodViewItem() { fillBeanFromRequest(item); if (item.getItemId() != null) { Object dbObj = HibernateHelper. getFirstMatch(item, "itemId", item.getItemId()); if (dbObj != null) { item = (CatalogueItem)dbObj; } } return methodDefault(); }

  50. View Cart and Process Cart @ButtonMethod(buttonName="viewCart") public String methodViewCart() { return jspLocation("Cart.jsp"); } @ButtonMethod(buttonName="processCart") public String methodProcess() { cart.setTotal(0); cart.setCount(0); for(CatalogueItemanItem : cart.getItems()) { cart.addTotal(anItem.getPrice()); cart.incrCount(); } return jspLocation("Process.jsp"); }

More Related