* Title of item: * Description: * Price: Goitems add. jsfunction checkForm (){var reg2=new RegExp (/d+d+/);var reg3=new RegExp (//);if ((document.getElementById („title“).value==null)—(document.getElementById („title“).value==»")) {alert («The title of the item must be string!»); returnfalse;}elseif ((document.getElementById… Читать ещё >
ACTION%>" value="<%=Constants.SHOW_ALL_ACTION%>" /><inputtype="submit" id="showall" onclick="" value="Show All Items" ></input></form></td><td width="30%" ><form method="post" action="MainServlet" ><input type="hidden" name="<%=Constants.ACTION%>" value="<%=Constants.SHOW_MY_ACTION%>" /><inputtype="submit" id="showmy" onclick="" value="Show My Items" ></input></form></td><td width="30%" ><form><input type="button" id="sell" onclick="javascript:window.location='additem.jsp';" value=" Add item «></input></form></td></tr></table><table id="Table3″ align="left» width="100%" border="1″ ><tr><td align="left" class="header" colspan="9″ >Items</td></tr><tr><td align="center" class="title" width="10%" >Title</td><td align="center" class="title" width="20%" >Description</td><td align="center" class="title" width="10%" >Price</td></tr><c:if test="${items≠null}" ><c:forEach var="row" items="${items}" ><tr><td>${row.title}</td><td>${row.description}</td><td>${row.price}</td></c:forEach></c:if></table> </body></html>web.xml<?xml version="1.0″ encoding="UTF-8″ ?><web-app id="WebApp_ID" version="2.4″ xmlns=".
http://java.sun.com/xml/ns/j2ee" xmlns: xsi=".
http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation=".
http://java.sun.com/xml/ns/j2ee.
http://java.sun.com/xml/ns/j2ee/web-app2_4.xsd" ><display-name>demo</display-name><welcome-file-list><welcome-file>test.jsp</welcome-file></welcome-file-list><servlet><description></description><display-name>MainServlet</display-name><servlet-name>MainServlet</servlet-name><servlet-class>servlets.MainServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>MainServlet</servlet-name><url-pattern>/MainServlet</url-pattern></servlet-mapping></web-app>context.xml<?xml version="1.0″ encoding="UTF-8″ ?><Context antiJARLocking="true" path="/OnlineMarketplace" ><Resource name="jdbc/onlinemarket" auth="Container" type="javax.sql.DataSource" username="admin" password="password" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/onlinemarket" /></Context>market.sqlDROPtable if EXISTSonlinemarket. users;DROPTABLE IF EXISTSonlinemarket. items;DROPTABLE IF EXISTSonlinemarket. users_items;CREATETABLEonlinemarket.users (user_idSMALLINT UNSIGNED NOTNULL AUTO_INCREMENT, loginvarchar (50) NOTNULL, passwordvarchar (50) NOTNULL, countSMALLINT NOTNULL, PRIMARYKEY (user_id));INSERTINTO onlinemarket. users (user_id, login, password, count) VALUES (null, 'admin', 'pass', 0);INSERTINTO onlinemarket. users (user_id, login, password, count) VALUES (null, 'user1', 'password', 0);CREATETABLEonlinemarket.items (item_idSMALLINT UNSIGNED NOTNULL AUTO_INCREMENT, titlevarchar (50) NOTNULL, descriptionvarchar (50) NOTNULL, priceREALNOTNULL, PRIMARYKEY (item_id));INSERTINTO onlinemarket. items (item_id, title, description, price) VALUES (null, 'Computer', 'Monitor','20 000');INSERTINTO onlinemarket. items (item_id, title, description, price) VALUES (null, 'Case', 'Case Logic 15.4″ Lightweight Computer Backpack','1000');CREATETABLEonlinemarket.users_items (idSMALLINT UNSIGNED NOTNULL AUTO_INCREMENT, user_idSMALLINT UNSIGNED NOTNULL, item_idSMALLINT UNSIGNED NOTNULL, PRIMARYKEY (id));INSERTINTO onlinemarket. users_items (id, user_id, item_id) VALUES (null, 1, 2);INSERTINTO onlinemarket. users_items (id, user_id, item_id) VALUES (null, 2, 1);additem.jsp<%@ page language="java" contentType="text/html; charset=UTF-8″ pageEncoding="UTF-8″ %><%@ taglib uri=".
http://java.sun.com/jsp/jstl/core" prefix="c" %><%@ page import="servlets.Constants" %><!DOCTYPE HTML PUBLIC «.
-//W 3C//DTD HTML 4.01 Transitional//EN" ><html><head><meta http-equiv="Content-Type" content="no-cashe" ><title>Add item</title><script src="add.js" ></script><link rel="stylesheet" type="text/css" href="style.css" ></head><body><form onsubmit="return checkForm ();" method="post" action="MainServlet" ><input type="hidden" name="<%=Constants.ACTION%>" value="<%=Constants.ADD_ACTION%>" /><table id="Table1″ align="center" ><tr><td><b>*</b>Title of item:</td><td><input type="text" id="title" name="title" value="" /></td></tr><tr><td><b>*</b>Description:</td><td><textarea id="description" name="description" cols="20″ rows="5″ ></textarea></td></tr><tr><td><b>*</b>Price:</td><td><input type="text" id="price" name="price" value="" /></td></tr><tr><td align="center" colspan="2″ ><input type="submit" id="button1″ onclick="" value="Publish/Save" /> <input type="reset" id="button2″ onClick="" value="Reset" /></td></tr><tr><td align="center" colspan="2″ ><a href="test.jsp" >Goitems</a></td></tr></table></form></body></html>add.jsfunction checkForm (){var reg2=new RegExp (/d+[.]d+/);var reg3=new RegExp (/[00−23][:][00−59]/);if ((document.getElementById («title»).value==null)—(document.getElementById («title»).value=="")) {alert («The title of the item must be string!»); returnfalse;}elseif ((document.getElementById («description»).value==null)—(document.getElementById («description»).value=="")) {alert («The description of the item must be string!»); returnfalse;}elseif (!reg2.test (document.getElementById («price»).value)) {alert («The price of the item must be double!»); returnfalse;}else {alert («Item was added successfully!»);returntrue; }}style.css@CHARSET «UTF-8″ ;body {font-family: Verdana, Arial, sans-serif;font-size: smaller;padding: 50px;color: #555;}h1 {text-align: left;letter-spacing: 6px;font-size: 1.4em;color: #be7429;font-weight: normal;width: 450px;}table {width: 580px;padding: 10px;background-color: #c5e7e0;}th {text-align: center;border-bottom: 1pxsolid;}td {text-align: center;padding: 10px;}a:link {color: #be7429;font-weight: normal;text-decoration: none;}a:link:hover {color: #be7429;font-weight: normal;text-decoration: underline;}MainServlet.javapackage servlets;import static servlets.Constants.*;import java.io.IOException;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import model. Item;import java.sql.*;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.List;import javax.swing.JOptionPane;/** * Servlet implementation class for Servlet: MainServlet * */public class MainServlet extends HttpServlet {private static final long serialVersionUID = 1L;private static final String TITLE = „title“ ;private static final String USER = „user“ ;private static final String DESCRIPTION = „description“ ;private static final String PRICE = „price“ ;private static final String ITEMS = „items“ ;private static final String NAME = „name“ ;private static final String TIME = „time“ ;private static final String COUNT = „count“ ;/** * Метод для обработки действия регистрации пользователя.* * @param request * @param response * @throws ServletException * @throws IOException */public void doRegister (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String login = request. getParameter („login“);String password = request. getParameter („password“);ResultSet rs = null; String page=REGISTER;try {Class.forName („com.mysql.jdbc.Driver“);Connection con = DriverManager. getConnection („jdbc:mysql://localhost:3306/onlinemarket“, „admin“ ,» password");Statement st = con. createStatement ();//Поиск пользователя в базе данных с введенным логиномString sql = «select * from users where login like '» + login+" '" ;rs = st. executeQuery (sql);if (!rs.first ()){ //Добавление пользователя в базу данныхst. executeUpdate («insert into users (user_id, login, password, count) values (NULL ,'» + login + «','» + password + «', 1)»);sql = «select * from users where login like '» + login+" '" +" and password like '" + password+" '" ;rs = st. executeQuery (sql);int user_id;int count=0; String time;while (rs.next ()) {user_id=rs.getInt («user_id»);request.getSession ().setAttribute (USER, user_id);count=rs.getInt («count»); // Добавление в сессию атрибута счетчикаrequest. getSession ().setAttribute (COUNT, count);// Добавление в сессию атрибута логина пользователяrequest. getSession ().setAttribute (NAME, login); Calendar cal = Calendar. getInstance (); SimpleDateFormat sdf = new SimpleDateFormat («HH:mm:ss»);time= sdf. format (cal.getTime ());// Добавление в сессию атрибута времени входа в систему пользователяrequest. getSession ().setAttribute (TIME, time);page=SHOW_ITEMS; }}else{request.setAttribute («message» ," There is already user with such login! P lease, enter another one login!"); }rs.close ();st.close ();con.close ();}catch (Exception e) {System.out.print (e);e.printStackTrace ();}if (page.equals (SHOW_ITEMS)){doShowAll (request, response);}else{dispatch (request, response, page);}}/** * Метод для работы с действием добавления товара в базу данных* * @param request * @param response * @throws ServletException * @throws IOException */public void doAddItem (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int user_id = (int) request. getSession ().getAttribute (USER);String title = request. getParameter (TITLE);String description = request. getParameter (DESCRIPTION);String price = request. getParameter (PRICE);ResultSet rs = null;try {Class.forName («com.mysql.jdbc.Driver»);Connection con = DriverManager. getConnection («jdbc:mysql://localhost:3306/onlinemarket», «admin» ," password");Statement st = con. createStatement (); //Добавление товара в базу данныхst. executeUpdate («insert into items (item_id, title, description, price) values (NULL ,'» + title+ «','» + description+ «','» +price + «')»); // Получение только что добавленного товараString sql = «select * from items where title like '» + title+" '" +" and description like '" + description+" '" +" and price ='" + price+" '" ;rs = st. executeQuery (sql);int item_id = 0;while (rs.next ()) {item_id=rs.getInt («item_id»);} //Добавление в базу данных связи между введенным товаром и пользователем, добавившем егоst. executeUpdate («insert into users_items (id, user_id, item_id) values (NULL ,'» + user_id+ «','» + item_id + «')»);rs.close ();st.close ();con.close ();}catch (Exception e) {System.out.print (e);e.printStackTrace ();}//dispatch (request, response, SHOW_ITEMS);doShowAll (request, response);}/** * Метод для обработки действия авторизации пользователя* * @param request * @param response * @throws ServletException * @throws IOException */public void doLogin (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String login = request. getParameter («login»);String password = request. getParameter («password»);String page=LOGIN;ResultSet rs = null;try {Class.forName («com.mysql.jdbc.Driver»);Connection con = DriverManager. getConnection («jdbc:mysql://localhost:3306/onlinemarket», «admin» ," password");Statement st = con. createStatement ();// Поиск в базе данных пользователей с аналогичной комбинацией логина и пароля, что и у пользователя, проходящего авторизациюString sql = «select * from users where login like '» + login+" '" +" and password like '" + password+" '" ;rs = st. executeQuery (sql);int user_id; String time;int count=0;while (rs.next ()) {page=SHOW_ITEMS;user_id=rs.getInt («user_id»);request.getSession ().setAttribute (USER, user_id);request.getSession ().setAttribute (NAME, login); Calendar cal = Calendar. getInstance (); SimpleDateFormat sdf = new SimpleDateFormat («HH:mm:ss»);time= sdf. format (cal.getTime ());request.getSession ().setAttribute (TIME, time);count=rs.getInt («count»);count++;st.executeUpdate («update users set count="+count+» where user_id="+user_id);request.getSession ().setAttribute (COUNT, count);}if (page.equals (LOGIN)){request.setAttribute («message» ," Wrong combination of login and password!");}rs.close ();st.close ();con.close ();}catch (Exception e) {System.out.print (e);e.printStackTrace ();}if (page.equals (SHOW_ITEMS)){doShowAll (request, response);}else{dispatch (request, response, page);}}/** * Метод для обработки действия отображения всех товаров* * @param request * @param response * @throws ServletException * @throws IOException */public void doShowAll (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ResultSet rs = null;String page=SHOW_ITEMS;List<Item> items = new ArrayList<Item>();try {Class.forName («com.mysql.jdbc.Driver»);Connection con = DriverManager. getConnection («jdbc:mysql://localhost:3306/onlinemarket», «admin» ," password");Statement st = con. createStatement ();// Получение списка всех товаров из базы данныхString sql = «select * from items» ;rs = st. executeQuery (sql);while (rs.next ()) {Item item = new Item ();item.setItem_id (rs.getInt (1));item.setTitle (rs.getString (2));item.setDescription (rs.getString (3));item.setPrice (rs.getDouble (4));items.add (item);}rs.close ();st.close ();con.close ();}catch (Exception e) {System.out.print (e);e.printStackTrace ();}request.getSession ().setAttribute (ITEMS, items);request.setAttribute (ITEMS, items);dispatch (request, response, page);}/** * Метод для обработки действия отображения списка товаров, добавленных авторизованным пользователем* * @param request * @param response * @throws ServletException * @throws IOException */public void doShowMy (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ResultSet rs = null;String page=SHOW_ITEMS;List<Item> items = new ArrayList<Item>();int user_id=(int) request. getSession ().getAttribute (USER);try {Class.forName («com.mysql.jdbc.Driver»);Connection con = DriverManager. getConnection («jdbc:mysql://localhost:3306/onlinemarket», «admin» ," password");Statement st = con. createStatement (); // Получение списка товаров, добавленных пользователемString sql = «select items. item_id, items. title, items. description, items. price from items, users_items where users_items.user_id="+user_id+» and users_items.item_id=items.item_id" ;rs = st. executeQuery (sql);while (rs.next ()) {Item item = new Item ();item.setItem_id (rs.getInt («item_id»));item.setTitle (rs.getString («title»));item.setDescription (rs.getString («description»));item.setPrice (rs.getDouble («price»));items.add (item);}rs.close ();st.close ();con.close ();}catch (Exception e) {System.out.print (e);e.printStackTrace ();}request.getSession ().setAttribute (ITEMS, items);request.setAttribute (ITEMS, items);dispatch (request, response, page);}/** * Обработка запросов для HTTP <code>GET</code> и <code>POST</code> * методов. * * @.
param request * servlet request * @param response * servlet response * @throws IOException * @throws ServletException */public void doAction (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {if (request.getParameter (ACTION).equals (LOGIN_ACTION)) {doLogin (request, response);}if (request.getParameter (ACTION).equals (REGISTER_ACTION)) {doRegister (request, response);}if (request.getParameter (ACTION).equals (ADD_ACTION)) {doAddItem (request, response);}if (request.getParameter (ACTION).equals (SHOW_ALL_ACTION)) {doShowAll (request, response);}if (request.getParameter (ACTION).equals (SHOW_MY_ACTION)) {doShowMy (request, response);}}/** * Handles the HTTP <code>GET</code> method. * * @ param request * servlet request * @param response * servlet response */public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {doPost (request, response);}/** * Handles the HTTP <code>POST</code> method. * * @.
param request * servlet request * @param response * servlet response */public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {doAction (request, response);}public void dispatch (HttpServletRequest request, HttpServletResponse response, String page) throws javax.servlet.ServletException, java.io.IOException {RequestDispatcher dispatcher = getServletContext ().getRequestDispatcher (page);dispatcher.forward (request, response);}}Constants.javapackage servlets;public class Constants {public static final String ACTION = «action» ;public static final String LOGIN_ACTION = «login» ;public static final String REGISTER_ACTION = «register» ;public static final String SHOW_ITEMS = «/test.jsp» ;public static final String LOGIN = «/index.jsp» ;public static final String REGISTER = «/registration.jsp» ;public static final String ADD_ACTION = «edit» ;public static final String SHOW_ALL_ACTION = «show» ;public static final String SHOW_MY_ACTION = «showmy» ;}Item.javapackage model;publicclass Item implements java.io.Serializable {privatestaticfinallongserialVersionUID = 1L;/** * Identificator of the item. */ privateint item_id;/** * Title of the item. */ private String title;/** * Description of the item.
*/ private String description;/** * Price of the item. */ privatedouble price;/** * Constructor of the class.
* */ public Item () {}/** * Constructor of the class. * */ public Item (int item_id, String title, String description, double price) {this.item_id = item_id;this.title = title;this.description = description;this.price = price;}public String getDescription () {return description;}publicvoid setDescription (String description) {this.description = description;}publicdouble getPrice () {return price;}publicint getItem_id () {return item_id;}publicvoid setItem_id (int item_id) {this.item_id = item_id;}public String getTitle () {return title;}publicvoid setTitle (String title) {this.title = title;}publicvoid setPrice (double price) {this.price = price;}}User.javapackage model;/** * Class for describing the model of user. */ publicclass User implements java.io.Serializable {privatestaticfinallongserialVersionUID = 1L;/** * User identificator. */.
privateint user_id;/** * User login. */ private String login;/** * User password. */ private String password;/** * Constructor of the class.
*/ public User (){}public User (int user_id, String login, String password) {this.user_id=user_id;this.login = login;this.password = password;}public String getLogin () {return login;}publicvoid setLogin (String login) {this.login = login;}public String getPassword () {return password;}publicvoid setPassword (String password) {this.password = password;}publicint getUser_id () {return user_id;}publicvoid setUser_id (int user_id) {this.user_id = user_id;}}ПРИЛОЖЕНИЕ 2. СКРИНЫ РАБОТАЮЩЕЙ ПРОГРАММЫ.
ИЛИ
↓