550 likes | 713 Views
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)
E N D
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) • Possible Extra Credit ( 6.1-6.3, 7.1-7.4)
Examples Chapter 7 • Check the examples for Chapter 7 • http://bytesizebook.com/guide/?/guide/Examples_include.jsp
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);
Criteria • You can add other criterias Criteria.add( Restrictions.or( Restriction.and ( Restrictions.gt( “age”,13), Restrictions.lt(“age”,18) ), Restrictions.eq(“withParent”,true) ) );
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; }
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”)) {…}
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; } ... }
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>
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); }
ControllerHelper • See the entire ControllerHelper from the site.
Removing Rows • void removeDB(Object obj) • Attempts to remove a row from from DB
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>
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"); }
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
Cookie Class • Java.servlet.http.cookie • Cookie team = new Cookie(“team”,”marlins”);
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
Remember <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="core" %>
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>
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">
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"); }
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"); }
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"); }
Show Cookies!!! public String showMethod() { return jspLocation("ShowCookies.jsp"); }
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; }
Find Cookie Values static public String findCookieValue( HttpServletRequestrequest,Stringname) { Cookie cookie = findCookie(request, name); if (cookie != null) { return cookie.getValue(); } return null; }
Path Specific Cookies • Path / • All servlet will receive the cookies • If not specified • Only the servlet in the given path will get it
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"); }
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
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 {…}
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; }
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() { ….}
Create Catalog Database • See Page 272,273 • See Code (Next Slide) • Complete code in web site or page 273
@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(); } }
Shopping Cart BEAN public class ShoppingCart<Item> { … } then protected ShoppingCart<CatalogueItem> cart= new ShopingCart<CatalogueItem>();
Cart Structure Private List<Item> items; public final void resetItems() { items = new ArrayList<Item>(); … } Public ShoppingCart() { resetItems(); |
Accesing Items public List<Item> getItems() { return items; } public void addItem(Item item) { items.add(item); }
Currency private static NumberFormat currency = NumberFormat.getCurrencyInstance(); You can do currency.format(total); which returns a string in currency format
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++;}
Complete Shopping Cart • See the book site or page 276-277
Cart: Controller helper //instance variables protected CatalogueItem item = new CatalogueItem(); protected ShoppingCart<CatalogueItem> cart= new ShoppingCart<CatalogueItem();
Cart: Controller Helper public Object getItem(){ return item; } public Object getCart() { return cart; }
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; } }
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"); }
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(); }
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(); }
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"); }