1. 程式人生 > >關於java web的筆記2018-01-12

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

tint on() 執行sql first for email 翻譯 金額 final

需求: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