浅谈model1模式及使用model1模式来实现浏览商品

版权声明: https://blog.csdn.net/acDream_/article/details/83448046

需要实现功能:

1.从数据库中读取各个商品的信息

2.点击某个图片会显示商品的详细信息

3.在显示商品页面的右边会显示你最近浏览过的商品

效果图: 

 

 使用model1模式来实现

1.需要实现数据库链接的DBHelper类

2.需要实体类

3.需要业务逻辑类(Model)-其中封装了对数据处理的方法

4.需要显示的JSP页面(View)-显示

实际上model1方式实现了MVC模式中的MV,因为JSP页面不仅要实现显示的效果还要进行调用业务逻辑,单单一个JSP页面中就包括了C和V

 下面是实现浏览商品的代码:

1.DBHelper类

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBHelper {
	private static String URL = "jdbc:mysql://localhost:3306/shopping";
	private static String DRIVER = "com.mysql.jdbc.Driver";
	private static String USERNAME = "root";
	private static String PASSWORD = "root";
	
	
	public static Connection getConn(){
		Connection conn = null;
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	
	public static void close(Connection conn,Statement sta,ResultSet rs){
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(sta!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(rs!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}

2.Sp:

package enptity;

public class Sp {
	private int id;
	private String name;
	private int kcl;
	private double price;
	private String js;
	private String place;
	private String picPath;

	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 int getKcl() {
		return kcl;
	}

	public void setKcl(int kcl) {
		this.kcl = kcl;
	}

	public double getPrice() {
		return price;
	}

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

	public String getJs() {
		return js;
	}

	public void setJs(String js) {
		this.js = js;
	}

	public String getPlace() {
		return place;
	}

	public void setPlace(String place) {
		this.place = place;
	}

	public String getPicPath() {
		return picPath;
	}

	public void setPicPath(String picPath) {
		this.picPath = picPath;
	}

	public Sp(){
		
	}
	
	public Sp(int id,String name,int kcl,double price,String js,String place,String picPath){
		setId(id);
		setName(name);
		setKcl(kcl);
		setPrice(price);
		setJs(js);
		setPlace(place);
		setPicPath(picPath);
	}
}

3.SpDao(Model)

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import util.DBHelper;

import enptity.Sp;

public class SpDao {
	Connection conn = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	/**
	 * 得到所有的商品信息
	 * @return
	 */
	public List<Sp> getAllSp(){
		List<Sp> list = new ArrayList<Sp>();
		try {
			conn = DBHelper.getConn();
			String sql = "select * from sp";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				list.add(new Sp(rs.getInt("id"), rs.getString("name"), rs.getInt("kcl"), rs.getDouble("price"), rs.getString("js"), rs.getString("place"), rs.getString("picPath")));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBHelper.close(conn, ps, rs);
		}
		return list;
	}
	
	public Sp getSp(int id){	
		try {
			conn = DBHelper.getConn();
			String sql = "select * from sp where id = ?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if(rs.next()){
				return new Sp(rs.getInt("id"), rs.getString("name"), rs.getInt("kcl"), rs.getDouble("price"), rs.getString("js"), rs.getString("place"), rs.getString("picPath"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DBHelper.close(conn, ps, rs);
		}
		return null;
	}
}

Veiw:

1.shop.jsp

<%@page import="dao.SpDao"%>
<%@page import="enptity.Sp"%>
<%@ page language="java" import="java.util.*" pageEncoding="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 'index.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="styles.css">
	-->
  </head>
  
  <body>
  <table align="center">
  <%
  	int count = 1;
  	SpDao spDao = new SpDao();
  	List<Sp> list = spDao.getAllSp();
  	out.print("<tr>");
  	for(Sp sp:list){
  		out.print("<td><a href='detail.jsp?id="+sp.getId()+"'><img alt='未找到该图片' src='image/"+sp.getPicPath()+"' width='200' height='200'></a><br>"+sp.getName()+",¥"+sp.getPrice()+"</td>");
  		out.print("<td width='100'></td>");
  		if(count%3==0){
  			out.print("</tr><tr>");
  		}
  		count++;
  	}
   %>
    </table>
  </body>
</html>

2.detail.jsp

<%@page import="enptity.Sp"%>
<%@page import="dao.SpDao"%>
<%@ page language="java" import="java.util.*" pageEncoding="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 'detail.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="styles.css">
	-->

    <style type="text/css">
<!--
#Layer1 {
	position:absolute;
	left:1209px;
	top:43px;
	width:144px;
	height:268px;
	z-index:1;
}
-->
    </style>
</head>
  
  <body> 
  <div id="Layer1">
  <table>
  <tr>
  <td>
  <b><font size="3">你浏览过的商品</font></b>
  </td>
  </tr>
  <%
  	SpDao spDao = new SpDao();
  	int id = 0;
  	if(request.getParameter("id")!=null){
    	id = Integer.valueOf(request.getParameter("id"));
    }
  	Cookie[] cookies = request.getCookies();
  	if(cookies==null){
  		//System.out.print("go");
  		Cookie cookie = new Cookie("jl",id+"*");
  		cookie.setMaxAge(24*60*60*10);
  		response.addCookie(cookie);
  	}else{
  		//System.out.print("to");
  		String idStr = "";
  		boolean isHave = false;
  		for(Cookie cookie:cookies){
  			if(cookie.getName().equals("jl")){
  			isHave = true;
  			int count = 0;
  			idStr = cookie.getValue();
  			List<Sp> list = new ArrayList<Sp>();
  			String subId = "";
  			boolean isFind = false;
  			for(int i = 0;count!=5 && i<idStr.length();i++){
  				if(idStr.charAt(i)=='*'){
  					if(id==Integer.valueOf(subId)){
  						isFind = true;
  					}
  					Sp sp = spDao.getSp(Integer.valueOf(subId));
  					list.add(sp);
  					count++;
  					subId = "";
  				}else{
  					subId = subId+idStr.charAt(i);
  				}
  			}
  			if(!isFind){
  				Cookie c = new Cookie("jl",id+"*"+idStr);//加到前面
  				cookie.setMaxAge(24*60*60*10);
  				response.addCookie(c);
  			}
  			for(Sp sp : list){
  				out.print("<tr><td><a href='detail.jsp?id="+sp.getId()+"'><img src='image/"+sp.getPicPath()+"' width='200' height='200'></a><br>"+sp.getName()+",¥"+sp.getPrice()+"</td></tr><tr></tr>");
  			}
  			}
  		}
  		if(!isHave){
  			//System.out.print("isHave");
  			Cookie cookie = new Cookie("jl",id+"*");
  			cookie.setMaxAge(24*60*60*10);
  			response.addCookie(cookie);
  		}
  	}
   %>
  </table>
 
  </div>
  <div align="center">
  <%	
    	request.setCharacterEncoding("UTF-8");
    	if(request.getParameter("id")!=null){
    		id = Integer.valueOf(request.getParameter("id"));
    		Sp sp = spDao.getSp(id);
    		out.print("<img src='image/"+sp.getPicPath()+"' alt='未找到该图片' width='500' height='500'><br><font size='7'>"+sp.getName()+",¥"+sp.getPrice()+"<br>产地: "+sp.getPlace()+",库存量: "+sp.getKcl()+"</font>");
    	}
     %> 
  </div>
  </body>
</html>

使用model1的优点:

1.把业务逻辑独立拿出来做为一个类,相比与在JSP页面中显示数据,又要对数据进行处理,大大减少的代码的冗余度

2.比之前全部使用JSP页面更加好维护一些,可拓展性也会好一些 

很显然使用model1模式来开发有很大的弊端:

1.JSP页面中既显示又调用业务逻辑方法,这会造成维护十分的困难,给JSP页面带来很大的负担

2.其实可扩展性也不是很强

总结:

使用model1模式比较适合小的项目,相对于比较大一点的项目更好去使用MVC模式,这个之后再谈.....(持续更新)

猜你喜欢

转载自blog.csdn.net/acDream_/article/details/83448046
今日推荐