Servlet是運行在服務器上的一段小程序,一個servlet就是一個java類,能夠經過 請求/響應 的編程模型來訪問這段程序。java
1.編寫一個servlet程序要通過三個步驟web
1>編寫一個java類,該類要繼承HttpServlet類編程
2>重寫HttpServlet中deGet()或者doPost()方法小程序
3>在web.xml中註冊Servlet瀏覽器
2.Servlet執行流程服務器
1>瀏覽器請求,會有一個url,例如:...servlet/testOne
app
2>到web.xml文件中,找url-pattern測試
<servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>/servlet/testOne</url-pattern> </servlet-mapping>
3>找url-pattern對應的servlet-name對應的servlet-class,以下this
<servlet> <servlet-name>test</servlet-name> <servlet-class>test.helloWorld(類helloWord的具體路徑)</servlet-class> </servlet>
4>找到類helloWorldurl
public class helloWorld extends HttpServlet{ //具體方法 }
3.Servlet生命週期
1>瀏覽器發送request請求
2>判斷Servlet實例是否存在
3>不存在的話,裝載Servlet類並建立實例
4>調用init()方法
5>調用service方法
6>調用Destroy方法
實戰項目
項目:使用servlet技術實現購物車效果
設計:購物車類的設計
購物車裏面主要有 商品 +價格
所以,能夠設計一個 商品類,而後加上 數量 構成 購物車類。
商品類以下
public class Items{ //商品編號 private int id; //商品名稱 private String name; //商品價格 private int price; }
購物車類以下
public class Char{ //購買商品集合 private HashMap<Items,Integer> goods; //購物車總金額 private double totalPrice; //構造方法,初始化變量 public Char() { goods = new HashMap<Items,Integer>(); totalPrice = 0.0; } //添加商品到購物車方法 public boolean addGoos(Items item,int number) { goods.put(item,number); //添加後須要從新計算購物車的價格 calTotalPrice(); return true; } //刪除商品方法 public boolean delGoods(Items item) { goods.remove(item); //添加後須要從新計算購物車的價格 calTotalPrice(); return true; } //統計購物車的總金額 public double calTotalPrice() { double sun = 0.0; //得到hashMap全部的鍵值 Set<Items> keys = goods.keySet(); //使用迭代器 Iterator<Items> it = keys.iterator(); while(it.hasNext()) { Items i = it.next(); sum = sum + i.getPrice*goods.get(i); } //設置購物車總金額 this.setTotalPrice(sum); //返回購物車總價 return this.getTotalPrice(); } //測試購物車類 public static void main(String[] args) { //建立商品對象 Items it1 = new Items(1,"李寧",200); Items it2 = new Itmes(2,"耐克",300); //建立購物車類 Char c = new Char(); //添加商品 c.addChar(it1,2); c.addChar(it2,3); //商品總價格 double price = c.getTotalPrice(); } }