關於java web的筆記2018-01-12

來源:互聯網
上載者:User

標籤:購物   forward   dml   發送   其他   amp   一個   ram   關於   

需求:1、寫一個商品類,有商品編號、商品名稱、商品分類、商品單價屬性。2、寫一個商品條目資訊類,有商品和數量兩個屬性,有商品總價格方法。
3、寫一個購物車類,有添加商品方法、查看訂單資訊,刪除商品,修改商品,清空購物車,求購物車中所有商品總金額方法。4、寫一個測試類別,測試上述方法。
商品類:
[java] view plain copy
public class Product {
private int productId;// 商品編號
private String productName;// 商品名稱
private String category;// 商品分類
private double price;// 單價

public Product() {// 無參構造
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;
}

}
商品條目資訊類:
[java] view plain copy
public class ProductItem {
private Product product;//購買的商品
private int count;//商品數量
public double totalMoney(){//小計
double price=product.getPrice();//擷取商品單價
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;
}

}

購物車類:
[java] view plain copy
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class ShoppingCart {//購物車
//key:商品編號 value:商品條目
private Map<Integer,ProductItem> map=new LinkedHashMap<Integer,ProductItem>();

public void addProduct(Product p){//添加商品
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(){//查看訂單資訊
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.getProductId()+",商品名稱:"
+product.getProductName()+",單價:"+product.getPrice()+",數量:"+productItem.getCount()
+",小計:"+productItem.totalMoney());
}
}
public boolean deleteProduct(int productId){//刪除商品
if(map.containsKey(productId)){
map.remove(productId);
return true;
}
return false;
}
public boolean modifyProduct(int productId,int count){//修改
if(map.containsKey(productId)){
if(count>=1){
ProductItem productItem = map.get(productId);
productItem.setCount(count);
return true;
}else if(count==0){//刪除
deleteProduct(productId);
return true;
}
}
return false;
}

public void clearCart(){//清空購
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;
}
}


jsp=html中寫java代碼
jsp中的內容就是對應著java中的內容,最終要編譯成class檔案
把jsp頁面中的html排版標籤輸出到瀏覽器:out.write("<br>");//是一個字元輸出資料流輸出的
jsp中的java代碼是如何執行的:jsp中的java代碼被原封不動地被翻譯到了servlet的service方法中
伺服器在調用jsp時,會給jsp傳遞的對象:request,response,pageContext,config,session,page,out
指令是給伺服器用的,告訴伺服器應當如何對待jsp頁面
<%@include file="/a.jsp"%>
動作指令:
<jsp:include page="/a.jsp">
</jsp:include>
請求轉寄,指向被轉寄的頁面
<jsp:forward page="/a.jsp">
<%--傳遞請求參數,供其他標籤使用--%>
<jsp:param name="a" value="123"></jsp:param>
<jsp:param name="b" value="456"></jsp:param>
</jsp:forword>
Statement:代表SQL語句,向資料庫發送並執行SQL語句
ResultSet executeQuery(String sql):僅僅執行資料庫的查詢操作,返回查詢的結果集
int executeUpdate(String sql):執行DML,返回影響操作資料記錄的行數
int num = stmt.executeUpdate("update users set id=‘111‘");
boolean execute(String sql):執行sql語句,如果有傳回值則返回true,沒有傳回值返回false
遍曆的結果集列印到控制台沒有鳥用,應該封裝到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);
}
jdbc的編碼規範和工具類的抽取
1.編寫設定檔dbcpfg.properties
2.工具類:JdbcUtil.java,直接拿來用
3.編寫自己的代碼
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的CRUD
public void myAdd(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
stmt = conn.createStatement();
// 添加沒有結果集
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();
// 刪除沒有結果集
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是整數,不用引號
}catch(Exception e){
throw new RuntimeException(e);
}finally{
JdbcUtil.release(null,stmt,conn);
}
}
// 從user中擷取資料
public void mySave(User user){
Connection conn = null;
PreparedStatement stmt = null;
try{
conn = JdbcUtil.getConnection();
// 先行編譯指令
stmt = conn.PrepareStatement("insert into users(name, pass, email) values (?,?,?,?)");
stmt.setString(1, user.getName());// 1代表先行編譯指令中的第一個問號,之後一次類推
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);
}
}
分頁
select * from customer limit 0,10
對客戶資訊的查詢結果集進行分頁
// 設計page類,封裝與分頁有關的資訊
public class Page{
private int pageSize = 10; // 每頁顯示的記錄條數
private List records; // 每頁顯示的記錄,dao傳過來
private int pageNum=1; // 當前頁碼,由使用者傳進來
private int totalPage; // 總共的頁數,計算出來

private int pageIndex; // 每頁開始記錄的索引,計算出來
private int totalRecords; // 總共的記錄個數,dao傳過來
public Page(int pageNum, int totalRecords){
this.pageNum = pageNum;
this.totalRecords = totalRecords;
// 計算總頁數
this.totalPage = totalRecords%page/Size==0?totalRecords/page/Size:totalRecords/page/Size+1;
// 當前頁的開始記錄索引
this.pageIndex = (pageNum-1)*pageSize;
}
}
// dao中的方法
// 擷取記錄的總條目數
int getTotalRecordsNum();
// 根據索引查詢分頁記錄,pageIndex:開始查詢的位置;size:每頁顯示的記錄條數
List<Customer> findPageRecords(int pageIndex, int size);

// dao 實現
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);
}
}
// 每一個記錄為一個對象,把記錄儲存起來就是要把這些對象存起來.當前頁的索引,每頁顯示的索引個數
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();// 儲存了所有的記錄
List<Customer> cs = new ArrayList<Customer>();
// 迭代把這些東東取出來
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);
}
}

// 根據使用者查詢的頁碼,返回有關該頁面資料的page對象
Page fingPage(String pageNum);
實現:
public Page findPage(String num){
private int pageNum = 1;// 預設值1
if(num!=null){
pageNum = Integer.parseInt(num);
}
// 從dao擷取總的記錄
int pageRecords = dao.getTotalRecordsNum();
// 目前有的資料,當前頁碼;總記錄。建立一個Page對象
Page page = new Page(pageNum,pageRecords);// 該對象已經初始化了,包含了所有的資訊
// 擷取記錄資料
List<Customer> cs = dao.findPageRecords(page.getPageIndex(),page.getPageSize());
// 大方向是一個list
page.setRecords(cs);
return page;

}

// 改造servlet
public void showAllCustomers(HttpServleRequest request, HttpServletResponse response){
// 擷取使用者要看的頁碼
String pageNum = request.getParameter("num");
Page page = s.findPage(pageNum);
request.setAttribute("page",page);
// 讓其在別的頁面顯示出來
request.getRequestDispacther("/abc/1.jsp").forward(request,response);
}
-------------------------
${param.name}等價於request.getParameter("name");// 用於伺服器從瀏覽器或用戶端取資料
${requestScope.name}等價於request.getAttribute("name"); // 伺服器傳遞結果到頁面,在頁面擷取伺服器儲存的值

<c:forEach items="${userList}" var="user" varStatus="status" begin="0" end="${userList.size}" step="1">
</c:forEach>
-------------------------
改造jsp頁面
<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}">修改</a>
<a href="javaScript:deleOne(‘${c.id}‘)">刪除</a>
</td>
</tr>
<c:forEach>
分頁:
第${page.pageNum}頁&nbsp;&nbsp;總共${page.totalPage}頁&nbsp;&nbsp;
<a href="${pageContext.request.contextPath}/servlet/Controller?op=showAllCustomers&num=${page.pageNum-1<1?1:page.pageNum-1}">上一頁</a>
<a href="${pageContext.request.contextPath}/servlet/Controller?op=showAllCustomers&num=${page.pageNum+1>page.totalPage?page.totalPage:page.pageNum+1}">下一頁</a>

jstl標籤
<c:forEach items="${userList}" var="user" varStatus="status" begin="0" end="${userList.size}" step="1" >
//迴圈體
<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>

參數說明:
1)items:是集合,用EL運算式;
2)var:變數名,存放items各個項 ,代表集合中每一條資料
3)varStatus: 顯示迴圈狀態的變數,有一下幾個屬性:
①index:從0開始; 顯示當前迭代的索引值
②count:元素位置,從1開始; 顯示當前迭代顯示的行位置,通過配合判斷語句,實現給奇、偶行著不同的色,以進行分區
③first:如果是第一個元素則顯示true;
④last:如果是最後一個元素則顯示true;
4)begin:迴圈的初始值(整型);
5)end: 迴圈結束(整型);
6)step:步長,迴圈間隔的數值(整型);

關於java web的筆記2018-01-12

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.