Sports Shop Notes

Posted by Ibnatu on Tue, 14 Dec 2021 18:09:42 +0100

2021/10/25

Main body process

  • Project Development Process
  • Database Analysis Design
  • Understanding B/S Architecture web Development
  • Web Technology Review and Practice
  • Front End Technology Enhancement
  • New Technology Learning

Software Development Process

  • requirement analysis
  • Outline design
  • detailed design
  • Code
  • test
  • Software Delivery
  • Check before acceptance
  • Maintain

development environment

  • Windows Operating System
  • MySql Database
  • Tomcat Server
  • Idea Development Tool
  • Use MVC + DAO mode
  • Project Name: Online Shopping Cart Project

The main function modules of the project

  • Commodity display module: commodity display, commodity inquiry, commodity details, commodity paging;
  • User module: user registration, login, exit login;
  • Shopping cart module: modification of goods added to shopping cart, shopping cart;
  • Order module: submit order, order information, order modification, etc.
  • Payment module: use WeChat payment to complete the payment of goods;
  • Receipt address: add, modify and set default receipt address;
  • Background module: to achieve the increase or deletion of users and commodities;

Database Analysis Design

  • PowerDesigner is used for database design;

  • First the CDM (Conceptual Data Model) is manually designed, then the PDM (Physical Data Model) is generated, and finally the.sql file of the database is obtained.

  • CDM: Describes the entities, attributes, and entity relationships to be stored;

  • PDM: Upgrade the conceptual data model to convert entities into models with database characteristics;

  • From entities to tables, from attributes to columns, to further complete data design;

  • Design ideas:

    • Visible
    • Invisible (need analysis)
    • Association Properties
  • Specific design (there is no relationship between the associated entity and the entity, that is, no foreign key)

    • User entity design (user entity of user module)

      create table user
      (
         u_id                 int not null auto_increment comment 'Primary Key Properties of User Entities',
         u_name               varchar(20) not null comment 'User Account',
         u_password           varchar(64) not null comment 'User Password',
         u_email              varchar(50) not null comment 'User's mailbox! For activation use!',
         u_sex                varchar(4) comment 'User gender!',
         u_status             int comment 'User's Activation State 0 Not Activated 1 Activation',
         u_code               varchar(64) comment 'Mail Activation Code',
         u_role               int comment 'User 0 Administrator 1',
         primary key (u_id)
      );
      
    • Receipt Address Entity Design (User's Personal Center's Address Entity, used to store address information)

      create table address
      (
         a_id                 int not null auto_increment comment 'Unique Primary Key Column for Address Entities',
         u_id                 int comment 'Primary Key Properties of User Entities',
         a_name               varchar(30) comment 'Address Recipient',
         a_phone              varchar(14) comment 'Recipient Phone',
         a_detail             varchar(200) comment 'Recipient Detailed Address',
         a_state              int comment 'Is default address 0 not 1 is default address',
         primary key (a_id)
      );
      
    • Merchandise Category Entity Design (Category Entity of Merchandise Module)

      create table type
      (
         t_id                 int not null auto_increment comment 'Primary Key for Category id',
         t_name               varchar(20) comment 'Name of category',
         t_info               varchar(200) comment 'Description of category',
         primary key (t_id)
      );
      
    • Design of commodity entities (commodity entities of the commodity module)

      create table product
      (
         p_id                 int not null auto_increment comment 'Unique primary key for goods',
         t_id                 int comment 'Primary Key for Category id',
         p_name               varchar(50) comment 'Name of the commodity',
         p_time               date comment 'Time of listing of goods',
         p_image              varchar(100) comment 'Path to merchandise pictures',
         p_price              decimal(12,2) comment 'prices for goods',
         p_state              int comment 'Hot Index for Commodities',
         p_info               varchar(200) comment 'Description of goods',
         primary key (p_id)
      );
      
    • Shopping cart entity design

      create table cart
      (
         c_id                 int not null auto_increment comment 'Unique identification of shopping cart',
         u_id                 int comment 'Primary Key Properties of User Entities',
         p_id                 int comment 'Unique primary key for goods',
         c_count              decimal(12,2) comment 'Shopping cart subtotal',
         c_num                int comment 'Number of shopping cart items',
         primary key (c_id)
      );
      
    • Order Entity Design (Order)

      create table orders
      (
         o_id                 varchar(64) not null comment 'Order number is a string type but also a unique identifier',
         u_id                 int comment 'Primary Key Properties of User Entities',
         a_id                 int comment 'Unique Primary Key Column for Address Entities',
         o_count              decimal(12,2) comment 'Total amount of the order',
         o_time               datetime comment 'Order Detail Time',
         o_state              int comment 'Order status 0 unpaid, 1 unpaid, 2 shipped to receive 3 received to evaluate 4 orders completed 5 returned status',
         primary key (o_id)
      );
      
    • Order interior goods specific display entity design

      create table item
      (
         i_id                 int not null auto_increment comment 'Unique identification of order item',
         o_id                 varchar(64) comment 'Order number is a string type but also a unique identifier',
         p_id                 int comment 'Unique primary key for goods',
         i_count              decimal(12,2) comment 'Subtotal of order items',
         i_num                int comment 'Quantity of order items',
         primary key (i_id)
      );
      
  • Association between entities (that is, adding foreign keys)

    alter table address add constraint FK_u_a_fk foreign key (u_id)
          references user (u_id) on delete restrict on update restrict;
    
    alter table cart add constraint FK_p_c_fk foreign key (p_id)
          references product (p_id) on delete restrict on update restrict;
    
    alter table cart add constraint FK_u_c_fk foreign key (u_id)
          references user (u_id) on delete restrict on update restrict;
    
    alter table item add constraint FK_o_i_fk foreign key (o_id)
          references orders (o_id) on delete restrict on update restrict;
    
    alter table item add constraint FK_p_i_fk foreign key (p_id)
          references product (p_id) on delete restrict on update restrict;
    
    alter table orders add constraint FK_a_o_fk foreign key (a_id)
          references address (a_id) on delete restrict on update restrict;
    
    alter table orders add constraint FK_u_o_fk foreign key (u_id)
          references user (u_id) on delete restrict on update restrict;
    
    alter table product add constraint FK_t_p_fk foreign key (t_id)
          references type (t_id) on delete restrict on update restrict;
    

2021/10/31

Project preparation

Establishment and preparation of projects

  • Create Project
  • Import Tool Class
  • Import jar package
  • Import Configuration File
  • Import Page

Writing Entity Classes

  • Each entity class implements the Serializable interface;

About why the Serializable interface is implemented?

  • Serializable is java. A semantic-level interface defined in the IO package to implement serialization of Java classes.
  • The Serializable serialization interface has no methods or fields but is used to identify serializable semantics.
  • Classes that implement the Serializable interface can be converted to byte streams by ObjectOutputStream, which can also be resolved to objects by ObjectInputStream.
  • For example, we can write a serialized object to a file, read it from the file again, and deserialize it into an object, that is, recreate the object in memory using type information and bytes that represent the object and its data.
  • Serializable and Deserialize
    • Serialization refers to the process of converting objects into byte sequences, which we call object serialization, which is the process of converting these objects in memory into a series of bytes.
    • Deserialization, on the other hand, is the process of restoring persisted byte file data as objects.
  • serialVersionUID
    • For a JVM, a class to be persisted must have a tag that only the holding JVM allows objects created by the class to be persisted by converting their IO system to byte data, which is the Serializable interface.
    • The serialVersionUID is used to determine which class loads this object during deserialization, so when we implement the Serializable interface, we usually define the serialVersionUID as visually as possible.

Write code filters

  • Requests and responses need to be coded before they can be released.

Create BaseServlet

  • Necessity of creating a BaseServlet;

    • To implement a function, we need to create a Servlet;
    • The drawbacks of this implementation:
      • A large number of Servlet s will be created;
      • Servlet instances are handed over to the web container (tomcat) for management;
      • A large number of Servlet instances will occupy a large amount of running memory;
      • This indirectly slows down the speed of the web container;
    • Knowledge Point: The doGet/doPost method of a servlet is a multithreaded method. A servlet can process requests many times or concurrently.
    • BaseServlet solves the following problems: simplifying and optimizing the creation and number of Servlets;
  • Ideas to implement BaseServlet;

    • Why should a Servlet correspond to a function before?

      • Because only one method is called after a Servlet is accessed, we are usually accustomed to writing a business logic in a method.
    • Ideas for implementation:

      • Let a Servlet correspond to multiple methods, each of which implements one business logic;

      • Steps to achieve:

        • Step 1: Declare multiple business logic methods in one Servlet;
        • Step 2: Add an identity to the path each time you access the Servlet, which is used to determine the specific business logic method you want to access.
        • Step 3: Each time you request the doGet/doPost/Service method, you can judge the identification of the parameters and call the corresponding business logic method.
  • Specific BaseServlet implementation (especially important here)

    • Implement the basic BaseServlet;

    • Optimize method calls;

      • The string using the identifier is the same as the method name;

      • You can use the reflection mechanism to call the corresponding execution method.

      • Avoid a lot of judgments;

      • When new methods appear, there is no need to add additional judgment methods.

        service(){    //1.Get the identifier//2. Call the corresponding logical method based on the identifier 		// Using Reflection Technology}
        
    • Optimize multiple Servlet implementations;

      • Ideas for implementation:
        • Create a BaseServlet class that inherits the HttpServlet;
        • Write service methods in BaseServlet;
        • Write in service: 1. Get the identifier; 2. Reflect call business logic;
        • Controller corresponding to each module can simply inherit the BaseServlet;
    • Optimize the return value problem;

      • Each method responds;
      • There are only four ways to respond: forward, redirect, return string, return byte stream;
      • So it can be processed in BaseServlet uniformly.
      • Steps:
        • Step 1: Change the return value of the method to a string, and you can start with
        • Step 2: Add a special identifier according to the contract;
        • BaseServlet centralized processing;
    • Handle identifier exceptions;

Specific code for BsaeServlet:

/** * BaseServlet Calls for centralized processing methods;* Return value processing;* Default page corresponding method processing; */public class BaseServlet  extends HttpServlet {    @Override    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //1. Request Acceptance Identifier//Identifier Provisions: Each time a request is made, the user needs to declare the value of the method parameter//parameter in the request's parameters, which is the method name we call String methodStr = request.getParameter(Constants.TAG); // Identifier exception handling//If the method does not get a value, we jump to the first page! If (methodStr == null || methodStr.equals (")) {methodStr = Constants.INDEX;} // 2. Call the corresponding business logic method (login, registration, etc.) // switch (method) {// case "login": // // The string of the identifier and the method name are the same; // / /Here you can use the reflection mechanism to call; // login (request, response); // break; // case "register" ://register(request, response);// Break; // Default://response. GetWriter(). Println ("No valid solution!"); //} // Reflect method of invoking business logic//Optimize 1: invoking method uses reflection technology//1. Gets the class object Class clazz = this for the class. GetClass(); // 2. Get Method/** * Parameter 1: Method Name;* Parameter 2...: Method parameter type; */ Try {Method method = clazz.getMethod (methodStr, HttpServletRequest.class, HttpServletResponse.class) ;// 3. Execution method/** * Parameter 1: Object to execute method * Parameter 2...: Parameter to execute method * Return value: Return value of execution method */ Object result = method. Invoke (this, request, response); If (result!= null) {//forward redirect return string String str = (String) result; //centralize return value response if (str.startsWith(Constants.FORWARD)) {//forward String path = str.substring (str.indexOf (Constants.FLAG) + 1; Request. GetRequestDispatcher (path). Forward(request, response);} Else if (str.startsWith (Constants.REDIRECT)) {//redirect String path = str.substring (str.indexOf (Constants.FLAG) + 1); response.sendRedirect (path);} Else{response.getWriter().println(str);}} Catch (Exception) {e.printStackTrace (); //To this point it means no reflection to the method}} /** * When the method identifier has no value, we assign an index by default, accessing the index method for each controller;* We can just extract the method into BaseServlet;* Default processing is to jump to the first page of the program; * @ Param request * @param response * @return * @throws IOException */ public String index (HttpServletRequest request, HttpServletResponse response) throws IOException {return Constants.FORWARD +'/index.jsp';}

Item Code

User management module

User registration
  • Functional description:

    • User name ajax asynchronous authentication
    • Registration function (inactive)
    • Send activation mail
    • Account Activation Function
  • Static pages used:

    • index.jsp

    • register.jsp

    • registerSuccess.jsp

    • message.jsp

User Login
  • Functional description:
    • Click on the login item to open the user login page
    • Enter user name and password to achieve user login function
  • Static pages used:
    • login.jsp
    • header.jsp
User Logoff
  • Functional description:
    • Information stored in session before emptying
    • Cancel auto login within 14 days to overwrite local cookie s;
    • Finally, jump to the login page;

Base64Utils (converting mailboxes to strings and also encrypting)

C3P0Utils (Database Connection Pool, Connect Database)

Constants (project constants library, give meaning to constants)

EmailUtils (Mailbox Authentication, User Activation Tool)

MD5Utils (Password Encryption Tool Class, Encrypt User Password into Database)

RandomUtils (Random Number Tool Class, Generates Random Numbers and Time Stamps, guarantees that random numbers are unique, act as user activation codes and can also act as accounts for user orders)

Commodity module

INSERT INTO TYPE (t_id,t_name,t_info) VALUES(1,"shoes" ,"Mainly running shoes!"),(2,"clothes" ,"Protect your skin while running!"),(3,"Cap" ,"Help you go one step further!"); INSERT INTO product (t_id,p_name,p_time,p_image,p_price,p_state,p_info) VALUES(1,"Adidas SL20.2 Shock-absorbing jogging shoes","2021-10-1","image/shoes01.jpg",379,4,"SL20.2 Major in lightweight running shoes, use the latest shock absorbing materials!"),(1,"Adidas Solar Drive Training jogging shoes","2021-10-2","image/shoes02.jpg",299,4,"The most comfortable shoe to cushion in training shoes!"),(1,"Adidas adiZero 5 Speed shoes","2020-10-1","image/shoes03.jpg",449,4,"Castle Peak College!"),(1,"ASICS Tiger walk Tarther","2021-10-3","image/shoes04.jpg",482,4,"Tiger walking is the most classic speed shoe!"),(1,"Nike next%2","2021-10-4","image/shoes05.jpg",1364,4,"The latest technology is leading the running trend!"),(1,"Nike React Infinity Run","2021-10-5","image/shoes06.jpg",340,4,"Use react Foam, reduce sports damage!"),(1,"Salomon XT-6","2021-10-6","image/shoes07.jpg",1298,4,"Cross-country performance shoes, with clever design and innovative technology to protect the athletes!"),(1,"New Balance NB5740","2021-10-6","image/shoes08.jpg",970,4,"Fashionable and easy to wear!"),(1,"Mizuno Rider25","2021-10-8","image/shoes09.jpg",568,4,"Meizumino's jogging and supporting running shoes are a new generation Enerzy Use of materials to help runners go further!"),(1,"160X2.0 Treadmill shoes","2021-10-6","image/shoes10.jpg",999,4,"Home-made speed running shoes with excellent performance, recommended by national marathon team members!"),(2,"Nike AEROSWIFT TEAM KENYA","2021-11-5","image/cloth01.jpg",349,5,"Kenya National Team uniform, nike The latest weaving technology, great light running vest!"),(2,"Nike Oregon Track Club","2021-11-9","image/cloth02.jpg",279,5,"Oregon Club running vest, a touch of green brings you back to nature!"),(2,"Dover Walker's Vest","2021-10-5","image/cloth03.jpg",99,5,"An ultra light vest created by Dover Walkers for marathon enthusiasts!"),(2,"ILoveRunning ILR vest","2021-11-1","image/cloth04.jpg",49,5,"Use lightweight, quick-dry fabrics to keep your sport dry!"),(2,"Special Pedestrians Racing Generation Black Gold vest","2021-11-2","image/cloth05.jpg",179,5,"Chinese people race, be the fastest person in China, throw themselves into running, love running!"),(2,"Biwalk Running Vest","2021-11-6","image/cloth06.jpg",129,5,"With quick-dry fabrics, the sweat excluded from the human body is absorbed instantly and the feeling of dryness is always maintained!"),(2,"UTO Long-distance sports vest","2021-11-2","image/cloth07.jpg",99,5,"Adopt Israel Nilit Suction and exhaust yarn, combined with Italian seamless integrated shaping technology, sports without worry!"),(2,"QINKUNG Light Work Athletic Running Vest","2021-11-3","image/cloth08.jpg",328,5,"Put on your waist and forget all your identities, and I'm a runner!"),(2,"Solitary Request with Combustion Equipment GREARLAB","2021-11-5","image/cloth09.jpg",299,5,"The owner of the lonely shadow on the summer runway is the great God that nobody dares to bring!"),(2,"Decarnon Sports Vest MSCF","2021-11-8","image/cloth10.jpg",99,5,"Designed for track and field sports!"),(3,"Onitier knitted cap outdoors in winter","2021-9-12","image/hat01.jpg",68,5,"Warm velvet cap, wind proof and warm, soft and comfortable!"),(3,"Buff Running cap sun protection in autumn and winter","2021-9-13","image/hat02.jpg",249,5,"Foldable ultra light design, the whole only 30g!"),(3,"Outdoor marathon sun caps","2021-9-14","image/hat03.jpg",80,5,"Lightweight, breathable and comfortable, suitable for sun protection and sweating in hot weather!"),(3,"compresssport Sports Competition Running Fitness Cap","2021-9-15","image/hat04.jpg",369,5,"Put on this cap, you can keep in style in fast-paced games too!"),(3,"Salomon REFFLECTIVE Marathon cross-country cap","2021-9-6","image/hat05.jpg",159,5,"Lightweight, breathable with a top shade cap, sweat band set for head circumference measurement!"),(3,"Ducanon rainproof duck-tongue cap in autumn and winter","2021-9-17","image/hat06.jpg",49,5,"Shade and rain in one step!"),(3,"Combustion equipment empty cap","2021-9-12","image/hat07.jpg",79,5,"Lightweight design for a more comfortable experience!"),(3,"BUFF VISOR","2021-9-23","image/hat08.jpg",188,5,"Integrated folding cap for easy storage and carrying!"),(3,"Mizuno Sports cap","2021-9-27","image/hat09.jpg",85,5,"Meizumi thick classic running training cap, with you to run, without fear and pride!"),(3,"Saucony Running Trend Cap","2021-9-19","image/hat10.jpg",140,5,"Mesh material veneer, comfortable texture, provides ventilation all day long!");
Commodity display
  • Functional description:

    • Home Category Display
    • Page-by-page display of categories
    • Commodity details display
  • Static pages used:

    • header.jsp (category display)

    • goodsList.jsp (Commodity List)

    • goodsDetail.jsp (Commodity Details List)

2021/11/1

Paging ideas

List<Product>   //Place all items (backend processing) totalPage // total pages, unknown (backend processing, totalCount/pageSize) currentPage // what page is currently (front-end returned) totalCount 		// Total number of bars, number of items (backend processing, based on data in the database) pageSize 		// The number of items per page, fixed (front-end returns), so create another entity class, PageBean, for categorization;

Shopping Cart module

Shopping cart additions
  • Functional description:

    • Add a shopping cart;
    • Shopping cart data;
    • Modify shopping cart data;
    • Delete individual data;
    • Empty the shopping cart;
  • Static pages used:

    • goodsDetail.jsp (with add cart button)

    • cartSuccess.jsp (Query cart details button when adding goods successfully)

    • header.jsp (also has the inquiry cart details button)

    • cart.jsp (Shopping Cart Details Page)

2021/11/2

Address module

Receipt address
  • Functional description:
    • Show Address Function
    • Add Address Function
    • Delete Address Function
    • Set Default Address Function
    • Modify Address Function
  • Static pages used:
    • cart.jsp (add receipt address)
    • self_info.jsp (Personal Center, page showing personal receipt address, adding receipt address)

2021/11/3

Order module

Generate order and display
  • Functional description:
    • Click on the shopping cart to open the shopping cart page;
    • Click Add Address and jump to page to preview the order (the combination of shopping cart and receiving address);
    • Click Submit Order to jump to the order information confirmation page;
    • If the shopping cart is empty, the order cannot be submitted;
    • When the order is successfully generated, the order is displayed and the order status is unpaid.
    • Finally, there is the order details page;
  • Static pages used:
    • cart.jsp (the entry to the order is in the shopping cart)
    • order.jsp (click on the page jumped by adding a receipt address, here is the button to submit the order)
    • orderList.jsp (last page's shopping cart data and address data together to generate order data, the user order list page)
    • header.jsp (click on the Personal Order button and also the User Order List page)
    • orderDetail.jsp (Order Details Page)
payment
  • Functional description:
    • Click Payment to open the Payment page;
    • Select the method of payment and complete the payment;
  • Static pages used:
    • orderList.jsp
View historical orders
  • Functional description:
    • Click on the order to open the historical order list page, you can view the order;
    • Be sure to log in first, order status is:
      • Not paid; No shipment has been paid; Shipped for receipt; Complete the order;
  • Static pages used:
    • orderList.jsp

2021/11/8

Database Connection Pool

  • Concepts: In fact, it is a container (collection) that holds database connections. When the system is initialized, the container is created, and some connection objects are requested in the container. When the user visits the database, the connection objects are retrieved from the container and returned to the container after the user visits the database.

  • Advantage:

    • Save resources (connecting objects can be used repeatedly);
    • User access efficiency is improved;
  • Realization:

    • DataSource Standard Interface (under the javax.sql package)
      • Get a connection: getConnection()
      • Return connection: Connection.close() //Call Connection if the connection object Connection is obtained from the connection pool. The close() method does not close the connection but returns it to the connection pool.
    • But we generally don't implement this interface, it's implemented by database vendors
      • C3P0: Database connection pool technology;
      • Druid: Database connection pool technology, which is provided by Alibaba;

C3P0

  • Steps:
    • Import jar packages: (two more important) (don't forget to import database-driven jar packages)
      • c3p0-0.9.5.2.jar (need to import)

      • mchange-commons-java-0.2.12.jar (need to import)

      • c3p0-0.9.5.2-sources.jar (see the source package)

      • c3p0-config.xml (configuration file)

    • Define the profile:
      • There must be c3p0 under the class path. Properties or c3p0-config.xml
      • Place the configuration file directly in the src directory;
    • Create Core Object: Database Connection Pool Object ComboPooledDataSource
    • Get a connection: getConnection()

Druid

  • Steps:

    • Import jar package: (one is more important)
      • druid-1.0.9.jar (need to import)

      • druid.properties (configuration file)

      • druid-1.0.9-javadoc.jar (document)

      • druid-1.0.9-sources.jar (source)

    • Define the profile:
      • Is in the form of properties;
      • File names can be arbitrary and directory locations can be arbitrary, but they need to be loaded manually;
    • Load configuration file:properties
    • Get the database connection pool object: Get DruidDataSourceFactory from the factory class
    • Get a connection: getConnection()
  • Define Tool Classes

    • Define a class JDBCUtils

    • Provides a static code block load profile to initialize connection pool objects;

    • Provide methods:

      • How to get the connection: Get the connection through the database connection pool;
      • Release resources;
      • The method to get the connection pool;

2021/11/9

JSTL

  • Disadvantages of EL expressions:

    • It is mainly used to obtain data from scopes. Although it can be used for operational judgment, all the results are presented as a result.
    • There is no process control, such as judgment;
    • For collections, only single-point access is possible, and traversal operations, such as loops, are not possible.
  • What is JSTL: Java Server Page Standard Tag Library (JSP tag library), also known as JSP tag collection;

  • JSTL action:

    • The data obtained by EL can be logically manipulated, such as judgement;
    • Working with EL to complete data presentation, such as traversing collections;
  • Use of JSTL:

    • First import the jar package;

    • Introducing tag libraries on jsp pages

      <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      

Use of core labels

Single condition label if judgment
<c:if test="condition"></c:if>
Multiple Conditional choose Judgment
<c:choose>    <c:when test="Condition 1">Result 1</c:when>    <c:when test="Condition 2">Result 2</c:when>    <c:when test="Condition 3">Result 3</c:when>    <c:otherwise>Result 4</c:otherwise></c:choose>
Iterate foreach Tags
<c:foreach    var="Variable Name"    items="aggregate"    begin="Start Subscript"    end="End Subscript"    step="Interval length"    varstatus="Traversal state"></c:foreach>   

Where varStatus defines:

  • Is first the first line
  • Is last the last line
  • count Current number of rows
  • index current element subscript
url tag
  • When cookie s are prohibited, the ID value is passed by rewriting the URL splicing JSESSIONID so that the last Session object can be found on the next visit.
<c:url context="" value=""></c:url>

Topics: JavaEE