Requirements: 1, write a commodity category, there is the product number, commodity name, commodity classification, Commodity Unit price attribute. 2, write a commodity item information class, there are two attributes of goods and quantity, there is a total price method of goods.
3, write a shopping cart category, there are add product methods, view order information, delete products, modify products, empty shopping cart, the total amount of all items in the shopping cart method. 4, write a test class, test the above method.
Product Category:
[Java] View plain copy
public class Product {
private int productid;//Product number
Private String productname;//Product name
Private String category;//Product category
Private double price;//unit price
Public Product () {//non-parametric construction
Super ();
}
Public Product (int productId, string productName, String category,
Double price) {
Super ();
This.productid = productId;
This.productname = ProductName;
this.category = category;
This.price = Price;
}
Public String toString () {
Return "Product [productid=" + ProductId + ", productname="
+ ProductName + ", category=" + category + ", price=" + Price
+ "]";
}
public int GetProductID () {
return productId;
}
public void Setproductid (int productId) {
This.productid = productId;
}
Public String Getproductname () {
return productName;
}
public void Setproductname (String productName) {
This.productname = ProductName;
}
Public String getcategory () {
return category;
}
public void Setcategory (String category) {
this.category = category;
}
Public double GetPrice () {
return price;
}
public void Setprice (double price) {
This.price = Price;
}
}
Product entry Information class:
[Java] View plain copy
public class Productitem {
Private product product;//purchased items
private int count;//Number of items
Public double Totalmoney () {//Subtotal
Double Price=product.getprice ();//Get Commodity unit Price
return price*count;
}
Public Productitem () {
Super ();
}
Public Productitem (product product, int count) {
Super ();
This.product = product;
This.count = count;
}
Public Product getproduct () {
return product;
}
public void Setproduct (product product) {
This.product = product;
}
public int GetCount () {
return count;
}
public void SetCount (int count) {
This.count = count;
}
}
Shopping Cart Category:
[Java] View plain copy
Import java.util.Collection;
Import Java.util.Iterator;
Import Java.util.LinkedHashMap;
Import Java.util.Map;
public class ShoppingCart {//Shopping cart
Key: Product Code value: Product entry
Private map<integer,productitem> map=new linkedhashmap<integer,productitem> ();
public void Addproduct (product p) {//Add product
int Productid=p.getproductid ();
if (Map.containskey (productId)) {
Productitem Productitem=map.get (productId);
Productitem.setcount (Productitem.getcount () +1);
}else{
Map.put (ProductId, New Productitem (p,1));
}
}
public void ShowAll () {//view order Information
collection<productitem> Productitems = Map.values ();
iterator<productitem> Iterator = Productitems.iterator ();
while (Iterator.hasnext ()) {
Productitem Productitem = Iterator.next ();
Product Product = Productitem.getproduct ();
SYSTEM.OUT.PRINTLN ("Product Code:" +product.getproductid () + ", Product Name:"
+product.getproductname () + ", Unit Price:" +product.getprice () + ", Quantity:" +productitem.getcount ()
+ ", Subtotal:" +productitem.totalmoney ());
}
}
public boolean deleteproduct (int productId) {//delete item
if (Map.containskey (productId)) {
Map.Remove (PRODUCTID);
return true;
}
return false;
}
public boolean modifyproduct (int productid,int count) {//Modify
if (Map.containskey (productId)) {
if (count>=1) {
Productitem Productitem = Map.get (productId);
Productitem.setcount (count);
return true;
}else if (count==0) {//delete
Deleteproduct (PRODUCTID);
return true;
}
}
return false;
}
public void Clearcart () {//Empty purchase
Map.clear ();
}
Public double Totalallmoney () {//
Double total=0;
collection<productitem> Productitems = Map.values ();
iterator<productitem> Iterator = Productitems.iterator ();
while (Iterator.hasnext ()) {
Productitem Productitem = Iterator.next ();
Double Money=productitem.totalmoney ();
Total+=money;
}
return total;
}
}
Write Java code in jsp=html
The content in the JSP is corresponding to the content in Java, and eventually compiled into a class file
Output the HTML layout tag in the JSP page to the browser: Out.write ("<br>");//is a character output stream output
How the Java code in the JSP is executed: the Java code in the JSP is translated intact into the Servlet's service method
The object that the server will pass to the JSP when it invokes the JSP: Request,response,pagecontext,config,session,page,out
Instructions are for the server, telling the server how to treat the JSP page
<% @include file= "/a.jsp"%>
Action command:
<jsp:include page= "/a.jsp" >
</jsp:include>
Request forwarding, pointing to the forwarded page
<jsp:forward page= "/a.jsp" >
<%--Pass request parameters for other labels to use--%>
<jsp:param name= "A" value= "123" ></jsp:param>
<jsp:param name= "B" value= "456" ></jsp:param>
</jsp:forword>
Statement: Representing SQL statements, sending and executing SQL statements to the database
ResultSet executeQuery (String sql): Executes the query operation of the database only, returns the result set of the query
int executeupdate (String sql): Executes DML, returning the number of rows that affect the operation data record
int num = stmt.executeupdate ("Update users set id= ' 111 '");
Boolean execute (String SQL): Executes the SQL statement, returns True if there is a return value, returns False if no return value
The traversed result set is printed to the console without the use of birds and should be encapsulated in JavaBean
list<users> user = new arraylist<users> ();
while (Rs.next ()) {
Users u = new users ();
U.setid (Rs.getint ("id"));
U.setname (rs.getstring ("name"));
U.setemail (rs.getstring ("email"));
U.setbirthday (rs.getdate ("Birthday"));
User.add (U);
}
Code specification for JDBC and extraction of tool classes
1. Writing the configuration file dbcpfg.properties
2. Tool Type: Jdbcutil.java, direct use
3. Write your own code
Connction conn = null;
Statment stmt = null;
ResultSet rs = null;
try{
conn = Jdbcutil.getconnection ();
stmt = Conn.createstatement ();
Your code
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (RS, stmt, conn);
}
JDBC's crud
public void Myadd () {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = Jdbcutil.getconnection ();
stmt = Conn.createstatement ();
Add no result set
Stmt.executeupdate ("INSERT INTO Users" (Iname, password, email, birthday) VALUES (' Tom ', ' 123 ', ' boshi.cn ', ' 1990-02-10 ') );
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (NULL, STMT, conn);
}
}
public void Mydel () {
Connction conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = Jdbcutil.getconnection ();
stmt = Conn.createstatement ();
Delete No result set
Stmt.executeupdate ("Delete from users where id= ' 12 '");
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (RS, stmt, conn);
}
}
public void Mymodify () {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = Jdbcutil.getconnection ();
stmt = Conn.createstatement ();
Stmt.executeupdate ("Update users set Name= ' Deng ' where id = 111");//ID is an integer without quotation marks
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (Null,stmt,conn);
}
}
Get data from user
public void Mysave (user user) {
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = Jdbcutil.getconnection ();
Pre-compilation Directives
stmt = conn. Preparestatement ("INSERT into users (name, pass, email) VALUES (?,?,?,?)");
Stmt.setstring (1, User.getname ());//1 represents the first question mark in the precompiled instruction, followed by an analogy
Stmt.setstring (2, User.getpass ());
Stmt.setstring (3, User.getemail ());
Stmt.executeupdate ();
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (Null,stmt,conn);
}
}
Page out
SELECT * FROM Customer limit 0,10
Paging through the query result set for customer information
Design the page class to encapsulate information about paging
public class page{
private int pageSize = 10; Number of records displayed per page
Private List Records; Each page shows the records that DAO passes over
private int pagenum=1; Current page number, passed in by user
private int totalpage; The total number of pages, calculated
private int pageIndex; Index of each page start record, calculated
private int totalrecords; The total number of records, DAO pass over
Public Page (int pagenum, int totalrecords) {
This.pagenum = Pagenum;
This.totalrecords = totalrecords;
Calculate Total Pages
This.totalpage = totalrecords%page/size==0?totalrecords/page/size:totalrecords/page/size+1;
Start record index of the current page
This.pageindex = (pageNum-1) *pagesize;
}
}
Methods in DAO
Gets the total number of entries for the record
int Gettotalrecordsnum ();
Query paging records according to index, PageIndex: Where to start the query; Size: number of records displayed per page
list<customer> findpagerecords (int pageIndex, int size);
DAO implementation
public int Gettotalrecordsnum () {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = Jdbcutil.getconnection ();
stmt = conn. Preparestatement ("SELECT count (*) from Customer");
rs = Stmt.executequery ();
if (Rs.next ()) {
return Rs.getint (1);
}
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (Null,stmt,conn);
}
}
Each record is an object and the records are saved to save the objects. Index of the current page, number of indexes displayed per page
Public list<customer> findpagerecords (int offset, int size) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = Jdbcutil.getconnection ();
stmt = conn. Preparestatement ("SELECT * from Customer");
rs = Stmt.executequery ();//Save All Records
List<customer> cs = new arraylist<customer> ();
Iteration takes these things out.
while (Rs.next ()) {
Customer customer = new Customer ();
Customer.setid (Rs.getint ("id"));
Customer.setname (rs.getstring ("name"));
Customer.setpassword (rs.getstring ("password"));
Customer.setemail (rs.getstring ("email"));
Customer.setbirthday (rs.gtedate ("Birthday"));
Cs.add (customer);
}
Return CS;
}catch (Exception e) {
throw new RuntimeException (e);
}finally{
Jdbcutil.release (Null,stmt,conn);
}
}
Returns the Page object for data about the pages, based on the page number of the user query
Page fingpage (String pagenum);
Realize:
Public Page findpage (String num) {
private int pagenum = 1;//Default value 1
if (num!=null) {
Pagenum = Integer.parseint (num);
}
Get the total records from DAO
int pagerecords = Dao.gettotalrecordsnum ();
Data currently available, current page number, total record. Create a Page object
Page page = new page (pagenum,pagerecords);//The object has been initialized with all the information
Get Record Data
List<customer> cs = dao.findpagerecords (Page.getpageindex (), page.getpagesize ());
The general direction is a list
Page.setrecords (CS);
return page;
}
Transform servlet
public void Showallcustomers (Httpservlerequest request, httpservletresponse response) {
Get the page number the user wants to see
String pagenum = request.getparameter ("num");
Page page = s.findpage (pagenum);
Request.setattribute ("page", page);
Let it show up on another page
Request.getrequestdispacther ("/abc/1.jsp"). Forward (Request,response);
}
-------------------------
${param.name} is equivalent to Request.getparameter ("name");//for server fetching data from browser or client
${requestscope.name} is equivalent to Request.getattribute ("name"); The server passes the result to the page and gets the value saved by the server on the page
<c:foreach items= "${userlist}" var= "User" varstatus= "status" begin= "0" end= "${userlist.size}" step= "1" >
</c:forEach>
-------------------------
Transforming JSP pages
<c:foreach items= "${page.records}" var= "C" varstatus= "vs" >
<tr class= "${vs.index%2==0?" Odd ': ' Even '} ' >
<td>
<input tyep= "checkbox" Name= "IDs" value= "${c.id}"
</td>
<td>
${c.name}
</td>
<td>
${c.email}
</td>
<td>
${{c.birthday}
</td>
<td>
<a href= "${pagecontext.request.contextpath}/servlet/controller?op=editcustoerui&customerid=${c.id}" > Modify </a>
<a href= "Javascript:deleone (' ${c.id} ')" > Delete </a>
</td>
</tr>
<c:forEach>
Paging:
Page ${page.pagenum} total ${page.totalpage} page
<a href= "${pagecontext.request.contextpath}/servlet/controller?op=showallcustomers&num=${page.pagenum-1 <1?1:page.pagenum-1} "> Prev </a>
<a href= "${pagecontext.request.contextpath}/servlet/controller?op=showallcustomers&num=${page.pagenum+1 >page.totalpage?page.totalpage:page.pagenum+1} "> Next </a>
Jstl Label
<c:foreach items= "${userlist}" var= "User" varstatus= "status" begin= "0" end= "${userlist.size}" step= "1" >
Loop body
<c:out value= "${status.index}" ></c:out>
<c:out value= "${status.count}" ></c:out>
<c:out value= "${user.name}" ></c:out>
<c:out value= "${user.age}" ></c:out>
</c:forEach>
Parameter description:
1) Items: is a collection, with El expression;
2) Var: variable name, storing items for each item in the set, representing each piece of data in the collection
3) Varstatus: A variable that shows the loop state, with a few properties:
①index: starting from 0; Displays the index value of the current iteration
②count: Element position, starting from 1; Displays the line position displayed by the current iteration, by matching the statement, to achieve odd, even row of different colors for partitioning
③first: Displays True if it is the first element;
④last: Displays True if it is the last element;
4) Begin: The initial value of the loop (integral type);
5) End: End of loop (integral type);
6) Step: Step length, the value of the cycle interval (integer type);
Notes about the Java Web 2018-01-12