浅谈MVC(jsp+servlet+JavaBean简单实例)

时间:2024-11-08 07:13:51

MVC(Model View Controller) 旨在分离模型、控制、视图。是一种分层思想的体现。

mvc简单流程图

项目实例:购物车商品管理

总体设计

1实现DBHelper类
2创建实体类
3创建业务逻辑类(DAO)
4创建控制层
5创建页面层


1数据库连接

package util;

import .*;

public class DBHelper {

    public DBHelper() {
        // TODO Auto-generated constructor stub
    }
     private static final String driver="";
        private static final String url="jdbc:mysql://localhost:3306/shopping";
        private static final String username="root";
        private static final String password="123";

    private static Connection con;
    //加载驱动
    static
    {
        try{
            (driver);
        }catch (Exception e) {
            ( );
        }
    }


    //单例模式返回数据库对象
    public static Connection getConnection() throws Exception {
        if(con==null){
            con=(url,username,password);
            return con;
    }
        return con;
    }
    public static void main(String[] args) {
        try {
            Connection con=();
            if(con!=null){
                ("连接正常!");
            }else{
                ("连接异常!");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            ();
        }

    }
}

2实体类

  • 商品类
package entity;

public class Items {

    private int id;
    private String name;
    private String city;
    private int price;
    private int number;
    private String picture;

    public Items() {

    }

    public Items(int id, String name, String city, int price, int number, String picture) {

        this.id = id;
        this.name = name;
        this.city = city;
        this.price = price;
        this.number = number;
        this.picture = picture;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }

    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return this.getId() + this.getName().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        if (this == obj) {
            return true;
        }
        if (obj instanceof Items) {
            Items i = (Items) obj;
            if (this.getId() == () && this.getName().equals(())) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    @Override
    public String toString() {

        return "商品编号" + this.getId() + ",商品名称" + this.getName();
    }

}

  • 购物车类
package entity;

import ;
import ;
import ;
import ;



//购物车类
public class Cart {

    // 购买商品集合
    private HashMap<Items, Integer> goods;

    // 购物车总金额
    private double totalPrice;


    public Cart() {

        goods = new HashMap<Items, Integer>();
        totalPrice = 0.0;
    }

    public HashMap<Items, Integer> getGoods() {
        return goods;
    }

    public void setGoods(HashMap<Items, Integer> goods) {
        this.goods = goods;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }
   //添加商品
    public boolean addGoodsInCart(Items item,int number){

        if((item)){
            (item, (item)+number);
        }else{
            (item, number);
        }


        calTotalPrice();//重新计算购物车总金额
        return true;
    }
    //删除
    public boolean removeGoodsFromCart(Items item){
        (item);
        return true;
    }
    //统计总金额
    public double calTotalPrice(){
        double sum=0.0;
        Set<Items> keys= ();//获得键集合
        Iterator<Items> it=();//获得迭代器对象
        while(()){
            Items i= ();
            sum +=()* (i);
        }
        this.setTotalPrice(sum);//设置购物车总金额
        return this.getTotalPrice();
    }
    //测试购物车类
    public static void main(String[] args) {

        //创建两个商品对象
        Items i1 =new Items(1,"沃特篮球鞋","温州",200,500,"");
        Items i2 =new Items(2,"李宁篮球鞋","广州",300,500,"");
        Items i3 =new Items(2,"李宁篮球鞋","广州",300,500,"");
        Cart c=new Cart();
        (i1, 1);
        (i2, 2);
        //再次购买李宁 三双
        (i3, 3);
        //遍历购物商品集合
        Set<<Items, Integer>> items=().entrySet();
        for(<Items, Integer> obj:items){

            (obj);
        }
        ("总金额"+());
    }
}

DAO层(javabean)

package dao;

import ;
import ;
import ;
import ;

import ;

import ;

//商品的业务逻辑类
public class ItemsDAO {

    // 获得所有的商品信息
    public ArrayList<Items> getAllItems() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
        try {
            conn = ();
            String sql = "select * from items;"; // SQL语句
            stmt = (sql);
            rs = ();
            while (()) {
                Items item = new Items();
                (("id"));
                (("name"));
                (("city"));
                (("number"));
                (("price"));
                (("picture"));
                (item);// 把一个商品加入集合
            }
            return list; // 返回集合。
        } catch (Exception ex) {
            ();
            return null;
        } finally {
            // 释放数据集对象
            if (rs != null) {
                try {
                    ();
                    rs = null;
                } catch (Exception ex) {
                    ();
                }
            }
            // 释放语句对象
            if (stmt != null) {
                try {
                    ();
                    stmt = null;
                } catch (Exception ex) {
                    ();
                }
            }
        }

    }

    // 根据商品编号获得商品资料
    public Items getItemsById(int id) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = ();
            String sql = "select * from items where id=?;"; // SQL语句
            stmt = (sql);
            (1, id);
            rs = ();
            if (()) {
                Items item = new Items();
                (("id"));
                (("name"));
                (("city"));
                (("number"));
                (("price"));
                (("picture"));
                return item;
            } else {
                return null;
            }

        } catch (Exception ex) {
            ();
            return null;
        } finally {
            // 释放数据集对象
            if (rs != null) {
                try {
                    ();
                    rs = null;
                } catch (Exception ex) {
                    ();
                }
            }
            // 释放语句对象
            if (stmt != null) {
                try {
                    ();
                    stmt = null;
                } catch (Exception ex) {
                    ();
                }
            }

        }
    }
    //获取最近浏览的前五条商品信息
    public ArrayList<Items> getViewList(String list)
    {
        ("list:"+list);
        ArrayList<Items> itemlist = new ArrayList<Items>();
        int iCount=5; //每次返回前五条记录
        if(list!=null&&()>0)
        {
            String[] arr = ("#");
            ("="+);
            //如果商品记录大于等于5条
            if(>=5)
            {
               for(int i=-1;i>=-iCount;i--)
               {
                  (getItemsById((arr[i])));  
               }
            }
            else
            {
                for(int i=-1;i>=0;i--)
                {
                    (getItemsById((arr[i])));
                }
            }
            return itemlist;
        }
        else
        {
            return null;
        }

    }

}

Servlet控制层

package servlet;

import ;
import ;

import ;
import ;
import ;
import ;

import ;
import ;
import ;

public class CartServlet extends HttpServlet {

    private String action;     // action对象有三个动作add show delete
    private ItemsDAO idao = new ItemsDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        ("text/html;charset=utf-8");
        PrintWriter out = ();
        if (("action") != null) {
            this.action = ("action");
            if (("add"))// 添加商品进购物车
            {
                if (addToCart(request, response)) {
                    ("/").forward(request, response);
                } else {
                    ("/").forward(request, response);
                }
            }

             if(("show")){              //显示购物车
                    ("/").forward(request, response);
             }
             if(("delete")){
                 if(deleteFromCart(request,response)){
                     ("/").forward(request, response); 
                 }else{
                     ("/").forward(request, response); 
                 }
             }
             }
             }



    private boolean addToCart(HttpServletRequest request, HttpServletResponse response) {
        String id = ("id");
        String number = ("num");
        Items item = ((id));

        // 是否第一次给购物车添加商品,需要给session中创建一个新的购物车对象
        if (().getAttribute("cart") == null) {
            Cart cart = new Cart();
            ().setAttribute("cart", cart);
        }
        Cart cart = (Cart) ().getAttribute("cart");
        if ((item, (number))) {
            return true;
        } else {
            return false;
        }
    }
    private boolean deleteFromCart(HttpServletRequest request,HttpServletResponse response){


        String id=("id");
        Cart cart=(Cart)().getAttribute("cart");
        Items item=((id));
        if((item)){
            return true;
        }else{
            return false;
        }
    }

    public CartServlet() {
        // TODO Auto-generated constructor stub
    }
    public void init() throws ServletException {
        // Put your code here
    }

}

jsp页面

<%@page import=""%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import=""%>
<%@ page import=""%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<!--
    <link rel="stylesheet" type="text/css" href="">
    -->
    <style type="text/css">
       div{
          float:left;
          margin: 10px;
       }
       div dd{
          margin:0px;
          font-size:10pt;
       }
       div dd.dd_name
       {
          color:blue;
       }
       div dd.dd_city
       {
          color:#000;
       }
    </style>
  </head>

  <body>
    <h1 >商品展示</h1>
    <hr>

    <center>
    <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td>

          <!-- 商品循环开始 -->
           <% 
               ItemsDAO itemsDao = new ItemsDAO(); 
            ArrayList<Items> list=();
               if(list!=null&&()>0)
               {
                   for(int i=0;i<();i++)
                   {
                      Items item = list.get(i);
           %>   
          <div>
             <dl>
               <dt>
                 <a href="?id=<%=()%>"><img src="images/<%=()%>" width="120" height="90" border="1"/></a>
               </dt>
               <dd class="dd_name"><%=() %></dd> 
               <dd class="dd_city">产地:<%=() %>&nbsp;&nbsp;价格¥:<%=() %></dd> 
             </dl>
          </div>
          <!-- 商品循环结束 -->

          <%
                   }
              } 
          %>
        </td>
      </tr>
    </table>
    </center>
  </body>
</html>

<%@ page language="java" import=".*" contentType="text/html; charset=utf-8" %>
<%@ page import=""%>
<%@ page import=""%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP '' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="">
    -->
    <link href="css/" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="js/"></script>
    <script type="text/javascript" src="js/"></script>
    <script type="text/javascript">
      function selflog_show(id)
      { 
         var num =  ("number").value; 
         ({id: 'haoyue_creat',title: '购物成功',width: 600,height:400, link: '<%=path%>/servlet/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
      }
      function add()
      {
         var num = parseInt(("number").value);
         if(num<100)
         {
            ("number").value = ++num;
         }
      }
      function sub()
      {
         var num = parseInt(("number").value);
         if(num>1)
         {
            ("number").value = --num;
         }
      }

    </script>

    <style type="text/css">
       hr{

         border-color:FF7F00; 
       }

       div{
          float:left;
          margin-left: 30px;
          margin-right:30px;
          margin-top: 5px;
          margin-bottom: 5px;

       }
       div dd{
          margin:0px;
          font-size:10pt;
       }
       div dd.dd_name
       {
          color:blue;
       }
       div dd.dd_city
       {
          color:#000;
       }
       div #cart
       {
         margin:0px auto;
         text-align:right; 
       }
       span{
         padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer;
       }
       a{
          text-decoration: none; 
       }
    </style>
  </head>

  <body>
    <h1>商品详情</h1>
    <a href="">首页</a> >> <a href="">商品列表</a>
    <hr>
    <center>
      <table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <!-- 商品详情 -->
          <% 
             ItemsDAO itemDao = new ItemsDAO();
             Items item = ((request.getParameter("id")));
             if(item!=null)
             {
          %>
          <td width="70%" valign="top">
             <table>
               <tr>
                 <td rowspan="5"><img src="images/<%=()%>" width="200" height="160"/></td>
               </tr>
               <tr>
                 <td><B><%=() %></B></td> 
               </tr>
               <tr>
                 <td>产地:<%=()%></td>
               </tr>
               <tr>
                 <td>价格:<%=() %></td>
               </tr>
               <tr>
                 <td>购买数量:<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" onclick="add();">+</span></td>
               </tr> 
             </table>
             <div id="cart">
               <img src="images/buy_now.png"><a href="javascript:selflog_show(<%=()%>)"><img src="images/in_cart.png"></a><a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a>
             </div>
          </td>
          <% 
            }
          %>
          <% 
              String list ="";
              //从客户端获得Cookies集合
              Cookie[] cookies = request.getCookies();
              //遍历这个Cookies集合
              if(cookies!=null&&>0)
              {
                  for(Cookie c:cookies)
                  {
                      if(().equals("ListViewCookie"))
                      {
                         list = ();
                      }
                  }
              }

              list+=request.getParameter("id")+"#";
              //如果浏览记录超过1000条,清零.
              String[] arr = list.split("#");
              if(arr!=null&&>0)
              {
                  if(>=1000)
                  {
                      list="";
                  }
              }
              Cookie cookie = new Cookie("ListViewCookie",list);
              response.addCookie(cookie);

          %>
          <!-- 浏览过的商品 -->
          <td width="30%" bgcolor="#EEE" align="center">
             <br>
             <b><font color="#FF7F00">您浏览过的商品</font></b><br>
             <!-- 循环开始 -->
             <% 
                ArrayList<Items> itemlist = (list);
                if(itemlist!=null&&()>0 )
                {
                   ("="+());
                   for(Items i:itemlist)
                   {

             %>
             <div>
             <dl>
               <dt>
                 <a href="?id=<%=()%>"><img src="images/<%=() %>" width="120" height="90" border="1"/></a>
               </dt>
               <dd class="dd_name"><%=() %></dd> 
               <dd class="dd_city">产地:<%=() %>&nbsp;&nbsp;价格:<%=() %></dd> 
             </dl>
             </div>
             <% 
                   }
                }
             %>
             <!-- 循环结束 -->
          </td>
        </tr>
      </table>
    </center>
  </body>
</html>

<%@ page language="java" import=".*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP '' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="">
    -->

  </head>

  <body>
    <center>
      <img src="images/add_cart_success.jpg"/>
      <hr>
      <% 
         String id = request.getParameter("id");
         String num = request.getParameter("num");
      %>
             您成功购买了<%=num%>件商品编号为<%=id%>的商品&nbsp;&nbsp;&nbsp;&nbsp;
      <br>
      <br>
      <br>

    </center>
  </body>
</html>

<%@ page language="java" import=".*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP '' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="">
    -->

  </head>

  <body>
    <center>
      <img src="images/add_cart_failure.jpg"/>
      <hr>

      <br>
      <br>
      <br>

    </center>
  </body>
</html>

<%@ page language="java" import=".*" contentType="text/html; charset=utf-8"%>
<%@ page import="" %>
<%@ page import="" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP '' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="">
    -->
    <link type="text/css" rel="stylesheet" href="css/" />
    <script language="javascript">
     function delcfm(){
         if(!comfirm("确认要删除?")){
             =false;
         }
     }
   </script>
  </head>

  <body>
   <h1>我的购物车</h1>
   <a href="">首页</a> >> <a href="">商品列表</a>
   <hr> 
   <div id="shopping">
   <form action="" method="">       
            <table>
                <tr>
                    <th>商品名称</th>
                    <th>商品单价</th>
                    <th>商品价格</th>
                    <th>购买数量</th>
                    <th>操作</th>
                </tr>
                <% 
                   //首先判断session中是否有购物车对象
                   if(request.getSession().getAttribute("cart")!=null)
                   {
                %>
                <!-- 循环的开始 -->
                     <% 
                         Cart cart=(Cart)request.getSession().getAttribute("cart");
                     HashMap<Items,Integer> goods=();
                     Set<Items> items=();
                     Iterator<Items> it=();

                     while(()){
                         Items i=it.next();
                         %> 
                <tr name="products" id="product_id_1">
                    <td class="thumb"><img src="images/<%=()%>" /><a href=""><%=()%></a></td>
                    <td class="number"><%=() %></td>
                    <td class="price" id="price_id_1">
                        <span><%=()*goods.get(i) %></span>
                        <input type="hidden" value="" />
                    </td>
                    <td class="number">
                        <%=goods.get(i)%>                   
                    </td>                        
                    <td class="delete">
                      <a href="servlet/CartServlet?action=delete&id=<%=()%>" onclick="delcfm();">删除</a>   <!-- onclick 调用js删除方法  -->                           
                    </td>
                </tr>
                     <% 
                     }
                     %>
                <!--循环的结束-->

            </table>
             <div class="total"><span id="total">总计:<%=() %></span></div>
              <% 
                }
             %>
            <div class="button"><input type="submit" value="" /></div>
        </form>
    </div>
  </body>
</html>



servlet类一定不要忘记配置xml文档!!!切记!!


<servlet>
    <servlet-name>CartServlet</servlet-name>
    <servlet-class></servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CartServlet</servlet-name>
    <url-pattern>/servlet/CartServlet</url-pattern>
  </servlet-mapping>

参照慕课网课程项目实例