淺談model1模式及使用model1模式來實現瀏覽商品
阿新 • • 發佈:2018-10-31
需要實現功能:
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模式,這個之後再談.....(持續更新)