Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Workshop08 PRJ321 Tran PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Subject: PRJ321

Workshop 08: Struts 2 Shoping List


--------------------------------------------------------------------------------------------------------
RULES: Ws 08 should be submited on the LMS system
Contact me @ https://www.facebook.com/quynhtran.ly.94
--------------------------------------------------------------------------------------------------------

Students kindly practice these questions in class and at home based on the
Lecturer’s guidance. Thank you :-D
USE [master]

GO

/****** Object: Database [ShopDB] Script Date: 3/11/2020 8:10:50 AM ******/

CREATE DATABASE [ShopDB]

CONTAINMENT = NONE

ON PRIMARY

( NAME = N'ShopDB', FILENAME = N'C:\Program Files\Microsoft SQL


Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\ShopDB.mdf' , SIZE = 4096KB , MAXSIZE =
UNLIMITED, FILEGROWTH = 1024KB )

LOG ON

( NAME = N'ShopDB_log', FILENAME = N'C:\Program Files\Microsoft SQL


Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\ShopDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB
, FILEGROWTH = 10%)

GO

ALTER DATABASE [ShopDB] SET COMPATIBILITY_LEVEL = 120

GO

IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))

begin

EXEC [ShopDB].[dbo].[sp_fulltext_database] @action = 'enable'

end

GO

ALTER DATABASE [ShopDB] SET ANSI_NULL_DEFAULT OFF

GO

ALTER DATABASE [ShopDB] SET ANSI_NULLS OFF

GO

ALTER DATABASE [ShopDB] SET ANSI_PADDING OFF

GO

ALTER DATABASE [ShopDB] SET ANSI_WARNINGS OFF

GO

ALTER DATABASE [ShopDB] SET ARITHABORT OFF

GO

ALTER DATABASE [ShopDB] SET AUTO_CLOSE OFF


GO

ALTER DATABASE [ShopDB] SET AUTO_SHRINK OFF

GO

ALTER DATABASE [ShopDB] SET AUTO_UPDATE_STATISTICS ON

GO

ALTER DATABASE [ShopDB] SET CURSOR_CLOSE_ON_COMMIT OFF

GO

ALTER DATABASE [ShopDB] SET CURSOR_DEFAULT GLOBAL

GO

ALTER DATABASE [ShopDB] SET CONCAT_NULL_YIELDS_NULL OFF

GO

ALTER DATABASE [ShopDB] SET NUMERIC_ROUNDABORT OFF

GO

ALTER DATABASE [ShopDB] SET QUOTED_IDENTIFIER OFF

GO

ALTER DATABASE [ShopDB] SET RECURSIVE_TRIGGERS OFF

GO

ALTER DATABASE [ShopDB] SET DISABLE_BROKER

GO

ALTER DATABASE [ShopDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF

GO

ALTER DATABASE [ShopDB] SET DATE_CORRELATION_OPTIMIZATION OFF

GO

ALTER DATABASE [ShopDB] SET TRUSTWORTHY OFF

GO

ALTER DATABASE [ShopDB] SET ALLOW_SNAPSHOT_ISOLATION OFF

GO

ALTER DATABASE [ShopDB] SET PARAMETERIZATION SIMPLE

GO

ALTER DATABASE [ShopDB] SET READ_COMMITTED_SNAPSHOT OFF

GO
ALTER DATABASE [ShopDB] SET HONOR_BROKER_PRIORITY OFF

GO

ALTER DATABASE [ShopDB] SET RECOVERY FULL

GO

ALTER DATABASE [ShopDB] SET MULTI_USER

GO

ALTER DATABASE [ShopDB] SET PAGE_VERIFY CHECKSUM

GO

ALTER DATABASE [ShopDB] SET DB_CHAINING OFF

GO

ALTER DATABASE [ShopDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )

GO

ALTER DATABASE [ShopDB] SET TARGET_RECOVERY_TIME = 0 SECONDS

GO

ALTER DATABASE [ShopDB] SET DELAYED_DURABILITY = DISABLED

GO

EXEC sys.sp_db_vardecimal_storage_format N'ShopDB', N'ON'

GO

USE [ShopDB]

GO

/****** Object: Table [dbo].[product] Script Date: 3/11/2020 8:10:50 AM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[product](

[id] [int] IDENTITY(1,1) NOT NULL,

[name] [nvarchar](50) NOT NULL,

[price] [float] NULL,

[description] [ntext] NULL,

PRIMARY KEY CLUSTERED


(

[id] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,


ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET IDENTITY_INSERT [dbo].[product] ON

INSERT [dbo].[product] ([id], [name], [price], [description]) VALUES (1, N'IPad', 700, N'Ipad Model')

INSERT [dbo].[product] ([id], [name], [price], [description]) VALUES (2, N'IPod', 100, N'Ipod Model')

INSERT [dbo].[product] ([id], [name], [price], [description]) VALUES (3, N'IPhone 6s', 800, N'Iphone 6s
Model')

INSERT [dbo].[product] ([id], [name], [price], [description]) VALUES (4, N'IPhone 5', 500, N'Iphone 5
Model')

INSERT [dbo].[product] ([id], [name], [price], [description]) VALUES (5, N'IPhone 12', 1200, N'Iphone
12 Model')

SET IDENTITY_INSERT [dbo].[product] OFF

SET ANSI_PADDING ON

GO

/****** Object: Index [UQ__product__72E12F1B375D1119] Script Date: 3/11/2020 8:10:50 AM


******/

ALTER TABLE [dbo].[product] ADD UNIQUE NONCLUSTERED

[name] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,


IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON
[PRIMARY]

GO

ALTER TABLE [dbo].[product] WITH CHECK ADD CHECK (([price]>=(0) AND [price]<=(10000)))

GO

USE [master]
GO

ALTER DATABASE [ShopDB] SET READ_WRITE

GO

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\context\Dat
abaseInfor.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package context;
7
8 /**
9 *
10 * @author Ly Quynh Tran
11 */
12 public interface DatabaseInfor {
13 public static String driverName =
"com.microsoft.sqlserver.jdbc.SQLServerDriver";
14 public static String url =
"jdbc:sqlserver://127.0.0.1:1433;databaseName=ShopDB;";
15 public static String user = "sa";
16 public static String pass = "abc123";
17 }
18

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\context\Con
nectDB.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package context;
7
8 import static context.DatabaseInfor.driverName;
9 import static context.DatabaseInfor.pass;
10 import static context.DatabaseInfor.url;
11 import static context.DatabaseInfor.user;
12 import java.sql.Connection;
13 import java.sql.DriverManager;
14
15 /**
16 *
17 * @author Ly Quynh Tran
18 */
19 public class ConnectDB implements DatabaseInfor{
20 private static ConnectDB instance;
21
22 public ConnectDB() {
23 }
24
25 public Connection OpenConnection() throws Exception {
26
27 Class.forName(driverName);
28 Connection con = DriverManager.getConnection(url, user, pass);
29 return con;
30 }
31 //Get instance of dbms only one time
32 public static ConnectDB getInstance(){
33 if(instance==null) instance = new ConnectDB();
34 return instance;
35 }
36 }
37

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\model\Cart.j
ava
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 import java.util.HashMap;
9 import java.util.Map;
10 import java.util.Set;
11
12 /**
13 *
14 * @author Ly Quynh Tran
15 */
16 public class Cart {
17 private final Map<Product, Integer> cart = new HashMap<Product,
Integer>();
18
19 public Cart() {
20 }
21
22 public void addProduct(Product p) {
23 Integer amount = cart.get(p);
24 cart.put(p, amount==null?1:(amount + 1));
25 }
26
27 public Map<Product, Integer> getProducts() {
28 return cart;
29 }
30
31 public float getTotalPrice() {
32 float total = 0;
33
34 Set<Product> keys = cart.keySet();
35 for (Product product : keys) {
36 total += product.getPrice() * cart.get(product);
37 }
38
39 return total;
40 }
41 }
42

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\model\Prod
uct.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package model;
7
8 /**
9 *
10 * @author Ly Quynh Tran
11 */
12 public class Product {
13
14 private int id;
15 private String name;
16 private float price;
17 private String description;
18
19 public Product(int id, String name, float price, String description) {
20 this.id = id;
21 this.name = name;
22 this.price = price;
23 this.description = description;
24 }
25
26 @Override
27 public String toString() {
28 return "Product{" + "id=" + id + ", name=" + name + ", price=" + price +
", description=" + description + '}';
29 }
30
31 public int getId() {
32 return id;
33 }
34
35 public void setId(int id) {
36 this.id = id;
37 }
38
39 public String getName() {
40 return name;
41 }
42
43 public void setName(String name) {
44 this.name = name;
45 }
46
47 public float getPrice() {
48 return price;
49 }
50
51 public void setPrice(float price) {
52 this.price = price;
53 }
54
55 public String getDescription() {
56 return description;
57 }
58
59 public void setDescription(String description) {
60 this.description = description;
61 }
62
63 @Override
64 public boolean equals(Object obj) {
65 if (obj == null || !(obj instanceof Product)) {
66 return false;
67 }
68 Product other = (Product) obj;
69
70 return this.id == other.id;
71 }
72
73 @Override
74 public int hashCode() {
75 int hash = 5;
76 hash = 11 * hash + this.id;
77 return hash;
78 }
79 }
80

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\dao\Product
DAO.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package dao;
7
8 import context.ConnectDB;
9 import java.sql.Connection;
10 import java.sql.PreparedStatement;
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13 import java.util.LinkedList;
14 import java.util.List;
15 import java.util.logging.Level;
16 import java.util.logging.Logger;
17 import model.Product;
18
19 /**
20 *
21 * @author Ly Quynh Tran
22 */
23 public class ProductDAO {
24
25 private static PreparedStatement searchByNameStatement;
26 private static PreparedStatement searchByIdStatement;
27
28 private PreparedStatement getSearchByNameStatement() throws
ClassNotFoundException, SQLException {
29 if (searchByNameStatement == null) {
30 //2. Connect
31 Connection connection;
32 try {
33 connection = ConnectDB.getInstance().OpenConnection();
34 searchByNameStatement = connection.prepareStatement("select
id,[name],[price],[description] from product where [name] like ?");
35 } catch (Exception ex) {
36
Logger.getLogger(ProductDAO.class.getName()).log(Level.SEVERE, null, ex);
37 }
38
39 //3. Create Statement
40 }
41 return searchByNameStatement;
42 }
43
44 private PreparedStatement getSearchByIdStatement() throws
ClassNotFoundException, SQLException {
45 if (searchByIdStatement == null) {
46 //2. Connect
47 Connection connection;
48 try {
49 connection = ConnectDB.getInstance().OpenConnection();
50 searchByIdStatement = connection.prepareStatement("select
[name],[price],[description] from product where [id] = ?");
51 } catch (Exception ex) {
52
Logger.getLogger(ProductDAO.class.getName()).log(Level.SEVERE, null, ex);
53 }
54
55 //3. Create Statement
56 }
57 return searchByIdStatement;
58 }
59
60 public List<Product> getProductsByName(String keyword) {
61
62 try {
63 PreparedStatement statement = getSearchByNameStatement();
64 //4. Process
65 statement.setString(1, "%" + keyword + "%");
66 ResultSet rs = statement.executeQuery();
67 List<Product> products = new LinkedList<Product>();
68 while (rs.next()) {
69 int id = rs.getInt("id");
70 String name = rs.getString("name");
71 float price = rs.getFloat("price");
72 String description = rs.getString("description");
73 products.add(new Product(id, name, price, description));
74 }
75 return products;
76 } catch (Exception ex) {
77
78 return new LinkedList<Product>();
79 }
80 }
81
82 public Product getProductById(int id) {
83
84 try {
85 PreparedStatement statement = getSearchByIdStatement();
86 //4. Process
87 statement.setInt(1, id);
88 ResultSet rs = statement.executeQuery();
89 while (rs.next()) {
90 String name = rs.getString("name");
91 float price = rs.getFloat("price");
92 String description = rs.getString("description");
93 return new Product(id, name, price, description);
94 }
95 } catch (Exception ex) {
96
97 }
98 return new Product(0, "", 0, "");
99 }
100 }
101

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\web\index.jsp
1 <%--
2 Document : index
3 Created on : 02/11/2020, 10:37:19 PM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@page contentType="text/html" pageEncoding="UTF-8"%>
8 <!DOCTYPE html>
9 <html>
10 <head>
11 <meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
12 <title>JSP Page</title>
13 </head>
14 <body>
15 <form action="productlist">
16 Search by name:<input name="keyword"/><input type="submit"/>
17 </form>
18 </body>
19 </html>
20

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\web\result.jsp
1 <%--
2 Document : result
3 Created on : 02/11/2020, 10:38:52 PM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@page contentType="text/html" pageEncoding="UTF-8"%>
8 <%@taglib prefix="s" uri="/struts-tags" %>
9 <!DOCTYPE html>
10 <html>
11 <head>
12 <meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
13 <title>Product List of search <s:property value="keyword"/></title>
14 </head>
15 <body>
16 <h1>Product List of search <s:property value="keyword"/></h1>
17 <table>
18 <s:iterator value="products" var="product">
19 <tr>
20 <td><s:property value="name"/></td>
21 <td><s:property value="price"/></td>
22 <td><s:property value="description"/></td>
23 <td><a href="addToCart?newProductId=<s:property
value="id"/>">Add to cart</a></td>
24 </tr>
25 </s:iterator>
26 <a href="index.jsp">Back</a>
27 </table>
28 </body>
29 </html>
30
31

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\web\viewCart.jsp
1 <%--
2 Document : viewCart
3 Created on : 02/11/2020, 10:39:44 PM
4 Author : Ly Quynh Tran
5 --%>
6
7 <%@page contentType="text/html" pageEncoding="UTF-8"%>
8 <%@taglib prefix="s" uri="/struts-tags" %>
9 <!DOCTYPE html>
10 <html>
11 <head>
12 <meta http-equiv="Content-Type" content="text/html; charset=UTF-
8">
13 <title>Cart Details</title>
14 </head>
15 <body>
16 <h1>Cart Details</h1>
17 <table border = "1">
18 <tr>
19 <th>Product</th>
20 <th>Amount</th>
21 </tr>
22 <s:iterator value="products" var="product">
23 <tr>
24 <td><s:property value="key.name"/></td>
25 <td><s:property value="value"/></td>
26 </tr>
27 </s:iterator>
28 </table>
29 <label>Total:</label><s:property value="total"/><br/>
30 <a href="index.jsp">Continue buying</a>
31 </body>
32 </html>
33
34

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\struts.xml
1 <!DOCTYPE struts PUBLIC
2 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
3 "http://struts.apache.org/dtds/struts-2.0.dtd">
4
5 <struts>
6 <!-- Configuration for the default package. -->
7 <package name="default" extends="struts-default">
8 <global-results>
9 <result name="error">index.jsp</result>
10 </global-results>
11 <action name="productlist" class="action.ProductList">
12 <result name="success" >result.jsp</result>
13 </action>
14 <action name="addToCart" class="action.AddProductToCart">
15 <result name="success" type="redirect">viewCart</result>
16 </action>
17 <action name="viewCart" class="action.ViewCart">
18 <result name="success">viewCart.jsp</result>
19 </action>
20 </package>
21 </struts>
22

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\action\AddP
roductToCart.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package action;
7
8 import com.opensymphony.xwork2.ActionContext;
9 import com.opensymphony.xwork2.ActionSupport;
10 import dao.ProductDAO;
11 import model.Cart;
12 import model.Product;
13
14 /**
15 *
16 * @author Ly Quynh Tran
17 */
18 public class AddProductToCart extends ActionSupport {
19
20 private int newProductId;
21
22 public void setNewProductId(int newProductId) {
23 this.newProductId = newProductId;
24 }
25
26 @Override
27 public String execute() throws Exception {
28 Cart cart = (Cart) ActionContext.getContext().getSession().get("cart");
29 if (cart == null) {
30 cart = new Cart();
31 }
32 Product p = new ProductDAO().getProductById(newProductId);
33 if (p.getId() == 0) {
34 return ERROR;
35 }
36 cart.addProduct(p);
37 ActionContext.getContext().getSession().put("cart", cart);
38 return SUCCESS;
39 }
40
41 }
42

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\action\Prod
uctList.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package action;
7
8 import com.opensymphony.xwork2.ActionSupport;
9 import dao.ProductDAO;
10 import java.util.List;
11 import model.Product;
12
13 /**
14 *
15 * @author Ly Quynh Tran
16 */
17 public class ProductList extends ActionSupport {
18
19 private String keyword;
20 private List<Product> products;
21
22 @Override
23 public String execute() throws Exception {
24 products = new ProductDAO().getProductsByName(keyword);
25 return SUCCESS;
26 }
27
28 public void setKeyword(String keyword) {
29 this.keyword = keyword;
30 }
31
32 public String getKeyword() {
33 return keyword;
34 }
35
36 public List<Product> getProducts() {
37 return products;
38 }
39
40 }
41

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\src\java\action\View
Cart.java
1 /*
2 * To change this license header, choose License Headers in Project
Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package action;
7
8 import com.opensymphony.xwork2.ActionContext;
9 import com.opensymphony.xwork2.ActionSupport;
10 import java.util.Map;
11 import model.Cart;
12 import model.Product;
13
14 /**
15 *
16 * @author Ly Quynh Tran
17 */
18 public class ViewCart extends ActionSupport {
19
20 private Map<Product, Integer> products;
21 private float total;
22
23 @Override
24 public String execute() throws Exception {
25 Cart cart = (Cart) ActionContext.getContext().getSession().get("cart");
26 if (cart == null) {
27 return ERROR;
28 }
29 products = cart.getProducts();
30 total = cart.getTotalPrice();
31 return SUCCESS;
32 }
33
34 public Map<Product, Integer> getProducts() {
35 return products;
36 }
37
38 public float getTotal() {
39 return total;
40 }
41
42 }
43

C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\WebStruts2Shop\web\WEB-
INF\web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
3 <filter>
4 <filter-name>struts2</filter-name>
5 <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-
class>
6 </filter>
7 <filter-mapping>
8 <filter-name>struts2</filter-name>
9 <url-pattern>/*</url-pattern>
10 </filter-mapping>
11 <session-config>
12 <session-timeout>
13 30
14 </session-timeout>
15 </session-config>
16 <welcome-file-list>
17 <welcome-file>index.html</welcome-file>
18 </welcome-file-list>
19 </web-app>
20

Link reference

http://www.kieutrongkhanh.net/2017/07/su-dung-filter-ket-hop-voi-struts-
2.html?fbclid=IwAR1X64GeyuIOMwq1n-LeNm2593h6aOWgLQxwwyNBjUR57fyVLgz4stWctRc

http://www.kieutrongkhanh.net/2018/03/xay-dung-ung-dung-online-shopping-
cart.html?fbclid=IwAR0PwKP4N_XcYh87B-e_HjM-HB5aYA58cbeGyFTq4IT5KiwNHn8XiEy853E

https://drive.google.com/drive/folders/19_THZLBuTvbKfnvDKCJ7OnOTevNOw1rW?usp=sharing

You might also like