В Javaee модель модели1 сосредоточена на странице JSSP. JSSP должен не только логически обработать запрос браузера (с использованием Javabean), но и отображать соответствующие страницы при доступе к базе данных.
В модели модели1 нет сервлета.
Диаграмма результатов модели1 заключается в следующем:
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 transitional // en"> <html> <head> <base href = "<%= basepath%>"> <Title> my jsp 'index.jsp' начальная страница </tite> <meta http-equiv = "pragma" no-contex "no-contex" no-contex "no-contex" no-c http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "expires" content = "0"> <meta http-equiv = "Content" Content = ", ключевое слово1, ключевое слово3"> <meta http-equiv = "description". type = "text/css" href = "styles.css"> -> <style type = "text/css"> div {float: left; Маржа: 10px; } div dd {margin: 0px; размер шрифта: 10pt; } div dd.dd_name {color: blue; } div dd.dd_city {color: #000; } </style> </head> <body> <center> <h1> Дисплей продукта </h1> <hr> <Таблица cellPadding = "0" сотока = "0"> <Tr> <td> <% itemsDao dao = new itemsDao (); ArrayList <Items> list = new ArrayList <Items> (); // Получить все продукты от 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> <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>
Нажав на изображение продукта, передайте идентификатор текущего продукта на страницу сведений
Подробности. JSP отображает подробные продукты через идентификатор продукта, а история просмотра поддерживается файлами cookie
<%@page import = "org.apache.taglibs.standard.tag.common.xml.foreachtag"%> <%@page import = "entity.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 transitional // en"> <html> <head> <base href = "<%= basepath%>"> <Title> my jsp 'index.jsp' начальная страница </tite> <meta http-equiv = "pragma" no-contex "no-contex" no-contex "no-contex" no-c http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "expires" content = "0"> <meta http-equiv = "Content" content = ", ключевое слово1, ключевое слово3"> <meta http-equiv = "description". {граница: 1; Фон: #eaeaee; } #historyView td {font-size: 10px; } </style> </head> <body> <enter> <h1> Детали продукта </h1> <hr> <Таблица cellPadding = "0" сотока = "0"> <tr> <td> <Center> <table> <% itemsdao dao = new itemsdao (); // Получить соответствующий объект продукта в DAO в соответствии с идентификатором продукта, отправленным из элемента запроса = dao.getitembyid (integer.parseint (request .getParameter ("id"))); if (item! = null) {%> <tr> <td rowspan = "5"> <img src = "Images/<%= item.getpicture ()%>"> </td> </tr> <tr> <td> <b> <%= item.getName ()%> </b> </td> </tr> <tr> <td> <%= item.getCity ()%> </td> </tr> <tr> <td id = "pricename"> цена: <%= item.getprice ()%> ¥ </td> </tr> <tr> <td id = "priceName"> цена: <%= item.getPrice ()%> ¥ </td> </tr> <%/adpries ()%¥ </td> request.getCookies (); String yoroystr = ""; for (cookie c: cookie) {if (c.getname (). equals ("vistory")) {storialstr = c.getValue (); }} vitiorStr + = item.getId () + ","; Cookie c = новое печенье («История», История); // сбросить ответ cookie response.addcookie (c); %> </table> </center> </td> <td valign = "top" id = "vistoryView"> <Center> <table> <tr> <td> <b> Продукты, которые вы просмотрели </b> </td> </tr> <% // Извлеките последние три просмотренных рекорда из DAO на основе Cookies и сохранить их в списка dao.gethistoryview (inistorystr); if (vistoryItems! = null && vistoryItems.size ()> 0) {// Перенос набор для (itiestemitem: vistoryItems) {%> <Tr> <td> <a href = "defints.jsp? id = <%= vistoryItem.getId ()%>"> <img src = "Images/<%= vistory.getem.getD ()%>"> </img src = "ImageS/<%= istory.getem.getD ()%>" </tr> <tr> <td><b><%=historyItem.getName()%></b> </td> </tr> <tr> <td>Origin: <%=historyItem.getCity()%></td> </tr> <% } } %> </table> </tr> </tr> </table> </center> </body> </html> Уровень DAO отвечает за работу запроса продуктов в базе данных
Пакет Dao; Импорт java.sql.connection; Импорт java.sql.preparedStatement; импортировать java.sql.resultset; Импорт java.sql.sqlexception; импортировать java.util.arraylist; Импорт util.dbhelper; Импорт Entity.Items; // бизнес -логический класс продукта открытый класс isementsdao {// Получить все информацию о продукте public arraylist <пункты> getallitems () {// collection arraylist <epest> list = new Arraylist <Items> (); Соединение conn = null; Подготовленное предприятие PS = NULL; Результат RS = NULL; try {conn = dbhelper.getConnection (); String sql = "select * from ements"; // sql оператор ps = conn.preparestatement (sql); rs = ps.executequery (); // Добавить результаты запроса в коллекцию по очереди, в то время как (rs.next ()) {item Item = new Etems (); item.setid (rs.getint ("id")); item.setName (rs.getString ("name")); item.setCity (Rs.GetString ("City")); item.setprice (rs.getDouble ("цена")); item.setpicture (rs.getstring ("picture")); item.setnumber (rs.getint ("номер")); list.add (item); }} 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 (); }}} return List; } // Получить информацию о продукте на основе номера продукта Public Items getItembyId (INT ID) {элемент item = new Elemes (); Соединение con = null; Подготовленное предприятие PS = NULL; Результат RS = NULL; String sql = "select * из элементов, где id =?"; try {con = dbhelper.getConnection (); ps = con.preprestatement (sql); ps.setint (1, id); rs = ps.executequery (); // Если идентификатор найден, инициализируйте его для объекта элемента if (rs.next ()) {item.setid (rs.getint ("id")); item.setName (rs.getString ("name")); item.setCity (Rs.GetString ("City")); item.setprice (rs.getDouble ("цена")); item.setpicture (rs.getstring ("picture")); item.setpicture (rs.getstring ("picture")); item.setnumber (rs.getint ("номер")); }} 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 (); }}} return item; } // Получите последние три предмета, просмотренные на основе файлов cookie public arraylist <Items> gethistoryview (String cookie) {arraylist <epets> list = new Arraylist <Items> (); String Ids [] = cookie.split (","); int counts = 3; // Последние три записи просмотрели if (ids! = null && ids.length> 0) {for (int i = ids.length - 1; i> = 0 && i> ids.length - counts - 1; i--) {item = getitembyid (integer.parseint (ids [i])); / * * Сначала определите, существует ли текущий элемент в коллекции. Если подсчет+1 существует, прочитайте его еще раз (гарантированно иметь 3 объекта в коллекции списков) не добавляйте этот элемент*/ if (list.contains (item)) {counts ++; продолжать; } list.add (item); }} return List; }} Предметы категории сущности
Пакет сущность; Общедоступные элементы {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 (string name) {this.name = name; } public String getCity () {return City; } public void setCity (String City) {this.city = City; } public Double GetPrice () {return Price; } public void setPrice (двойная цена) {this.price = цена; } public int getNumber () {return №; } 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 Автопогенерированный метод заглушка вернуть this.getid ()+this.getName (). Hashcode (); } @Override public boolean equals (Object obj) {if (this == obj) {return true; } else {if (obj exanceof items) {item item = (items) obj; if (this.getId () == item.getId () && this.getName (). equals (item.getName ())) {return true; }}} вернуть false; }} Здесь мы переписали методы Hascode и Equals для изменения метода сравнения (все элементы являются новым объектом. Даже если содержимое двух продуктов одинаково, они не будут равны. Поэтому нам необходимо изменить метод сравнения)
Поскольку для истории просмотра мы не можем обновить текущую историю просмотра продуктов, и все продукты являются продуктами. Нам просто нужно убедиться, что в истории просмотра есть только один продукт. Таким образом, метод GethistoryView в слое DAO имеет этот код
<span style = "Белое пространство: pre"> </span> if (list.contains (item)) {counts ++; продолжать; } Тогда есть класс инструментов
Dbhelpher Singleton Pattern получает объект соединения
Утилит пакета; Импорт java.sql.connection; Импорт java.sql.drivermanager; Импорт java.sql.sqlexception; открытый класс dbhelper {private Static Final String Driver = "com.mysql.jdbc.driver"; Частная статическая конечная строка url = "jdbc: mysql: // localhost: 3306/shopping? useUnicode = true & charcterencoding = utf-8"; частная статическая конечная строка username = "root"; Private Static Final String Password = "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, имя пользователя, пароль); } catch (sqlexception e) {// todo автоматически сгенерированный блок e.printstacktrace (); }} return con; }}Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.