Servlet的Model2模型详解及简单购物车的实现

来源:互联网 发布:发卡平台源码2016免费 编辑:程序博客网 时间:2024/06/05 15:01

Java Web应用程序设计中使用了两个模型,简称Model1和Model2


Model1只适用于非常小型的应用程序,我们建议对所有程序都使用Model2


1,Model2概述:

Model2基于MVC(model-view-controller)设计模式


模型Model负责封装应用程序的数据和业务逻辑      

使用POJO,即简单的java对象。许多人用javaBean来保存模型对象的状态,并将业务逻辑转移到一个Action类中

javaBean必须有一个午餐构造器,以及用于访问属性的set/get方法,还必须是可序列化的


视图view负责应用程序的显示   一般用JSP页面来显示

在JS页面中,利用EL表达式和定制标签来显示值


controller负责接收用户的输入,并命令view和model做出相应的修改

Spring MVC这类框架是用Servlet Controller  ;Struct2,则是使用过滤器

在Model2,每一个HTTP请求都必须被定向到控制器中,请求的URI(Uniform Request Identifier)告诉控制器调用哪一个action

例如:

想让程序发送一个Add Product表单,要使用URI: http://domain/appName/product_input

想要应用程序保存一项产品,要使用:http://domain/appName/product_save

它还会将模型对象保存在一个可以通过View访问到的地方并通过View显示出来


2.下面通过一个购物实例来帮助大家熟悉Model2模型


首先创建一个Product类

import java.io.Serializable;public class Product implements Serializable {private static final long serialVersionUID=748392348L;private String name;private String description;private float price;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;
}}


ProductForm类  

Form类被映射到HTML表单,用于验证HTML表单输入的数据是否符合要求

第二用途是保存用户的输入,用于验证失败时在他的原始表单中重新显示出来,让用户知道输入错在哪

public class ProductForm  {private String name;private String description;private String price;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getPrice() {return price;}public void setPrice(String price) {this.price = price;}}

ColltrollerServlet类 就是控制器

判断请求URI的地址来调用适用的action以及View

import java.io.IOException;import java.util.List;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet(name="ControllerServlet",urlPatterns={"/product_input","/product_save"})public class ControllerServlet extends HttpServlet {private static final long serialVersionUID=98279L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubprocess(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubprocess(req,resp);}private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO Auto-generated method stubString uri=req.getRequestURI();int lastIndex=uri.lastIndexOf("/");String action=uri.substring(lastIndex+1);String dispatchUrl=null;if(action.equals("product_input")){//no action class,there is nothing to be donedispatchUrl="/ProductForm.jsp";}else if(action.equals("product_save")){ProductForm productForm=new ProductForm();productForm.setName(req.getParameter("name"));productForm.setDescription(req.getParameter("description"));productForm.setPrice(req.getParameter("price"));//validate ProductFormProductValidator productValidator=new ProductValidator();List<String> errors=productValidator.validate(productForm);if(errors.isEmpty()){//create Product from ProductFormProduct product=new Product();product.setName(productForm.getName());product.setDescription(productForm.getDescription());product.setPrice(Float.parseFloat(productForm.getPrice()));//no validation error ,execute action methodSaveProduct saveProduct=new SaveProduct();saveProduct.save(product);//store model in a scope variable for the ProductDetails.jspreq.setAttribute("product", product);dispatchUrl="/ProductDetails.jsp";}else{req.setAttribute("errors", errors);req.setAttribute("form", productForm);dispatchUrl="/ProductForm.jsp";}}//forward to a viewif(dispatchUrl!=null){ RequestDispatcher  rd=req.getRequestDispatcher(dispatchUrl); rd.forward(req, resp);}}}



Aciton类


SaveProductAction类,负责将产品保存到存储设备中,比如数据库

public class SaveProduct {public void save(Product product){//insert Product to the database}}



View 视图

ProductDetails.jsp页面用于显示通过验证的产品信息

<body>   <div id="global"><h4>The product has been saved</h4>   <p>   <h5>Details:</h5>   Product Name:${product.name }<br/>   Description: ${product.description }<br>   Price: ${product.price }<br>      </p></div><br>  </body>


ProductForm.jsp用于获取用户输入的产品信息

并且还有显示错误信息,以及重新显示无效的值的功能

<body>      <dir id="global">    <h3>Add a product</h3>    <c if test="${requestScope.errors!=null }">    <p id="errors">Error(s)!<ul>        <li>${requestScope.errors[0]}</li>     <li>${requestScope.errors[1]}</li>    </ul></p>    </c>    <form method="post" action="product_save">    <table>    <tr>     <td>Product Name:</td>    <td><input type="text" name="name"  value="${form.name }"></td>    </tr>    <tr>    <td>Description:</td>    <td><input type="text" name="description"  value="${form.description}"></td>        </tr>    <tr>    <td>Price:</td>    <td><input type="text" name="price"  value="${form.price }"></td>        </tr>    <tr><td><input type="reset"></td>    <td><input type="submit" value="Add Product"></td></tr>        </table></form>    </dir><br>  </body>



验证器

在执行Action前,输入验证是一个重要的步骤


ProductValidator用于检验用户输入是否符合标准

import java.util.ArrayList;import java.util.List;public class ProductValidator           {public List<String> validate(ProductForm productForm){List<String> errors=new ArrayList<String>();String name=productForm.getName();if(name==null||name.trim().isEmpty()){errors.add("Product must a name");}String price=productForm.getPrice();if(price==null||price.trim().isEmpty()){errors.add("Product must a price");}else{try{Float.parseFloat(price);}catch(NumberFormatException e){errors.add("Invalid price value");}}return errors;}}


下面通过 http://localhost:8080/app/product_input来测试

测试结果






2 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 微店没收到货却显示已收货怎么办? 手机存的照片误删了怎么办 魔兽世界把要用的装备分解了怎么办 邻居家的狗见到我就叫怎么办 我的世界玩的时间长会卡应该怎么办 网易我的世界密码账号都忘了怎么办 我的世界创建世界画面乱码了怎么办 网易我的世界云端存档不够用怎么办 玩刺激战场带耳机声音有延迟怎么办 我的世界手机版狼变色怎么办 我的世界开了光影太阳太刺眼怎么办 我的世界饥饿值掉的慢怎么办 我的世界合装备过于昂贵怎么办 我的世界故事模式屏幕是黑的怎么办 人物只剩下轮廓的图用ps怎么办 两年义务兵考军校分数不够怎么办 大学生兵考上军校后原学籍怎么办 我的世界工业附魔到精准采集怎么办 交换生在台期间遗失通行证怎么办 驾驶证上的号码是士兵证号怎么办 士兵证丢了但是要买飞机票怎么办 君泰保安公司不发工资怎么办 冬天洗棉衣后有一圈白色怎么办 买了一批化肥没有执行标准怎么办 防护栏下面打不了膨胀螺丝怎么办 不知道怀孕照了x射线怎么办 腹部照了x光片照了三次怎么办 像在工厂戴的静电帽弄丢了怎么办 诈骗犯把钱被转到别人账户怎么办 狗狗5个月在家随地大小便怎么办 上课放屁放的快没憋到老是放怎么办 丈夫有外遇并跟小三有一儿子怎么办 借款夫妻双亡借出去的钱怎么办? 橡胶底的劳保鞋开胶了怎么办? 求部队停止有偿服务内部超市怎么办 晋江买了全本还是有防盗章节怎么办 宝宝没有穿衣服的地方长疙瘩怎么办 詹姆斯士兵12魔术贴老是掉怎么办 手机版本不支持陌陌视频聊天怎么办 私人单位不给员工写收入证明怎么办 cad图形缩小后找不到图了怎么办