Javaee에서 Model1 모델은 JSSP 페이지를 중심으로합니다. JSSP는 브라우저의 요청을 논리적으로 처리 할뿐만 아니라 (Javabean 사용) 데이터베이스에 액세스 할 때 관련 페이지를 표시해야합니다.
Model1 모델에는 서블릿이 없습니다.
Model1의 결과 다이어그램은 다음과 같습니다.
Model1은 유지 관리 가능성과 확장 성이 좋지 않으며 소규모 프로젝트에만 적합합니다.
먼저 결과를 실행하십시오
goods.jsp
<%@page import = "entity.items"%> <%@page import = "dao.itemsdao"%> <%@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 전환 // en"> <html> <head> <head> <base href = "<%= basepath%>"> <title> 나의 jsp 'index.jsp'시작 페이지 </titp-equiv = "pragma"= no-cache ""no-cache ""pragma " http-equiv = "Cache-control"content = "no-cache"> <meta http-equiv = "chewors"content = "0"> <meta http-equiv = "keyword ="keyword1, keyword2, keyword2, keyword3 "> <meta http-equiv ="descript "> <" "rel rel rele"> type = "text/css"href = "styles.css"> -> <style type = "text/css"> div {float : 왼쪽; 여백 : 10px; } div dd {마진 : 0px; 글꼴 크기 : 10pt; } div dd.dd_name {색상 : 파란색; } div dd.dd_city {색상 : #000; . ArrayList <Items> list = new ArrayList <initment> (); // DAO에서 모든 제품을 가져 와서 목록에 저장하는 수집 목록 = dao.getallitems (); if (list! = null && list.size ()> 0) {수집 및 디스플레이를 통해 (int i = 0; i <list.size (); i ++) {항목 item = list.get (i); %> <div> <dl> <dt> <a href = "details.jsp? id = <%= item.getId ()%>"> <img src = "images/<%= item.getPicture ()%>"/> </a> </dt> <dd> <%= item.getname ()%> <dd> <%= <) <%= item.getPrice ()%> </dd> </dl> </div> <%}}%> </td> </tr> </table> </table> </center> </body> </html> 코드의 제품을 나타내는 이미지
<span style = "화이트 공간 : pre"> </span> <a href = "details.jsp? id = <%= item.getid ()%>"> <img src = "images/<%= item.getPicture ()%>"/> </a>
제품 이미지를 클릭하여 현재 제품의 ID를 세부 사항 페이지로 전달하십시오.
세부 사항 .JSP는 제품의 ID를 통해 세부 제품을 표시하며 쿠키로 탐색 기록이 유지됩니다.
<%@page import = "org.apache.taglibs.standard.tag.common.xml.foreachtag"%> <%@page import = "entity.items.items"%> <%@page import = "dao.itemsdao"%> <%@page language = "java"import = "java.util. request.getContextPath (); String BasePath = request.getScheme () + ": //" + request.getServerName () + ":" + request.getServerport () + path + "/"; %> <! doctype html public "-// w3c // dtd html 4.01 전환 // en"> <html> <head> <head> <base href = "<%= basepath%>"> <title> 나의 jsp 'index.jsp'시작 페이지 </titp-equiv = "pragma"= no-cache ""no-cache ""pragma " http-equiv = "Cache-control"content = "no-cache"> <meta http-equiv = "cheword ="0 "> <meta http-equiv ="keywords "content ="keyword1, keyword2, keyword3 "> <meta http-equiv ="description = "syle page"> <style/css "> #HistoryView {Border : 1; 배경 : #Eaeeee; } #historyView td {font-size : 10px; } </style> </head> <body> <center> <h1> 제품 세부 사항 </h1> <hr> <테이블 CellPadding = "0"CellPacing = "0"> <td> <Td> <center> <table> <% itemsDao dao = new yeptsDao (); // 요청 항목에서 전송 된 제품 ID에 따라 해당 제품 객체를 가져옵니다. 항목 = dao.getItemByid (integer.parseint (요청 .getParameter ( "id"))); if (item! = null) {%> <tr> <td rowspan = "5"> <img src = "images/<%= item.getPicture ()%>"> </td> </tr> <td> <b> <%= item.getname ()%> </b> </td> <tr> <td id = "Cityname"> <%= item.getCity ()%> </td> </tr> <tr> <td id = "priceName"> price : <%= item.getPrice ()%> </td> </tr> <tr> <td id = "pricename"> priceName "> <%= item.getPrice ()%</td> </tr> <%} // request.getCookies (); 문자열 historystr = ""; for (쿠키 C : 쿠키) {if (c.getName (). equals ( "history")) {historystr = c.getValue (); }} historystr + = item.getId () + ","; 쿠키 C = 새로운 쿠키 ( "역사", historystr); // 쿠키 재설정 응답 .addcookie (c); %> </table> </center> </td> <td valign = "Top"id = "historyview"> <cristorview "> <cristorView"> <central> <tr> <td> <b> 탐색 된 제품 </b> </td> </tr> <% // 쿠키를 기반으로 DAO에서 마지막 세 번의 검색 기록을 가져와 목록 <ehristoratemlist = histormlistem <% //리스트 컬렉션에 저장합니다. dao.gethistoryview (historystr); if (historyitems! = null && historyitems.size ()> 0) {// 세트를 (items historyitem : historyitems)에 전송합니다. </tr> <tr> <td> <b> <%= historyitem.getName ()%> </b> </td> </tr> <tt> <td> ours : <%= historitem.getCity ()%> </td> </tr> <%}}}%> </table> </tr> </trail> </htm> </htm> DAO 계층은 데이터베이스에서 제품의 쿼리 작동을 담당합니다.
패키지 dao; java.sql.connection 가져 오기; Java.sql.preparedStatement import; java.sql.resultset import; java.sql.sqlexception 가져 오기; java.util.arraylist 가져 오기; util.dbhelper import; 가져 오기 엔티티 .ITEMS; // 제품 공개 클래스의 비즈니스 로직 클래스 Dao {// 모든 제품 정보 가져 오기 공개 ArrayList <Items> getAllItems () {// 제품 수집 ArrayList> list = new ArrayList <Items> (); 연결 Conn = null; 준비된 상태 ps = null; resultSet rs = null; try {conn = dbhelper.getConnection (); 문자열 sql = "항목에서 선택 * 선택"; // sql 문 ps = conn.preparestatement (sql); rs = ps.ExecuteQuery (); // 쿼리 결과를 컬렉션에 차례로 추가하는 동안 (rs.next ()) {항목 항목 = 새 항목 (); item.setid (rs.getint ( "id")); item.setName (rs.getString ( "name")); item.setCity (rs.getString ( "City")); item.setPrice (rs.getDouble ( "price")); item.setPicture (rs.getString ( "그림")); item.setNumber (rs.getInt ( "number")); list.add (항목); }} catch (sqlexception e) {e.printstacktrace (); } 마침내 {// 리소스를 닫습니다 if (rs! = null) {try {rs.close (); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} if (ps! = null) {try {ps.close (); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }}} 리턴 목록; } // 제품 번호를 기반으로 제품 정보 가져 오기 공개 항목 getItemById (int id) {항목 항목 = 새 항목 (); 연결 con = null; 준비된 상태 ps = null; resultSet rs = null; 문자열 sql = "id =?"에서 항목에서 선택 *; "; try {con = dbhelper.getConnection (); ps = con.preparestatement (SQL); ps.setint (1, id); rs = ps.ExecuteQuery (); // id가 발견되면 If (rs.next ()) {item.setId (rs.getInt ( "id")); item.setName (rs.getString ( "name")); item.setCity (rs.getString ( "City")); item.setPrice (rs.getDouble ( "price")); item.setPicture (rs.getString ( "그림")); item.setPicture (rs.getString ( "그림")); item.setNumber (rs.getInt ( "number")); }} catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); } 마침내 {// 리소스를 닫습니다 if (rs! = null) {try {rs.close (); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} if (ps! = null) {try {ps.close (); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }}} 반환 항목; } // 쿠키를 기반으로 한 마지막 세 항목을 찾아냅니다. public arraylist <items> gethistoryView (String Cookie) {arraylist <items> list = new ArrayList <Items> (); 문자열 ids [] = cookie.split ( ","); int counts = 3; // 마지막 3 개의 레코드가 if (ids! = null && ids.length> 0) {for (int i = ids.length -1; i> = 0 && i> ids.length -counts -1; i-) {항목 항목 = getItembyid (integer.parseint (ids [i]); / * * 먼저 컬렉션에 현재 항목이 존재하는지 확인하십시오. Counts+1이 존재하는 경우 한 번 더 읽으십시오 (목록 컬렉션에 3 개의 개체가 보장 됨)이 항목을 추가하지 마십시오*/ if (list.contains (item)) {counts ++; 계속하다; } list.add (항목); }} 리턴 목록; }} 엔티티 카테고리의 항목
패키지 엔티티; 공개 수업 항목 {private int id; 개인 문자열 이름; 개인 문자열 도시; 개인 이중 가격; 개인 INT 번호; 개인 문자열 사진; public int getid () {return id; } public void setid (int id) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public String getCity () {return City; } public void setcity (String City) {this.city = City; } public double getPrice () {반환 가격; } public void setPrice (이중 가격) {this.price = 가격; } public int getNumber () {반환 번호; } public void setNumber (int number) {this.number = 숫자; } public String getPicture () {return infice; } public void setPicture (문자열 그림) {this.picture = picture; } @override public int hashcode () {// todo 자동 생성 메소드 스텁이 this.getId ()+this.getName (). hashcode (); } @override public boolean equals (Object obj) {if (this == obj) {return true; } else {if (obj instance items) {항목 항목 = (항목) obj; if (this. }}} 거짓을 반환합니다. }} 여기서 우리는 Hascode를 다시 작성하고 비교 방법을 수정하는 방법과 같습니다 (모든 항목은 새로운 객체입니다. 두 제품의 내용이 동일하더라도 동일하지 않아서 비교 방법을 수정해야합니다).
브라우징 기록의 경우 현재 제품 브라우징 기록을 새로 고칠 수 없으며 모든 제품은 제품입니다. 브라우징 역사에는 단 하나의 제품 만 있는지 확인하면됩니다. 그래서 DAO 레이어의 gethistoryView 메소드에는이 코드가 있습니다.
<span style = "화이트 공간 : pre"> </span> if (list.contains (item)) {counts ++; 계속하다; } 그런 다음 공구 클래스 가 있습니다
dbhelpher 싱글 톤 패턴은 연결 객체를 얻습니다
패키지 유틸리티; java.sql.connection 가져 오기; Java.SQL.DriverManager 가져 오기; java.sql.sqlexception 가져 오기; public class dbhelper {private static final string driver = "com.mysql.jdbc.driver"; 개인 정적 최종 문자열 URL = "jdbc : mysql : // localhost : 3306/shopping? useunicode = true & charcterencoding = utf-8"; 개인 정적 최종 문자열 username = "루트"; 비공개 정적 최종 문자열 암호 = "123"; 개인 정적 연결 Con = NULL; // 정적 블록 코드는 드라이버 static {try {class.forname (driver); } catch (classNotFoundException e) {// TODO 자동 생성 캐치 블록 E.PrintStackTrace (); }} public static connection getConnection () {if (con == null) {try {con = drivermanager.getConnection (url, username, password); } catch (sqlexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} return con; }}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.