Crazy God notes sorting | JavaWeb | SMBMS project | file upload and mail sending

JavaWeb

1. Basic concepts

1.1 concept

web development:

  • Web, the meaning of web page, www.baidu.com com·

  • Static web

    • html,css
    • The data provided to everyone will never change!
  • Dynamic web

    • Taobao, almost all websites;
    • The data provided to everyone will always change, and everyone will see different information at different times and places!
    • Technology stack: Servlet/JSP, ASP, PHP

1.2 web application:

web application: a program that can provide browser access;

  • a.html, b.html... Multiple web resources can be accessed from outside to provide services to the outside world
  • Any page or resource you can access exists on a computer in a corner of the world.
  • URL
  • These unified web resources will be placed in the same folder, web application – > Tomcat: server
  • A web application consists of many parts
    • html,css,js
    • jsp,servelt
    • java program
    • jar package
    • Configuration files (Properties)

After the web application is written, if you want to provide access to the outside world; A server is needed for unified management;

1.3 static web

  • *.htm, *. html these are suffixes of web pages. If these Dongsi exist on the server all the time, we can read them directly and need the network;

  • Disadvantages of static web

    • web pages cannot be updated dynamically. All users see the same page
      • Rotation chart: click effect: pseudo dynamic
      • JavaScript [most used in actual development]
      • VBScritp
    • It cannot interact with the database (data cannot be persisted, and users cannot interact)

1.4 dynamic web

The page will be displayed dynamically, "the display effect of web page varies from person to person"

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hfcrtce-1639619842276) (C: / users / 77 / appdata / roaming / typora / typora user images / image-20211202083847696. PNG)]

Disadvantages:

  • There is an error in the dynamic web resource added to the server. We need to rewrite the background program and publish it again

advantage:

  • web pages can be updated dynamically, and all users don't see the same page
  • He can interact with the database (data persistence: registration, product information, user information...)

2.web server

2.1 technical explanation

ASP

  • Microsoft: the earliest ASP left in China
  • Embedded VB script in HTML, ASP+COM
  • In ASP development, a page has thousands of lines of business code
  • High maintenance cost

PHP

  • PHP has fast development speed, powerful functions, cross platform, and simple code (70%, WP)
  • Unable to carry large traffic (limitations)

JSP/Servlet

B/S: browser and server; C/S: client and server

  • B/S architecture mainly promoted by sun company
  • Java language based
  • It can bear the impact of three high (high concurrency, high availability and high performance) problems
  • The syntax is similar to ASP to strengthen the market intensity

2.2 web server

Server is a passive operation, which is used to process some user requests and give users some response information

IIS: Microsoft, built-in in windows

Tomcat: Tomcat is the Apache Software Foundation (Apache Software Foundation) a core project in the Jakarta project. The latest Servlet and JSP specifications can always be reflected in Tomcat. Tomcat 5 supports the latest Servlet 2.4 and JSP 2 specifications. Because Tomcat technology is advanced, stable and free, it is deeply loved by the fans and has been recognized by some software developers. Popular Web application server.

Tomcat server is a free open source Web application server, which is a lightweight application The server , it is widely used in small and medium-sized systems and not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a beginner, it is the best choice

The trick is that when configured correctly, Apache serves HTML pages, while Tomcat actually runs JSP pages and servlets. In addition, Tomcat and IIS Like other Web servers, it has the function of processing HTML pages. In addition, it is also a Servlet and JSP container. The independent Servlet container is the default mode of Tomcat. However, Tomcat handles static HTML Is not as powerful as Apache server. The latest version of Tomcat is 10.0 five

[Extension]

Rt.jar: rt.jar represents the runtime JAR and contains bootstrap classes -- all classes from the Core Java API.

Windows and Linux Rt.jar is located in the lib directory of JRE. Before JDK 1.7, it was called classes in Mac OS X Jar, starting from Java 7, is also changed to rt.jar. Many developers try to put their own classes into rt.jar to solve the problems related to class path, but it is best not to do so, because rt.jar contains class files trusted by the JVM, and the JVM will not strictly check the security of other class files when loading.

rt.jar is a zip like compressed file, precisely called "Java archive" (jar), which stores all the resources required by Java class files and programs. It can also contain mainfest files and main class entries. It becomes an executable jar and runs with the Java jar command.

  1. rt.jar stands for runtime and contains compiled calss files for all core Java runtime environments.
  2. You must include rt.jar in the classpath, otherwise you do not have access to core classes, such as Java. Jar lang.String,java.lang.Thread,java.util.ArrayList or Java io. InputStream, etc., and other classes in all Java APIs. You can use the IDE to open and view the contents of rt.jar, which contains not only all Java APIs, but also the internal classes specified in the com package.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-cko1udg8-1639619842278) (C: / users / 77 / appdata / roaming / typora / typora user images / image-2021120209141420. PNG)]

  1. In windows, rt.jar is located in Java_ Under home / JRE / lib. Even if you do not install JDK and only install JRE, you will see it in exactly the same location, in Java_ Rt.jar not found in home / lib directory.

  2. Rt.jar is the location of all Java packages. For example, from Java util. The concurrenctpackage reference class, such as concurrencthashmap, will be looked up by the JVM from rt.jar so that the program can run correctly.

  3. Another question often asked by Java developers is, where can I find the source code of the classes contained in rt.jar? JDK can be installed in $JAVA_HOME / src.zip file to find all the source code. BTW,sun.* The source code is also included in SRC Zip, but this is proprietary closed source Oracle code.

  4. One important thing about rt.jar is that the JVM knows all the classes in the JAR file, which means that the JVM will not perform checks when loading from any location. This is done for various performance reasons, which is why these classes are loaded by bootstrap or primodial class loaders. So it's best not to try to include your class files in rt.jar, which is not recommended by Java officials.

3. Tomcat

3.1 installing Tomcat

Install Tomcat Apache Tomcat download, installation and configuration tutorial

3.2 Tomcat startup and configuration

Starting and shutting down Tomcat

Start this page:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qxljmxjj-1639619842279) (C: / users / 77 / appdata / roaming / typora / typora user images / image-20211202092658814. PNG)]

Successful startup:

Problems:

  1. Java environment variables are not configured
  2. Flash back problem: compatibility needs to be configured
  3. Garbled code problem: set in the configuration file

You can modify conf / logging Java. In properties util. logging. ConsoleHandler. Encoding = GBK solves the problem of garbled code

3.3 configuration

You can configure the port number for startup

  • The default port number of tomcat is 8080
  • mysql:3306
  • http:80
  • https: 443

You can configure the name of the host

  • The default host name is localhost - > 127.0 zero point one
  • The default site application location is webapps

Change the default localhost of the host

If you want to modify the mapping of localhost, you can modify host in C:\Windows\System32\drivers

There are only two default mappings. Now add a Xiaoqi Go in. Com

Later in

You can enter this website by modifying the name of the host

Please talk about how the website is accessed!

  • Enter a domain name: Enter
  • Check whether there is a mapping of this domain name under the C:\Windows\System32\drivers\etc\hosts configuration file of this machine
    • Yes: directly return the corresponding IP address
    • None: find the DNS server, return if found, and return 404 if not found
  • Configure environment variables

3.4 publish a web site

  • Put the website written by yourself under the specified web application folder (webapps) in the server (Tomcat), and you can access it

Structure of website

--webapps : Tomcat Server web catalogue
	-ROOT
	-kuangstudy : Directory name of the web site
		- WEB-INF
			-classes : java program
			-lib: web Application dependent jar package
			-web.xml : Site profile
		- index.html Default home page
		- static 
            -css
            	-style.css
            -js
            -img
         -.....

4. HTTP

4.1 introduction to http

HTTP: Hypertext Transfer Protocol, running over TCP

  • Text: html
  • Hypertext: picture, music, video, location, map
  • http default port: 80
  • https: default port 443

4.2 two times

  • http1.0
    • HTTP/1.0: after the client can connect to the web server, it can only obtain one web resource and disconnect
  • http2.0
    • HTTP/1.1: after the client can connect with the web server, it can obtain multiple web resources.

4.3 Http request

request URL: https://www.baidu.com / request address
 Request method: GET  Request mode
 Status code: 200  
Remote address: 221.180.224.32:443
 Reference site policy: unsafe-url
Accept: text/html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Cookie: BIDUPSID=8A6AE05E30038BBC7948753470556D7A; PSTM=1614658565; BD_UPN=12314753; __yjs_duid=1_337238548b71ba0b10c86b119d21bbfc1620368349218; BDUSS=hmZHY3WDRUOEtjUDRnOW9-aW8yM2ZoSFpSMFgtQU8xM0RvYXpmeVlQODlsUXRoRVFBQUFBJCQAAAAAAAAAAAEAAADRzC-UxO7G33IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD0I5GA9CORgeH; BDUSS_BFESS=hmZHY3WDRUOEtjUDRnOW9-aW8yM2ZoSFpSMFgtQU8xM0RvYXpmeVlQODlsUXRoRVFBQUFBJCQAAAAAAAAAAAEAAADRzC-UxO7G33IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD0I5GA9CORgeH; BAIDUID=E4DB781D2FC507A01A723B457A3168D4:FG=1; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; BAIDUID_BFESS=6CD2DB7B468919A666E80AC79B5D16F7:FG=1; BDRCVFR[CgxaefauCu_]=mk3SLVN4HKm; BD_HOME=1; BDRCVFR[9YlbB-d_Yv6]=mk3SLVN4HKm; delPer=0; BD_CK_SAM=1; PSINO=1; BDRCVFR[yXDDijtIVMD]=mk3SLVN4HKm; rsv_jmp_slow=1638427343111; ab_sr=1.0.1_ZTM5ZWQyMWE3YTU1YzFiNmUyNDNhYjc2YTJlNTYzOWMyZWVjOGE2ZTBlYjBkZjBiYWM2NDdiNmRiODMxNDY0NGY3NGQ3NmE4NThhM2VjNWRhNzM5OTE2ZTlhMGEyZTU3MTM2NzkwMTEwZTFkZmI5OGMwYTZkNDM2OGQ2NTNlODI2MWRjZDVhMTcyMTIzYzYwMTNkYmZlYTg0ZjcyMjFiNA==; H_PS_PSSID=; channel=2143.new.favo.diufeng.cn; H_PS_645EC=a46b4FtnN%2FpDwvUHsABwti8%2FRV3iLccBV8PY2o%2Fb2dZl5UXLQNXPDHMw%2BZbC41CKFiLObtfWkWoq; baikeVisitId=82e82499-fa3a-4730-820c-1538974b39bc; sugstore=1; BA_HECTOR=0k050k840g2k058khq1gqgqqr0r
Host: www.baidu.com
Referer: http://2143.new.favo.diufeng.cn/

1. Request method in request line: GET

  • Request method: get, post, head, delete, put, trace
  • get: the request can carry few parameters with limited size. The data content will be displayed in the URL address bar of the browser, which is unsafe but efficient
  • post: the parameters that the request can carry are not limited, and the size is not limited. The data content will not be displayed in the URL address bar of the browser. It is safe but not efficient

2. Request message header

Accept: Tell the browser what data types it supports
Accept-Encoding: Which encoding format is supported  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language: Tell the browser its locale
Cache-Control: Cache control
Connection: Tell the browser whether to disconnect or remain connected when the request is completed
HOST: host..../.

4.4 Http response

Cache-Control: private   Cache control
Connection: keep-alive   connect
Content-Encoding: gzip   code
Content-Type: text/html;charset=utf-8  type

1. Responder

Accept: Tell the browser what data types it supports
Accept-Encoding: Which encoding format is supported  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language: Tell the browser its locale
Cache-Control: Cache control
Connection: Tell the browser whether to disconnect or remain connected when the request is completed
HOST: host..../.
Refresh: Tell the client how often to refresh;
Location: Repositioning the web page;

2. Response status code

  • 200: request response succeeded
  • 3xx: request to punch
  • 4xx: resource not found; 404: resource does not exist
  • 5xx: service code error; 500 502: gateway error

When you enter in the browser and enter, the page shows back. What did you experience

  1. Domain name resolution: finding IP addresses

    The browser obtains the URL address and requests the IP address corresponding to the URL from the operating system. The operating system first queries the local HOST file by querying DNS (domain name system). If not, query the network to obtain the corresponding IP address

    Explanation: divide the URL into several parts: protocol, network address and resource path. The protocol refers to the way the computer obtains resources. The common ones are HTTP and FTP; The network address can be domain name or IP address, or include port number. If the port number is not indicated, the default is port 80.

  2. After DNS returns the IP address and confirms the IP and port number, it can initiate a TCP connection to the server corresponding to the IP address - three handshakes

  3. The browser sends an HTTP request to a web server

  4. The server responds to HTTP requests

  5. The browser parses the HTML code and requests static resources of HTML

  6. Close TCP connection - four waves

  7. Browser render page

5.Maven

Configuring Tomcat in 5.1Maven

Why is this problem? When we visit a website, we need to specify a folder name

5.2 pom documents

pom.xml: is the core configuration file of maven

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>javaweb-02-maven</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--Project dependency-->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!--stay build Medium configuration resource,To prevent the failure of resource export-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

5.3 write html by example

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0">

  <!--web.xml Is to configure us web Core application of-->
  <!--register Servlet-->
  <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>xiaoqi.HelloServlet</servlet-class>
  </servlet>

  <!--servlet Corresponding to one mapping: mapping-->
  <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <!--Request path-->
    <url-pattern>/xiaoqi</url-pattern>
  </servlet-mapping>
</web-app>

HelloServlet

package xiaoqi;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        //Type of response: html
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        //Gets the output stream of the response
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello World!</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Xiao Qi</h1>");
        out.println("</body>");
        out.println("</html>");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

6. Servlet

6.1 introduction

  • Servlet is a technology for sun company to develop dynamic web
  • sun provides an interface called Servlet in these API s. If you want to develop a Servlet program, you only need to complete two small steps
    • Write a class to implement the Servlet interface
    • Deploy the developed Java classes to the web server
  • The Java program that implements the Servlet interface is called Servlet

6.2 HelloServlet

1. Build a maven project and delete the src directory. In the future, we will build a mold in this project; This empty project is the main project of Maven

2. Understanding of maven father son project

  • The parent project will have:
<modules>
    <module>servlet-01</module>
</modules>
  • There will be:
<parent>
    <artifactId>javaweb-03-maven</artifactId>
    <groupId>org.example</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>

The jar package in the parent project can be directly used by the child project

3. Optimization of Maven environment

  • The web Replace XML with the latest
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0">
  
</web-app>
  • Import dependency

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    
  • Complete the structure of maven

4. Write a Servlet program

  • Write a common class
  • Implement Servlet interface [Servlet has two default implementation classes in sun company: HttpServlet and]
package xiaoqi.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    //Because get/post is only a different way of request implementation, they can call each other, and the business logic is the same
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        //ServletOutputStream outputStream = resp.getOutputStream();
        PrintWriter writer = resp.getWriter();//Response flow
        
        writer.println("Hello Servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

5. Write Servlet mapping

We write a java program, but to access it through the browser, the browser needs to connect to the web server, so we need to register the servlet we write in the web service and give it a path that the browser can access

<!--register servlet-->
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>xiaoqi.servlet.HelloServlet</servlet-class>
</servlet>
<!--servlet Request path for-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/xiaoqi</url-pattern>
</servlet-mapping>

6. Configure Tomcat

7. Start test

6.3 Servlet operation principle

Servlet is called by the web server. After receiving the browser request, the web server will

6.4 Mapping

  1. A Servlet can specify a mapping path

     <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/xiaoqi</url-pattern>
        </servlet-mapping>
    
  2. A Servlet can specify multiple mapping paths

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/xiaoqi</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/xiaoqi2</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/xiaoqi3</url-pattern>
        </servlet-mapping>
    
  3. A Servlet can specify a common mapping path

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/xiaoqi/*</url-pattern>
        </servlet-mapping>
    
  4. Default request path

    <!--Default request-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/*</url-pattern>
    
  5. Specify some suffixes or prefixes, etc

    <!--You can customize the suffix to implement request mapping
     Note:*A path that cannot be preceded by a map
     As long as xiaoqi Just the end-->
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.xiaoqi</url-pattern>
    </servlet-mapping>
    
  6. Priority issues

    Specifies that the inherent mapping path has the highest priority. If it cannot be found, the default processing request will be returned;

     <!--404-->
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>.servlet.ErrorServlet</servlet-class>
     </servlet>
    
     <servlet-mapping>
         <servlet-name>error</servlet-name>
         <url-pattern>/*</url-pattern>
     </servlet-mapping>
    
    public class ErrorServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            PrintWriter writer = resp.getWriter();
            writer.println("<h1>404</h1>");
    
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    
    }
    

6.5 servletContext

When the web container starts, it will create a corresponding Servlet object for each web program, which represents the current application.

shared data

  • The data I save in this Servlet can be obtained in another Servlet

    Create a class that writes to the context

package xiaoqi.servlet;

import sun.security.ec.point.ProjectivePoint;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("hello");
        //this.getInitParameter();  Initialization parameters
        //this.getServletConfig(); Servlet Configuration 
        //this.getServletContext();  context
        ServletContext servletContext = this.getServletContext();
        String username = "Xiao Qi";//data
        servletContext.setAttribute("username", username);//A data is saved in ServletContext,k:username v:username
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Create a class that reads the context

package xiaoqi.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        ServletContext servletContext = this.getServletContext();//Share one
        String username = (String)servletContext.getAttribute("username");
        PrintWriter writer = resp.getWriter();
        writer.println(username);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>xiaoqi.servlet.HelloServlet</servlet-class>
        <!--Place some initialization parameters
        <init-param>
            <description></description>
        </init-param>-->
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>getcontext</servlet-name>
        <servlet-class>xiaoqi.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getcontext</servlet-name>
        <url-pattern>/context</url-pattern>
    </servlet-mapping>
</web-app>

result

Enter first localhost:8080/servlet_02_war/hello : save to context

In entry localhost:8080/servlet_02_war/context : read

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-pexfpzga-1639619842287) (C: / users / 77 / appdata / roaming / typora / typora user images / image-20211205095326358. PNG)]

Get initialization parameters

Configure web initialization parameters

  <!--to configure web Applied initialization parameters-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>

Get use

public class ServletDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().println(url);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Register binding

<servlet>
    <servlet-name>mysql</servlet-name>
    <servlet-class>xiaoqi.servlet.ServletDemo03</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>mysql</servlet-name>
    <url-pattern>/mysql</url-pattern>
</servlet-mapping>

Request forwarding

public class ServletDemo04 extends HttpServlet{
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Entered Demo04");
        ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/mysql").forward(req,resp);//Forward the request path to obtain the request forwarding
        //forward realizes forwarding: two parameters req resp, one request and one response

    }
}
    <servlet>
        <servlet-name>se4</servlet-name>
        <servlet-class>xiaoqi.servlet.ServletDemo04</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>se4</servlet-name>
        <url-pattern>/se4</url-pattern>
    </servlet-mapping>

Read resource literature

Properties class

  • Create new Properties in the java directory
  • Create new Properties in the resource directory

The discovery is packaged in the same path: classse, which we commonly call classpath

Idea: you need a file stream

username=xiaoqi
password=123456
package xiaoqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream resourceAsStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties pro = new Properties();
        pro.load(resourceAsStream);
        String username = pro.getProperty("username");
        String password = pro.getProperty("password");
        resp.getWriter().println(username);
        resp.getWriter().println(password);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Test access results

6.6 HttpServletResponse

The web server receives the http request from the client. For this request, create a ServletRequest object representing the request and an HttpServletResponse representing the response

  • If you get the parameters requested by the client: find HttpServletRequest
  • If you want to respond to the client with some information: find HttpServletResponse

1. Simple classification

Responsible for sending data to the browser - write method

ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;

Method responsible for sending response header to browser

void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setBufferSize(int var1);
int getBufferSize();
void setHeader(String var1, String var2);
void setIntHeader(String var1, int var2);

Response status code

int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200;
int SC_MULTIPLE_CHOICES = 300;
int SC_NOT_FOUND = 404;
int SC_INTERNAL_SERVER_ERROR = 500;

2. Common applications

  1. Output a message to the browser - getwrite
  2. Download File
    1. To get the path of the downloaded file
    2. What is the name of the downloaded file
    3. Set up a way to make the browser support downloading the files we need
    4. Gets the input stream of the downloaded file
    5. Create buffer
    6. Get outputstream object
    7. Writes the fileoutputstream stream to the buffer buffer
    8. Use outputstream to output the data in the buffer to the client
package xiaoqi.Servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Find the path to download the file
        String realPath = "D:\\java\\javaweb\\javaweb-03-maven\\response\\target\\classes\\1.png";
        //this.getServletContext().getRealPath() / / get the absolute path of the current project
        System.out.println("Path to download file" + realPath);
        //public int lastIndexOf(int ch): returns the index of the last occurrence of the specified character in this string. If there is no such character in this string, it returns - 1.
        //2. Get the name of the downloaded file
        //D:\java\javaweb\javaweb-03-maven\response\target\classes\1.jpg
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);//This position is 1 jpg
        System.out.println(filename);
        //3. Set the header information of the web download file
        //Its function is to set the header of the response. Content disposition: indicates the configuration information of the response, and attachment: indicates that attachments are included
        //URLEncoder.encode(filename,"utf-8") converts the file name to utf-8 so that the browser can understand the Chinese file name
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));//Pay attention to use here;
        //4. Turn file into stream
        FileInputStream fileInputStream = new FileInputStream(realPath);//Turn a file into a stream
        //5. Create buffer
        int len = 0;
        byte[] buffer = new byte[1024];//buffer
        //6. Create output stream
        ServletOutputStream outputStream = resp.getOutputStream();
        //7. Write the buffer to the client through the output stream
        while ((len=fileInputStream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);//Write out the buffer
        }
        outputStream.flush();
        fileInputStream.close();
        outputStream.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

3. Verification code function

How did the verification come from?

  • Front end implementation
  • The back-end implementation needs to use the Java picture class to produce a picture
package xiaoqi.Servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //How to make the browser refresh automatically once
        //Refresh every 3 seconds
        resp.setHeader("refresh","3");
        //How to create a picture in memory
        BufferedImage bufferedImage = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);
        //Get pictures
        Graphics2D graphics = (Graphics2D)bufferedImage.getGraphics();//2D pen
        //Set the background color of the picture
        graphics.setColor(Color.white);//background color 
        graphics.fillRect(0,0,80,20);//Coordinates and length and width
        //Write data to the picture and generate random numbers
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(null,Font.BOLD,14));
        graphics.drawString(makeNumber(),0,20);

        //Tell the browser to open the request as a picture
        resp.setContentType("image/png");//Format response
        //There is a cache in the website. Do not let the browser cache
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");//Cache control does not cache
        resp.setHeader("Pragma","no-cache");

        //Write the picture to the browser
        ImageIO.write(bufferedImage, "png", resp.getOutputStream());
    }

    private String makeNumber(){
        Random random = new Random();
        String s = random.nextInt(99999999) + "";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i =0; i<8-s.length() ;i++){
            stringBuffer.append("0");
        }
        String s1 = stringBuffer.toString() + s;//There must be an 8-digit number
        return s1;

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

4. Redirection

After a web resource receives a client request, it will notify the client to access another web resource. This process is called redirection.

void sendRedirect(String var1) throws IOException;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*Implementation of redirection
        resp.setHeader("Location","/r1/image");
        resp.setStatus(302);
         */
        resp.sendRedirect("/r1/image");//Skip to this request
    }

Question: what is the difference between redirection and forwarding?

Same point: the page will jump

Difference: the url will not change when the request is forwarded

When redirecting, the url will change

Simulate a user login

User login page

<html>
<body>
<%@page pageEncoding="UTF-8" %>
<h2>Hello World!</h2>
<%--The path submitted here needs to find the path to the project--%>
<%--pageContext.request.ContextPath():Represents the current project path--%>
<form action="${pageContext.request.contextPath}/login" method="get">
    user name:<input type="text" name="username"><br>
    password:<input type="password" name="password"><br>
    <input type="submit">
</form>

</body>
</html>

java handler

package xiaoqi.Servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class requesttest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("Enter this request");
        //After successfully entering the request, process the request
        String username = req.getParameter("username");
        String passwrod = req.getParameter("password");
        System.out.println(username + ":" + passwrod);
        //Redirect
        resp.sendRedirect("/re/success.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Success page

<%--
  Created by IntelliJ IDEA.
  User: 77
  Date: 2021/12/9
  Time: 15:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>Successs</h1>
</body>
</html>

6.7 HttpServletReuqest

HttpServletReuqest: represents the request of the client. The user accesses the server through the HTTP protocol. All the information in the HTTP request will be encapsulated in HttpServletReuqest. All the information of the client will be obtained through the method of HttpServletReuqest.

1. Get the parameters passed by the front end

2. Request forwarding

index user login page

<%--
  Created by IntelliJ IDEA.
  User: 77
  Date: 2021/12/9
  Time: 16:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login</title>
</head>
<body>
<h1>Sign in</h1>
<div style="text-align: center">
    <%--with post Submit the form and submit it to our login request--%>
    <form action="${pageContext.request.contextPath}/login" method="post">
        user name:<input type="text" name="username"><br>
        password:<input type="password" name="password"><br>
        Hobbies:
        <input type="checkbox" name="hobbies" value="1">1
        <input type="checkbox" name="hobbies" value="2">2
        <input type="checkbox" name="hobbies" value="3">3
        <input type="checkbox" name="hobbies" value="4">4
        <br>
        <input type="submit">
    </form>
</div>
</body>
</html>
package xiaoqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println("-----------------");
        System.out.println(username + ":"  + password);
        System.out.println(Arrays.toString(hobbies));
        System.out.println("-----------------");
        //Forward by request
        resp.setCharacterEncoding("utf-8");
        //Get the path under this project
        /// here represents the current web application
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }
}
<%--
  Created by IntelliJ IDEA.
  User: 77
  Date: 2021/12/9
  Time: 16:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>success</h1>
</body>
</html>

7. Cookie Session

Cookie determines the user identity by recording information on the client, and Session determines the user identity by recording information on the server.

What is a Cookie?

Cookie technology is the solution of the client. Cookie is the special information sent by the server to the client, which is stored in the client in the form of text file, and then the client will bring these special information every time it sends a request to the server. Let's be more specific: when a user uses a browser to visit a website that supports Cookies, the user will provide personal information including the user name and submit it to the server; Then, the server will send back these personal information while returning the corresponding hypertext to the client, Of course, these information are not stored in the HTTP Response Body, but in the HTTP Response Header. When the client browser receives the response from the server, the browser will store these information in a unified location. For the Windows operating system, we can start from: [system disk]: \ Documents and Settings Find the stored cookie in the [user name] \ Cookies directory; Since then, when the client sends a request to the server, it will send the corresponding cookie back to the server again. And this time, The cookie information is stored in the HTTP Request Header (Request Header). With the implementation of cookie technology, after receiving the request from the client browser, the server can get the client specific information by analyzing the cookie stored in the Request Header, so as to dynamically generate the content corresponding to the client. Generally, we can see "please remember me" in the login interface of many websites If you check this option and log in again, you don't need to repeat and cumbersome login actions when you visit the website next time, and this function is realized through Cookies.

7.1 conversation

Session: users open a browser, open many hyperlinks, access multiple web resources, and close the browser. This process is called session

Stateful session:

A website, how to prove you've been here?

Client server

  1. The server gives a cookie to the client, and the client can bring the cookie when it visits the client next time

  2. The server registers that you have been here. Next time you come, I will match you

7.2 two techniques for saving sessions

cookie

  • Client Technology (response, request)

session

  • Server technology. Using this technology, we can save the user's session information. We can put the data or information into the session.

Common example: after the website is logged in, you don't have to log in next time.

7.3 Cookie

  1. Get cookie information from the request

  2. Server response client

    Cookie[] cookies = req.getCookies();//Get cookie
    cookie.getName();//Key to get cookie
    new Cookie("lastTime",System.currentTimeMillis()+"");Create a cookie
    cookie.setMaxAge(24*60*60);//Set the validity period of the cookie
    resp.addCookie(cookie);//Respond to a cookie to the client
    
package xaioqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

//Protect the last access time of the user
public class CookieDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //The server tells you the time of your arrival, encapsulates this time as a new one, and you will be known when you come next time
        //Solve Chinese garbled code
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");

        PrintWriter out = resp.getWriter();
        //The Cookie server obtains the Cookie from the client
        //The client sends a request to the server
        Cookie[] cookies = req.getCookies();//An array is returned here, indicating that there may be multiple cookie s
        //Determine whether the cookie exists in the client
        if (cookies!=null){
            //If present
            out.write("Last visited:");
            for (int i =0 ;i<cookies.length;i++) {
                Cookie cookie = cookies[i];
                //Get the name of the cookie
                if(cookie.getName().equals("lastTime")){//Find the key value pair of lastTime to find the time
                    //Gets the value in the cookie
                    long l = Long.parseLong(cookie.getValue());//Change a string into a long integer
                    //Then convert a long integer to a Date
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.write("This is my first visit to the website");
        }
        //This code is always executed, and the time needs to be updated for both the first and second access
        //The server responds with a cookie to the client
        Cookie cookie = new Cookie("lastTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(24*60*60);//Set the validity of the cookie to one day
        resp.addCookie(cookie);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Local cookie s: usually placed in the user directory.

Does a website cookie exist online?

  • A cookie can only hold one piece of information
  • A web site can send multiple cookies to the browser and store up to 20 cookies
  • 300 cookie s is the upper limit of the browser
  • cookie size limit: 4KB

Delete cookie:

  • If the validity period is not set, close the browser and it will automatically become invalid;
  • Set the validity time to 0;
package xaioqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class CookieDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Create a cookie with the same name as the one you want to delete
        Cookie cookie = new Cookie("lastTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(0);//Let cookie s expire immediately
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Transmit text - decode and encode in case of garbled code

URLEncoder.encode("Xiao Qi","utf-8")//code
URLDecoder.decode(cookie.getValue(),"UTF-8")//decode
package xaioqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class CookieDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-16");
        resp.setCharacterEncoding("utf-16");

        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies(); if (cookies!=null){
            //If present
            out.write("The name is:");
            for (int i =0 ;i<cookies.length;i++) {
                Cookie cookie = cookies[i];
                if(cookie.getName().equals("name")){
                   // URLDecoder.decode(cookie.getValue(),"UTF-8");
                    // decode
                    out.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                }
            }
        }else {
            out.write("nothing");
        }

        Cookie cookie = new Cookie("name", URLEncoder.encode("Xiao Qi","utf-8"));//code
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

7.4 Session - key points

Session is another mechanism for recording the status of customers. The difference is that cookies are saved in the client browser, while session is saved on the server. When the client browser accesses the server, the server records the client information on the server in some form. This is session. When the client browser accesses again, it only needs to find the status of the customer from the session.

If the Cookie mechanism determines the customer's identity by checking the "pass" on the customer, the session mechanism confirms the customer's identity by checking the "customer details" on the server. Session is equivalent to a customer file created by the program on the server. When a customer visits, he only needs to query the customer file table.

What is Session:

  • The server will create a Session object for each user

  • A Session monopolizes a browser. As long as the browser is not related, the Session exists; A browser corresponds to a Session object

  • After the user logs in, the whole website can be accessed! - > Save user information or shopping cart information

The difference between Session and Cookie:

  • Cookie is to write the user's data to the user's browser. The browser saves it, and the client can save multiple
  • Session writes the user's data to the user's exclusive session and the server saves it (saves important information and reduces the waste of server resources)
  • The Session object is created by the server

Tell me the difference between Cookie and Session?

  • Both cookie and Session are Session technologies. Cookie runs on the client side and Session runs on the server side.
  • The size of cookies is limited and the number of cookies stored by the browser is also limited. There is no size limit for Session, which is related to the memory size of the server.
  • Cookies have security risks. You can attack them after you find your cookies through interception or local files.
  • Sessions are saved on the server side and will not disappear until they exist for a period of time. If there are too many sessions, it will increase the pressure on the server.

session principle:

  • session is saved on the server side. Theoretically, there is no limit, as long as your memory is large enough
  • When the browser accesses the server for the first time, it will create a session object and return a value of JSESSIONID=ID,
    Create a Cookie object with key as JSSIONID and value as ID. write the Cookie back to the browser
  • When the browser accesses the server for the second time, it carries the value of Cookie information JSESSIONID=ID. if the session of the JSESSIONID has been destroyed,
    Then a new session will be created again, and a new JSESSIONID will be returned to the browser through a Cookie
  • For a web project, a browser shares a session. Even if two web projects are deployed on the same server, the sessions for the two projects are different
    For example, you have deployed two web projects on tomcat at the same time, namely web1 and web2. When you access web1 on a browser at the same time, the session created is A1, and the session created when you access web2 is A2.
    The session you use when accessing web1 multiple times is still A1, and the session you use when accessing web2 multiple times is A2
  • Session is implemented based on Cookie technology. After restarting the browser and accessing the original connection again, a new session will still be created,
    Because the Cookie will disappear after closing the browser, but the Session of the original server is still there. It will be automatically destroyed only when it is destroyed
  • If cookies are disabled on the browser side, a new Session will be created for each visit, but we can rewrite the URL through the server-side program. If there are many pages and many connections, it will increase unnecessary workload.

Test the creation of a Session on the web page

package xaioqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve the problem of garbled code
        req.setCharacterEncoding("UTF-16");
        resp.setCharacterEncoding("UTF-16");
        resp.setContentType("text/html;charset=uft-16");//Format document
        //Get Session
        HttpSession session = req.getSession();//Get Session from request
        //Save something in the Session
        session.setAttribute("name","xiaoqi");
        //Get the session id
        String id = session.getId();
        //Judge whether it is a new session and whether the session is newly created
        if (session.isNew()){
            resp.getWriter().write("Session Created successfully, ID:" + id);
        }else {
            resp.getWriter().write("Session It already exists"+id);
        }

        /*Session What did you send when you created it
        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        resp.addCookie(cookie);*/


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Get this Session

package xaioqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Solve the problem of garbled code
        req.setCharacterEncoding("UTF-16");
        resp.setCharacterEncoding("UTF-16");
        resp.setContentType("text/html;charset=uft-16");//Format document
        //Get Session
        HttpSession session = req.getSession();

        String name = (String)session.getAttribute("name");
        System.out.println(name);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Manually unregister session:

package xaioqi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Unregister session
        HttpSession session = req.getSession();
        session.removeAttribute("name");//Remove name
        session.invalidate();;//Logout, manually logout session
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Set the validity period of the session, and the session will expire automatically

 <!--set up session Default effective time-->
    <session-config>
        <!--1 Minutes later Session Automatic failure-->
        <session-timeout>1</session-timeout>
    </session-config>

**Usage scenario: * * save user login information; Shopping cart information; The data that is often used in the whole project is saved in the Session.

8. JSP

8.1 what is JSP

Java Server Pages - Java server-side pages, like servlets, are used to develop dynamic Web pages

Biggest features:

  • Writing JSP is like writing HTML
  • Differences between and HTML:
    • Only static data is provided to users
    • JSP pages can embed Java code to provide users with dynamic data

8.2 principle

  • Work inside the server

    There is a work directory in Tomcat

    If Tomcat is used in the IDEA, a work directory will be generated in Tomcat of the IDEA

The discovery page was converted into a java program

The browser sends a request to the server. No matter what resources it accesses, it is actually accessing the Servlet!

JSP will eventually be converted into a Java class - JSP is essentially a Servlet

//initialization 
public void _jspInit() {
  }
//Destroy
  public void _jspDestroy() {
  }
//JSPService
  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
  1. Judgment request

  2. Built in some objects

        final javax.servlet.jsp.PageContext pageContext;//context
        javax.servlet.http.HttpSession session = null;//Session
        final javax.servlet.ServletContext application;//application
        final javax.servlet.ServletConfig config;//config
        javax.servlet.jsp.JspWriter out = null;//out
        final java.lang.Object page = this;//Current page
        javax.servlet.jsp.JspWriter _jspx_out = null;
        javax.servlet.jsp.PageContext _jspx_page_context = null;java
        final javax.servlet.http.HttpServletRequest request //request
        final javax.servlet.http.HttpServletResponse        //response
    
  3. Code before output page

 response.setContentType("text/html");//Set the page setup for the response
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
  1. The above objects can be used directly in JSP pages

Create a hello jsp

<%--
  Created by IntelliJ IDEA.
  User: 77
  Date: 2021/12/10
  Time: 15:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
hello
</body>
</html>

An error occurred in the folder

Implementation process:

In a JSP page:

  • Java code will be output intact;
  • If it is HTML code, it will be converted to
out.write("<html>\n");

8.3 basic syntax of JSP

As an application of Java technology, JSP has some of its own extended syntax (just understand it)

JSP expression

<%--JSP expression
 Function: used to output the program to the client
<%= Variable or expression %>
--%>

<%= new java.util.Date()%>

JSP script fragment

  <%--JSP Script fragment--%>
  <%
    int sum = 0;
    for (int i =0; i< 100 ;i++)
      sum +=i;
    out.println("<h1>sum" + sum + "<h1>");
  %>

Re implementation of script fragments

<%
 int x= 10;
 out.println(x);
%>
<p>This is a jsp text</p>
<%
  out.println(x);
%>
<hr>

<%--Embedding in code HTML language--%>
<%
for (int i =0;i< 5;i++){
%>
<h1>hello world</h1>
<%
  }
%>

JSP declaration

<%!
  static {
    System.out.println("Loding");
  }
  private int globalVar = 0;
  public void aVoid(){
    System.out.println("get into avoid");
  }
%>

It will be compiled into the Java class generated by JSP, and the rest will be put into the method_ jspService()

In JSP, embed Java code!

<%%>
<%=%>
<%!%>

<%--notes--%>
12345

JSP comments will not be displayed on the client, and HTML will!

8.4 JSP instructions

<%@page args.... %>
<%@include file=""%>

<%--@include The two pages will be combined into one--%>
<%@include file="common/header.jsp"%>
<h1>Web page subject</h1>
<%@include file="common/footer.jsp"%>
<hr>

<%--jSP label
    jsp:include: Splicing pages, the essence is still three
    --%>
<jsp:include page="/common/header.jsp"/>
<h1>Web page subject</h1>
<jsp:include page="/common/footer.jsp"/>

Configuration error page

<%--Customize 500 error interface--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page %>
<html>
<head>
    <title>Customize 500 interface</title>
</head>
<body>
    
<img src="image/img.png" alt="500">
</body>
</html>
<%--
  Created by IntelliJ IDEA.
  User: 77
  Date: 2021/12/10
  Time: 16:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--Custom error page--%>
<%--<%@ page errorPage="error/500.jsp" %>--%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    int x =1/0;
%>
</body>
</html>

Configuration error page

<error-page>
    <error-code>404</error-code>
    <location>/error/404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/error/500.jsp</location>
</error-page>

8.5 9 built in objects

  • PageContext store
  • Request to store things
  • Response
  • Session storage
  • Application [servvetcontext] save things
  • config [SerlvetConfig]
  • out
  • page, don't understand
  • exception
pageContext.setAttribute("name1","Qinjiang 1"); //The saved data is only valid in one page
request.setAttribute("name2","Qinjiang 2"); //The saved data is only valid in one request, and the request forwarding will carry this data
session.setAttribute("name3","Qinjiang 3"); //The saved data is valid only in one session, from opening the browser to closing the browser
application.setAttribute("name4","Qinjiang 4");  //The saved data is only valid in the server, from opening the server to closing the server
  • Request: the client sends a request to the server. The generated data is useless after the user reads it. For example, news is useless after the user reads it!

  • session: the client sends a request to the server, and the generated data is still useful when the user runs out, such as a shopping cart;

  • application: when the client sends a request to the server, the generated data is used up by one user and may be used by other users, such as chat data;

  • //Take it out from pageContext, and we search for it
    //From bottom to top (SCOPE): Page - > request - > session - > Application
    //Parent delegation mechanism of JVM
    
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    /*pageContext.setAttribute("test","test",PageContext.APPLICATION_SCOPE);
    pageContext.setAttribute("test","test",PageContext.REQUEST_SCOPE);
    pageContext.setAttribute("test","test",PageContext.SESSION_SCOPE);
    pageContext.setAttribute("test","test",PageContext.PAGE_SCOPE);

   PageContext.PAGE_SCOPE Control scope
*/
    pageContext.setAttribute("name1","pageContext_name01");
    session.setAttribute("name2","session_name02");
    request.setAttribute("name3","request_name03");
    application.setAttribute("name4","application_name04");
%>
<html>
<head>
    <title>jspDemo01</title>
</head>
<body>
<%
    String name1 = (String) pageContext.findAttribute("name1");
    String name2 = (String) pageContext.findAttribute("name1");
    String name3 = (String) pageContext.findAttribute("name1");
    String name4 = (String) pageContext.findAttribute("name1");
    String name5 = (String) pageContext.findAttribute("name1");
%>
<h1>${name1}</h1>
<h1>${name2}</h1>
<h1>${name3}</h1>
<h1>${name4}</h1>
<h1>${name5}</h1>
</body>
</html>

First visit Demo01

Second visit Demo02

Page request forwarding;

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    pageContext.forward("/pageContextDemo01.jsp");//Page front end forwarding
    /*
     * Background forwarding
     * request.getRequestDispatcher("/pageContextDemo01.jsp").forward(request,response);
     * */
%>

</body>
</html>

8.6 JSP tag, JSTL tag, EL expression

EL expression: ${}

  • get data
  • Perform operations
  • Get common objects for web development
<!-- JSTL Dependency of expression -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!-- standard Tag library -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

JSP tag

<%--jsp:include--%>

<%--
http://localhost:8080/jsptag.jsp?name=kuangshen&age=12
--%>

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="kuangshen"></jsp:param>
    <jsp:param name="age" value="12"></jsp:param>
</jsp:forward>

JSTL expression

The use of JSTL tag library is to make up for the shortage of HTML tags; It can customize many tags for us to use. The function of tags is the same as that of Java code!

Format label

SQL tag

XML tag

Core label (master part)

Steps for using JSTL tag library

  • Introduce the corresponding taglib
  • Use one of the methods
  • In Tomcat, you also need to introduce the JSTL package, otherwise an error will be reported: JSTL parsing error

c: if

<head>
    <title>Title</title>
</head>
<body>


<h4>if test</h4>

<hr>

<form action="coreif.jsp" method="get">
    <%--
    EL Expression to get the data in the form
    ${param.Parameter name}
    --%>
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="Sign in">
</form>

<%--Judge that if the submitted user name is administrator, the login is successful--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="Welcome to the administrator!"/>
</c:if>

<%--Self closing label--%>
<c:out value="${isAdmin}"/>

</body>
12345678910111213141516171819202122232425262728

c:choose c:when

<body>

<%--Define a variable score,The value is 85--%>
<c:set var="score" value="55"/>

<c:choose>
    <c:when test="${score>=90}">
        Your grades are excellent
    </c:when>
    <c:when test="${score>=80}">
        Your grades are average
    </c:when>
    <c:when test="${score>=70}">
        Your grades are good
    </c:when>
    <c:when test="${score<=60}">
        Your grade is a failure
    </c:when>
</c:choose>

</body>
123456789101112131415161718192021

c:forEach

<%

    ArrayList<String> people = new ArrayList<>();
    people.add(0,"Zhang San");
    people.add(1,"Li Si");
    people.add(2,"Wang Wu");
    people.add(3,"Zhao Liu");
    people.add(4,"Tian Liu");
    request.setAttribute("list",people);
%>


<%--
var , Variables traversed each time
items, Object to traverse
begin,   Where to start
end,     Where to go?
step,   step
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/> <br>
</c:forEach>

<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
    <c:out value="${people}"/> <br>
</c:forEach>

1234567891011121314151617181920212223242526272829

9. JavaBean

Entity class

JavaBean s have specific ways to write:

  • Must have a parameterless construct
  • Property must be privatized
  • There must be a corresponding get/set method;

It is generally used to map ORM with database fields;

ORM: Object Relational Mapping

  • Table - > class
  • Fields – > Properties
  • Line record - > object

people table

idnameageaddress
1Qinjiang 13Xi'an
2Qinjiang 218Xi'an
3Qinjiang 3100Xi'an
class People{
    private int id;
    private String name;
    private int id;
    private String address;
}

class A{
    new People(1,"Qinjiang 1",3,"Xi'an");
    new People(2,"Qinjiang 2",3,"Xi'an");
    new People(3,"Qinjiang 3",3,"Xi'an");
}
123456789101112
  • filter
  • File upload
  • Mail sending
  • jdbc review: how to use jdbc, jdbc crud, jdbc transaction

10. MVC three-tier architecture

What is MVC: Model view Controller

10.1 structure of earlier years

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-tc3sisww-1639619842295) (C: / users / 77 / appdata / roaming / typora / typora user images / image-20211211151557959. PNG)]

Users directly access the control layer, and the control layer can directly operate the database

Users directly access the control layer, and the control layer can directly operate the database;

servlet--CRUD-->database
 Disadvantages: the program is very bloated, which is not conducive to maintenance  
servlet In the code: processing request, response, view jump, processing JDBC,Processing business code and processing logic code

Architecture: nothing can't be solved by adding one layer!
Program call
↑
JDBC ((implement this interface)
↑
Mysql Oracle SqlServer ....((different manufacturers)

10.2 MVC three-tier architecture

Model

  • Business processing: business logic (Service)
  • Data persistence layer: CRUD (Dao)

View

  • Display data
  • Provide link to initiate Servlet request (a, form, img...)

Controller (Servlet)

  • Receive user's request: (req: request parameters, Session information...)

  • Give it to the business layer to process the corresponding code

  • Control view jump

    Sign in--->Receive user login request--->Process the user's request (get the user login parameters, username,password)---->Give it to the business layer to handle the login business (judge whether the user name and password are correct: Transaction)--->Dao Check whether the user name and password are correct-->database
    

11. Filter (key)

For example, Shiro security framework technology is implemented with Filter

Filter: filter, used to filter website data;

  • Deal with Chinese garbled code
  • Login authentication

Filter development steps:

  1. Guide Package

  2. Write filter

    1. Guide the package correctly (note)

    2. Implement filter interface

      package xiaoqi.filter;
      
      import javax.servlet.*;
      import java.io.IOException;
      
      public class CharacterEncondingFilter implements Filter {
          @Override
          //Initialization: when the web server starts, it starts to initialize, waiting for the filter object to appear at any time
          public void init(FilterConfig filterConfig) throws ServletException {
              System.out.println("initing");
          }
      
          @Override
          //Chain chain
             /*
                1. All code in the filter will be executed when filtering specific requests
                2. The filter must continue to pass - then forward the request
                    chain.doFilter(request,response);
                 */
          public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
              servletRequest.setCharacterEncoding("utf-8");
              servletResponse.setCharacterEncoding("utf-8");
              servletResponse.setContentType("text/html;charset=UTF-8");
      
              System.out.println("Before execution..");
              filterChain.doFilter(servletRequest,servletResponse);//Let our request continue. If we don't write the program, it will be intercepted and stopped here
              System.out.println("After execution..");
          }
      
          @Override
          //Destroy: when the web server is shut down, the filter is destroyed
          public void destroy() {
              System.out.println("destroy");
          }
      }
      
    3. On the web Configuring filters in XML

        <filter>
              <filter-name>encoding</filter-name>
              <filter-class>xiaoqi.filter.CharacterEncondingFilter</filter-class>
          </filter>
          <filter-mapping>
              <filter-name>encoding</filter-name>
              <!--as long as/servlet Any request from will pass through this filter-->
              <url-pattern>/servlet/*</url-pattern>
          </filter-mapping>
      
      

No filter

Through the filter

12. Listener

Implement a listener interface; (there are n kinds of listeners)

  1. Write a listener

    Implement the listener interface

Implement a listener interface; (N kinds)

  1. Write a listener

    Implement the listener interface

    //Count the number of people online: session
    public class OnlineCountListener implements HttpSessionListener {
    
        //Create session monitor: watch your every move
        //This event will be triggered once the Session is created!
        public void sessionCreated(HttpSessionEvent se) {
            ServletContext ctx = se.getSession().getServletContext();
    
            System.out.println(se.getSession().getId());
    
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(1);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count+1);
            }
    
            ctx.setAttribute("OnlineCount",onlineCount);
    
        }
    
        //Destroy session listening
        //This event will be triggered once the Session is destroyed!
        public void sessionDestroyed(HttpSessionEvent se) {
            ServletContext ctx = se.getSession().getServletContext();
    
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(0);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count-1);
            }
    
            ctx.setAttribute("OnlineCount",onlineCount);
    
        }
    
    
        /*
        Session Destruction:
        1. Manually destroy getsession() invalidate();
        2. Automatic destruction
         */
    }
    
  2. web. Register listeners in XML

    <!--Register listener-->
    <listener>
        <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
    </listener>
    
  3. It depends on whether it is used!

13 common applications of filters and listeners

Listener: often used in GUI programming;

package xiaoqi.listener;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("Happy Mid-autumn Day ");  //Create a new form
        Panel panel = new Panel(null); //panel
        frame.setLayout(null); //Set the layout of the form

        frame.setBounds(300,300,500,500);
        frame.setBackground(new Color(0,0,255)); //Set background color

        panel.setBounds(50,50,300,300);
        panel.setBackground(new Color(0,255,0)); //Set background color

        frame.add(panel);

        frame.setVisible(true);

        //Listen for events. Listen for closing events
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("open");
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                super.windowDeiconified(e);
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("closing");
                System.exit(0);
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("closed");
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("activated");
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                System.out.println("disactavited");
            }
        });


    }
}

Users can enter the home page only after logging in! Users cannot enter the home page after logging off!

  1. After the user logs in, put the user's data into Sison
  2. When entering the home page, judge whether the user has logged in; Requirements: implemented in the filter!

Users can enter the home page only after logging in! Users cannot enter the home page after logging off!

  1. After the user logs in, put the user's data into Sison

  2. When entering the home page, judge whether the user has logged in; Requirements: implemented in the filter!

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    
    if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
        response.sendRedirect("/error.jsp");
    }
    
    chain.doFilter(request,response);
    12345678
    

code implementation
Login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 742356
  Date: 2020/5/18
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
<form action="/servlet/login" method="post">
    full name:<input type="text" name="username"><br />
    <input type="submit" name="Submit">
</form>

</body>
</html>

123456789101112131415161718192021

success.jsp

<%@ page import="com.ph.util.Constant" %><%--
  Created by IntelliJ IDEA.
  User: 742356
  Date: 2020/5/18
  Time: 12:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>homepage</title>
</head>
<body>

<%
    /*It is not recommended to write filter code on jsp pages*/
   /* Object userSession = request.getSession().getAttribute(Constant.USER_SESSION);
    if(userSession == null){
        response.sendRedirect("/Login.jsp");
    }*/
%>

<h1>homepage</h1>
<a href="/servlet/logout">cancellation</a>

</body>
</html>

12345678910111213141516171819202122232425262728

error.jsp

<%--
  Created by IntelliJ IDEA.
  User: 742356
  Date: 2020/5/18
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
User name or request error
<a href="Login.jsp">Return to the login interface</a>
</body>
</html>

123456789101112131415161718

LoginServlet

package com.ph.servlet;

import com.ph.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        //Get the parameters of the front-end request
        String username = req.getParameter("username");
        if("admin".equals(username)){//Login succeeded
            req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else{//Login failed
            resp.sendRedirect("/error.jsp");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

1234567891011121314151617181920212223242526272829303132

LogoutServlet

package com.ph.servlet;

import com.ph.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
        if(user_session !=null){
            req.getSession().removeAttribute(Constant.USER_SESSION);
            resp.sendRedirect("/Login.jsp");
        }else{
            resp.sendRedirect("/Login.jsp");
            //Note: if "\" is not added before the path during redirection, the path will be loaded after the last mandatory
            /*For example:
            *       The path of the login request is localhost:8081/servlet/login
            *       After successful login and redirection, the path is localhost: 8081 / servlet / success jsp
            *       Bulletin 404
            *
            *
            * */
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

1234567891011121314151617181920212223242526272829303132333435363738

//Note: if "" is not added in front of the path during redirection, the path will be loaded after the last mandatory
/*For example:
*The path of the login request is localhost:8081/servlet/login
*After successful login and redirection, the path is localhost: 8081 / servlet / success jsp
*Bulletin 404
*
*
* */

Filter
SysFilter.java

package com.ph.filter;

import com.ph.util.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if(request.getSession().getAttribute(Constant.USER_SESSION)==null){
            response.sendRedirect("/error.jsp");
        }

        filterChain.doFilter(request,response);
    }

    public void destroy() {

    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.ph.servlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.ph.servlet.LogoutServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/servlet/logout</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.ph.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/sys/*</url-pattern>
    </filter-mapping>
</web-app>

14. JDBC

What is JDBC: Java connection database!

jar package support is required:

  • java.sql
  • javax.sql
  • MySQL connector Java... Connection driver (must be imported)

Establishment of experimental environment

CREATE TABLE users(
    id INT PRIMARY KEY,
    `name` VARCHAR(40),
    `password` VARCHAR(40),
    email VARCHAR(60),
    birthday DATE
);

INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'Zhang San','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'Li Si','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'Wang Wu','123456','ww@qq.com','2000-01-01');


SELECT	* FROM users;

Import database dependencies

<!--mysql Drive of-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

Connect to the database in IDEA:

JDBC fixing steps:

  1. Load driver
  2. Connect to the database, representing the database
  3. Object statement to send SQL to database: CRUD
  4. Write SQL (different SQL according to business)
  5. Execute SQL
  6. Close connection
public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //configuration information
        //Useunicode = true & characterencoding = UTF-8 to solve Chinese garbled code
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1. Load drive
        Class.forName("com.mysql.jdbc.Driver");
        //2. Connect to the database and represent the database
        Connection connection = DriverManager.getConnection(url, username, password);

        //3. Send SQL object statement to the database, Preparedstatement: CRUD
        Statement statement = connection.createStatement();

        //4. Write SQL
        String sql = "select * from users";

        //5. Execute SQL query and return a ResultSet: result set
        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()){
            System.out.println("id="+rs.getObject("id"));
            System.out.println("name="+rs.getObject("name"));
            System.out.println("password="+rs.getObject("password"));
            System.out.println("email="+rs.getObject("email"));
            System.out.println("birthday="+rs.getObject("birthday"));
        }

        //6. Close the connection and release resources (be sure to do it) first on and then off
        rs.close();
        statement.close();
        connection.close();
    }
}

Precompiled SQL

public class TestJDBC2 {
    public static void main(String[] args) throws Exception {
        //configuration information
        //Useunicode = true & characterencoding = UTF-8 to solve Chinese garbled code
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1. Load drive
        Class.forName("com.mysql.jdbc.Driver");
        //2. Connect to the database and represent the database
        Connection connection = DriverManager.getConnection(url, username, password);

        //3. Write SQL
        String sql = "insert into  users(id, name, password, email, birthday) values (?,?,?,?,?);";

        //4. Precompiling
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1,2);//For the first placeholder? The value of is assigned to 1;
        preparedStatement.setString(2,"Madness theory Java");//For the second placeholder? The value of is assigned to crazy God Theory Java;
        preparedStatement.setString(3,"123456");//For the third placeholder? The value of is assigned as 123456;
        preparedStatement.setString(4,"24736743@qq.com");//For the fourth placeholder? The value of is assigned to 1;
        preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//For the fifth placeholder? The value of is assigned as new date (new Java. Util. Date() getTime());

        //5. Execute SQL
        int i = preparedStatement.executeUpdate();

        if (i>0){
            System.out.println("Insert successful@");
        }

        //6. Close the connection and release resources (be sure to do it) first on and then off
        preparedStatement.close();
        connection.close();
    }
}

affair

Either all succeed or all fail!

ACID principle: ensure data security.

Open transaction
 Transaction commit  commit()
Transaction rollback  rollback()
Close transaction

transfer accounts:
A:1000
B:1000
    
A(900)   --100-->   B(1100) 
12345678910

Junit unit test

rely on

<!--unit testing -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
123456

Simple use

@The Test annotation is only valid for methods. As long as the annotated method is added, it can be run directly!

@Test
public void test(){
    System.out.println("Hello");
}
1234

Failure is red:

Build an environment

CREATE TABLE account(
   id INT PRIMARY KEY AUTO_INCREMENT,
   `name` VARCHAR(40),
   money FLOAT
);

INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
123456789
    @Test
    public void test() {
        //configuration information
        //Useunicode = true & characterencoding = UTF-8 to solve Chinese garbled code
        String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        Connection connection = null;

        //1. Load drive
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //2. Connect to the database and represent the database
             connection = DriverManager.getConnection(url, username, password);

            //3. Notify the database to start the transaction and false to start it
            connection.setAutoCommit(false);

            String sql = "update account set money = money-100 where name = 'A'";
            connection.prepareStatement(sql).executeUpdate();

            //Manufacturing error
            //int i = 1/0;

            String sql2 = "update account set money = money+100 where name = 'B'";
            connection.prepareStatement(sql2).executeUpdate();

            connection.commit();//If the above two SQL statements are executed successfully, commit the transaction!
            System.out.println("success");
        } catch (Exception e) {
            try {
                //If an exception occurs, notify the database to roll back the transaction
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

BaseDao.java

package com.gree.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String username;
    private static String password;
    private static String url;


    static{
        Properties properties = new Properties();
        String configFile = "db.properties";
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(configFile);
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");

    }
    /*Get database connection*/
    public static Connection getConnection() throws SQLException {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }
    /*
    * Query general class
    * */

    public static ResultSet executeQ(Connection conn , PreparedStatement pstm,ResultSet rs,String sql,Object[] objects) throws SQLException {
        pstm = conn.prepareStatement(sql);
        for(int i = 0;i<objects.length;i++){
            pstm.setObject(i+1,objects[i]);
        }
        rs = pstm.executeQuery();
        return rs;
    }

    /*
    * Operation data general class
    *
    * */
    public static int execute(Connection conn,PreparedStatement pstm,String sql,Object[] objects) throws SQLException {
        int execute = 0;
        pstm = conn.prepareStatement(sql);
        for(int i = 0;i<objects.length;i++){
            pstm.setObject(i+1,objects[i]);
        }
        execute = pstm.executeUpdate();
        return execute;

    }

    /*
    * close resource
    *
    * */
    public static boolean closeResource(Connection conn,PreparedStatement pstm,ResultSet rs){
        boolean flag = true;
        if(rs!=null){
            try {
                rs.close();
                //gc recovery
                rs=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if(pstm!=null){
            try {
                pstm.close();
                //gc recovery
                pstm=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if(conn!=null){
            try {
                conn.close();
                //gc recovery
                conn=null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }

        return flag;
    }
}

Project: SMSBS

How to build the project?

1. Build a template maven webapp project

2. Configure Tomcat

3. Can the test project run

4. Import the dependent jar package:

  1. Servlet implements servlet interface

  2. jsp jsp tag

  3. MySQL connector Java database connection

  4. jstl jsp tag library

  5. The package that the standard jsp tag library depends on

    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
      </dependency>
      <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
      </dependency>
      <dependency>
        <!--jsp Dependency of expression-->
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl-api</artifactId>
        <version>1.2</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/taglibs/standard -->
      <dependency>
        <!--Tag library-->
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
      </dependency>
      <!-- Connect to database-->
      <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
      </dependency>
      <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <version>RELEASE</version>
        <scope>compile</scope>
      </dependency>
    
    </dependencies>
    

5. Build project structure

6. Write entity class

ORM mapping: table ----- > class

7. Preparation of basic public headings

  1. Database configuration file

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
    username=root
    password=123456
    
  2. Tool class

    package xiaoqi.dao;
    
    import java.io.InputStream;
    import java.sql.*;
    import java.util.Properties;
    
    //Public class for operating database
    public class BaseDao {
        private static String driver;
        private static String url;
        private static String username;
        private static String password;
    
        //Static code fast
        static {
            Properties properties = new Properties();
            //Turn resources into streams
            InputStream is =
                    BaseDao.class.getClassLoader().getResourceAsStream("db.properties");//Read the corresponding resources through the class loader
            try {
                properties.load(is);//Load profile
            } catch (Exception e) {
                e.printStackTrace();
            }
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
    
        }
        //Get connection to database
        public static Connection getConnection(){
            Connection connection = null;
            try {
                Class.forName(driver);//Register driver
                connection = DriverManager.getConnection(url, username, password);//Establish connection
            } catch (Exception e) {
                e.printStackTrace();
            }
            return connection;
        }
        //Write query public class
    
        /**
         * query
         * @param connection  connect
         * @param sql      sql sentence
         * @param params   Database parameters
         * @return
         * @throws SQLException
         */
        public static ResultSet execute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException {
            //Get connection
            preparedStatement = connection.prepareStatement(sql);//sql statement
            for (int i =0; i<params.length;i++){
                preparedStatement.setObject(i+1,params[i]);//Placeholders start with 1, so you need + 1
            }
            //Precompiled sql does not need to be executed later
            resultSet = preparedStatement.executeQuery();//Execute sql statement
            return resultSet;
    
    
        }
    
        /**
         * Addition, deletion and modification
         * @param connection
         * @param sql
         * @param params
         * @param preparedStatement
         * @return Number of returned results
         * @throws SQLException
         */
        public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
            //Get connection
            preparedStatement = connection.prepareStatement(sql);//sql statement
            for (int i =0; i<params.length;i++){
                preparedStatement.setObject(i+1,params[i]);//Placeholders start with 1, so you need + 1
            }
            int update = preparedStatement.executeUpdate();
            return update;
        }
    
        /**
         * close resource
         * @param connection
         * @param preparedStatement
         * @param resultSet
         * @return
         */
        public static boolean closeResources(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
            boolean flag = true;
            if (resultSet!= null){
                try {
                    resultSet.close();
                    //GC recovery
                    resultSet = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                    flag = false;//When the shutdown is not successful, it returns flash
                }
            }
            if (connection != null){
                try {
                    connection.close();
                    //GC recovery
                    connection = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                    flag = false;//When the shutdown is not successful, it returns flash
                }
            }
            if (preparedStatement!= null){
                try {
                    preparedStatement.close();
                    //GC recovery
                    preparedStatement = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                    flag = false;//When the shutdown is not successful, it returns flash
                }
            }
            return flag;
        }
    }
    
  3. Write character encoding filter

    public class CharacterEncodingFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            servletRequest.setCharacterEncoding("utf-8");
            servletResponse.setCharacterEncoding("utf-8");
            servletResponse.setContentType("text/html;charset=UTF-8");
    
            //Let our request continue. If we don't write, the program will be intercepted and stopped here!
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    

8. Import static resources

Realization of login function

1. Write front page

2. Set the welcome page

<!--Set up welcome page-->
<welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
</welcome-file-list>

Problem loading page:

3. Write the Dao layer user login interface

package xiaoqi.dao.user;

import xiaoqi.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

public interface UserDao {
    //Get logged in users
    User getLoginUser(Connection connection,String userCode) throws SQLException;

}

4. Write the implementation of Dao layer user login

package xiaoqi.dao.user;

import xiaoqi.dao.BaseDao;
import xiaoqi.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao{
    @Override
    public User getLoginUser(Connection connection, String userCode) throws SQLException{
        //Prepare three objects
        PreparedStatement preparedStatement = null;//Prevent sql injection precompiling
        ResultSet rs = null; //Return result set
        User user = null;
        //Judge whether the database is successfully linked
        if (connection!=null){

            String sql = "select * from smbms_user where userCode = ?";
            Object[] params = {userCode};
            rs = BaseDao.execute(connection, sql, params, rs, preparedStatement);
            if (rs.next()) {
                user = new User();
                //Query all properties in user
                user.setId(rs.getInt("id"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserName(rs.getString("userName"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                user.setUserRole(rs.getInt("userRole"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
            }
            //connection is not off
            BaseDao.closeResources(null, preparedStatement, rs);

        }
    return user;
    }
}

5. Business layer interface

package xiaoqi.service.User;

import xiaoqi.pojo.User;

public interface UserService {
    //User login
    User login(String userCode,String password);
}

6. Business layer implementation class

package xiaoqi.service.User;

import org.junit.jupiter.api.Test;
import xiaoqi.dao.BaseDao;
import xiaoqi.dao.user.UserDao;
import xiaoqi.dao.user.UserDaoImpl;
import xiaoqi.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService{
    //The business layer will call the Dao layer, so we need to introduce the Dao layer
    private UserDao userDao;

    public UserServiceImpl() {
        userDao = new UserDaoImpl();
    }

    @Override
    public User login(String userCode, String password) {
        Connection connection = null;
        User user = null;

        try {
            //Get this connection
            connection = BaseDao.getConnection();
            //User login
            user = userDao.getLoginUser(connection,userCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResources(null,null,null);
        }
        return user;

    }
    @Test
    public void Test(){
        UserService userService = new UserServiceImpl();
        User admin = userService.login("admin", "1234567");
        System.out.println(admin.getAddress() + admin.getUserPassword());
    }
}

7. Write Servlet

package xiaoqi.servlet.user;

import xiaoqi.pojo.User;
import xiaoqi.service.User.UserService;
import xiaoqi.service.User.UserServiceImpl;
import xiaoqi.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    //Servlet control layer: calling business code

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet - start");

        //Get user name and password
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //Compare with the password in the database
        //Calling the code of the business layer
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);//This user has been found here
        if (user != null){
            //You can log in and find this person
            //Put the user into the session
            //Stored in key value pairs
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //Jump to the internal home page
            resp.sendRedirect("jsp/frame.jsp");
        }else {
            //No one was found
            //Forward it back to the login page and prompt the user name or password error
            req.setAttribute("error","Incorrect user name or password");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Added password verification

if (user != null){
    //You can log in and find this person
    //Put the user into the session
    //Stored in key value pairs
    if (userPassword.equals(user.getUserPassword())){
        //Determine whether the password is correct
        req.getSession().setAttribute(Constants.USER_SESSION,user);
        //Jump to the internal home page
        resp.sendRedirect("jsp/frame.jsp");
    }else {
        //Password error
        req.setAttribute("error","Incorrect user name or password");
        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }

}else {
    //No one was found
    //Forward it back to the login page and prompt the user name or password error
    req.setAttribute("error","Incorrect user name or password");
    req.getRequestDispatcher("login.jsp").forward(req,resp);
}

8. Register Servlet

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>xiaoqi.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login.do</url-pattern>
</servlet-mapping>

9. Test visit

Login function optimization

cancellation

package xiaoqi.servlet.user;

import xiaoqi.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginOutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute(Constants.USER_SESSION);//Remove useful session
        //After the request, return to the login page
        resp.sendRedirect(req.getContextPath()+"/login.jsp");//Return to login page
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
    <servlet>
        <servlet-name>LoginOutServlet</servlet-name>
        <servlet-class>xiaoqi.servlet.user.LoginOutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginOutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>

Landing interception optimization

package xiaoqi.filter;

import xiaoqi.pojo.User;
import xiaoqi.utils.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //Get user from session
        User user = (User)request.getSession().getAttribute(Constants.USER_SESSION);
        if (user == null){
            //Has been cancelled
            response.sendRedirect("/smbms/error.jsp");
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }

    @Override
    public void destroy() {

    }
}
<!--User login filter-->
<filter>
    <filter-name>SysFilter</filter-name>
    <filter-class>xiaoqi.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SysFilter</filter-name>
    <url-pattern>/jsp/*</url-pattern>
</filter-mapping>

Change Password

1. Import front-end materials

 <li><a href="../jsp/pwdmodify.jsp">Password modification</a></li>

2. Write the project from the bottom up

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-lsrrzhjl-1639619842299) (C: / users / 77 / appdata / roaming / typora / typora user images / image-20211213102025355. PNG)]

3.UserDao interface

//Modify the password of the current user
int updatePwd(Connection connection,int id,String password) throws SQLException;

4.UserDao implementation class

    //Modify current user password
    @Override
    public int updatePwd(Connection connection, int id, String password) throws SQLException {
        //Compile object
        PreparedStatement preparedStatement = null;
        int execute = 0;
        if (connection !=null){
            String sql = "update smbms_user set UserPassword = ? where id = ?";
            Object[] params = {password,id};//parameter
            //implement
            execute = BaseDao.execute(connection, sql, params, preparedStatement);
            //Close connection
            BaseDao.closeResources(null,preparedStatement,null);
        }
        return execute;
    }
}

5.UserService interface

//Modify the password according to the user id
boolean updatePwd(int id,String password);

6.UserService implementation class

//Change Password
@Override
public boolean updatePwd(int id, String password) {
    Connection connection = null;
    boolean flag = false;
    //Change Password
    try {
        connection = BaseDao.getConnection();
        if (userDao.updatePwd(connection,id,password) > 0){
            //If the modification is successful
            flag = true;

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        BaseDao.closeResources(connection,null,null);
    }
    return flag;
}

7.Servlet

package xiaoqi.servlet.user;

import com.mysql.jdbc.StringUtils;
import org.junit.jupiter.api.Test;
import xiaoqi.pojo.User;
import xiaoqi.service.User.UserService;
import xiaoqi.service.User.UserServiceImpl;
import xiaoqi.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//Realize servlet reuse
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the user id from the session
        System.out.println("doget");
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        //New password
        System.out.println(attribute);
        String newpassword = req.getParameter("newpassword");
        System.out.println(newpassword);
        boolean flag = false;
        if (attribute!=null && !StringUtils.isNullOrEmpty(newpassword)){
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) attribute).getId(), newpassword);
            if (flag){
                req.setAttribute("message","Password modification succeeded. Please exit and log in again");
                //Password modification succeeded. Remove session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","Password modification failed");
            }

        }else {
            req.setAttribute("message","Password modification error");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

}

8. Register web

<servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>xiaoqi.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>

9. Reuse

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String method = req.getParameter("method");
    if (method!=null && method.equals("savepwd") ){
        this.updatePwd(req,resp);
    }
}

Problems encountered in password modification:

Because the old password is not verified, the old password verification is cleared, and because the browser has cached the old password, it cannot be submitted without verifying the old password

Resolution: clear browser cache

Optimize password and modify Ajax;

  1. Bring into dependence - Alibaba's fastjson

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.78</version>
    </dependency>
    
  2. servlet

    //Verify old password
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        //Get the ID from the session
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //Get the old password from the front end and get it from js
        String oldpassword = req.getParameter("oldpassword");
    
        //Universal Map
        HashMap<String,String> resultMap = new HashMap<>();
    
        if (o!=null){
            //session failed. session expired
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){
            resultMap.put("result","error");//Return error with blank password
        }else {
            String userPassword = ((User) o).getUserPassword();//Get the password of session
            if (oldpassword.equals(userPassword)){
                //Password verification is correct
                resultMap.put("result","true");
            }else {
                resultMap.put("result","fasle");
            }
        }
    
        PrintWriter writer = null;
        try {
            resp.setContentType("application/json");//This is the above code, which is a json code
            writer = resp.getWriter();
            //JSONArray is a tool class of Alibaba, which converts map to json format
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            writer.close();
        }
    }
    

User management implementation

1. Import pagination tool class

package xiaoqi.utils;

/**
 * @author Administrator
 * @Auther: wuxy
 * @Date: 2021/1/28 - 01 - 28 - 19:43
 * @Description: com.wxy.util
 * @version: 1.0
 */
public class PageSupport {
    //Current page number - from user input
    private int currentPageNo = 1;

    //Total quantity (table)
    private int totalCount = 0;

    //Page capacity
    private int pageSize = 0;

    //Total pages - totalCount/pageSize (+ 1)
    private int totalPageCount = 1;

    public int getCurrentPageNo() {
        return currentPageNo;
    }

    //OOP has three features: encapsulation (private property, and get/set has some unsafe conditions in set)
    public void setCurrentPageNo(int currentPageNo) {
        if(currentPageNo > 0){
            this.currentPageNo = currentPageNo;
        }
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        if(totalCount > 0){
            this.totalCount = totalCount;
            //Set total pages
            this.setTotalPageCountByRs();
        }
    }
    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if(pageSize > 0){
            this.pageSize = pageSize;
        }
    }

    public int getTotalPageCount() {
        return totalPageCount;
    }

    public void setTotalPageCount(int totalPageCount) {
        this.totalPageCount = totalPageCount;
    }

    public void setTotalPageCountByRs(){
        if(this.totalCount % this.pageSize == 0){
            this.totalPageCount = this.totalCount / this.pageSize;
        }else if(this.totalCount % this.pageSize > 0){
            this.totalPageCount = this.totalCount / this.pageSize + 1;
        }else{
            this.totalPageCount = 0;
        }
    }

}

2. User list page import

1. Get the number of users

1.userDao

//Total number of query users
int getUserCount(Connection connection,String userName,int userRole) throws SQLException;

2.UserDaoImpl

    //Query the total number of users according to user name or user role
    @Override
    public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        int count = 0;
        if (connection!=null){
            StringBuffer sql = new StringBuffer();
            //If the front end does not enter any information, execute this paragraph and query all
            sql.append("select count(1) as count from smbms_user u, smbms_role r where u.userRole = r.id");
            ArrayList<Object> list = new ArrayList<>();//Store our parameters
            //If the front end passes in a name, add a condition
            if (!StringUtils.isNullOrEmpty(userName)){
                sql.append(" and u.userName like ?");
                list.add("%" +userName+"%");//Fuzzy query
            }
            if (userRole>0){
                sql.append(" and u.userRole = ?");
                list.add(userRole);//index+1
            }
            //How to convert a list into an array
            Object[] params = list.toArray();
            System.out.println("userDaoImpl->count"+sql.toString());
            //Start query
            rs = BaseDao.execute(connection, sql.toString(), params, rs ,preparedStatement);

            if (rs.next()){
                count = rs.getInt("count");//Get the final quantity from the result set
            }
            BaseDao.closeResources(null,preparedStatement,rs);
        }
        return count;
    }

3.userService

//Number of query records
int getUserCount(String userName,int userRole);

4.userServiceImpl

//Get the number of query users
//Call Dao layer
@Override
public int getUserCount(String userName, int userRole) {
    Connection connection = null;
    int count =0;
    try {
        connection = BaseDao.getConnection();
        count = userDao.getUserCount(connection,userName,userRole);//Get quantity
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        BaseDao.closeResources(connection,null,null);
    }
    return count;
}

@Test
public void Test(){
    UserService userService = new UserServiceImpl();
    int count = userService.getUserCount("Li Ming", 0);
    System.out.println(count);
}

2. Display user list

1.dao layer

//Get user list
List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize) throws SQLException;

2.dao implementation layer

//Get user list
@Override
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException {
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    List<User> userlist = new ArrayList<>();
    if (connection!=null){
        StringBuffer sql = new StringBuffer();
        List<Object> list = new ArrayList<>();
        sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
        if (!StringUtils.isNullOrEmpty(userName)){
            sql.append(" and u.userName = ?");
            list.add("%"+userName+"%");
        }
        if (userRole>0){
            sql.append(userRole);
            sql.append(" and u.userRole = ?");
        }
        //In the database, paging uses limit startIndex pageSize
        //Current page (current page-1) * page size
        //0,5    1   0    012345
        //6,5    2   5    26789
        //11,5   3   10
        sql.append(" order by creationDate DESC limit ?,?");
        currentPageNo = (currentPageNo-1)*pageSize;//First displayed on the front end
        list.add(currentPageNo);//First startindex
        list.add(pageSize);//Page size

        Object[] params = list.toArray();
        System.out.println("sql ->" + sql.toString());
        rs = BaseDao.execute(connection,sql.toString(),params,rs,preparedStatement);
        while (rs.next()){
            User _user = new User();
            _user.setId(rs.getInt("id"));
            _user.setUserCode(rs.getString("userCode"));
            _user.setUserName(rs.getString("userName"));
            _user.setGender(rs.getInt("gender"));
            _user.setBirthday(rs.getDate("birthday"));
            _user.setPhone(rs.getString("phone"));
            _user.setUserRole(rs.getInt("userRole"));
            _user.setUserRoleName(rs.getString("userRoleName"));
            userlist.add(_user);
        }
        BaseDao.closeResources(null,preparedStatement,rs);
    }
    return userlist;
}

3.service layer

//Query user list
List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);

4.service implementation layer

@Override
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
    Connection connection = null;
    List<User> list = new ArrayList<>();
    System.out.println("queryUserName ---- > " + queryUserName);
    System.out.println("queryUserRole ---- > " + queryUserRole);
    System.out.println("currentPageNo ---- > " + currentPageNo);
    System.out.println("pageSize ---- > " + pageSize);
    try {
        connection =  BaseDao.getConnection();
        list = userDao.getUserList(connection,queryUserName,queryUserRole,currentPageNo,pageSize);//Get query result set
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        BaseDao.closeResources(connection,null,null);
    }
    return list;
}

@Test
public void Test(){
    UserService userService = new UserServiceImpl();
    List<User> userList = userService.getUserList(null, 0, 2, 5);
    for (User user : userList) {
        System.out.println(user.getUserName());
    }
}

3. Get role list

In order to clarify our responsibilities, we need to put the role list into another package to facilitate code maintenance

public interface roleDao {
    //Get role list
    List<Role> getRoleList(Connection connection) throws SQLException;
}
//Get role list
@Override
public List<Role> getRoleList(Connection connection) throws SQLException {
    PreparedStatement preparedStatement = null;
    ResultSet rs = null;
    List<Role> list = new ArrayList<>();
    if (connection !=null){
        String sql = "select * from smbms_role";
        Object[] params = {};
        rs  = BaseDao.execute(connection, sql, params, rs, preparedStatement);
        while (rs.next()){
            Role _role = new Role();
            _role.setId(rs.getInt("id"));
            _role.setRoleCode(rs.getString("roleCode"));
            _role.setRoleName( rs.getString("roleName"));
            list.add(_role);

        }
        BaseDao.closeResources(null,preparedStatement,rs);
    }
    return list;
}
 //Get role list
    List<Role> getRoleList();
//Introducing Dao
private roleDao roleDao;

public roleServiceImpl() {
    roleDao = new roleDaoImpl();//Constructor loading
}

//Get role list
@Override
public List<Role> getRoleList() {
    Connection connection = null;
    List<Role> roleList = null;
    try {
        connection = BaseDao.getConnection();
        roleList = roleDao.getRoleList(connection);
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        BaseDao.closeResources(connection,null,null);
    }
    return roleList;
}
@Test
public void test(){
    roleService roleService = new roleServiceImpl();
    List<Role> roleList = roleService.getRoleList();
    for (Role role : roleList) {
        System.out.println(role.getRoleName());
    }
}

4. Servlet displayed by the user

1. Obtain the data of the user's previous paragraph (query)

 //Query user list
    //Get data from the front end
    String queryName = req.getParameter("queryname");
    String queryUserRole = req.getParameter("queryUserRole");
    String pageIndex = req.getParameter("pageIndex");
    //Get user list
    UserServiceImpl userService = new UserServiceImpl();
    roleServiceImpl roleService = new roleServiceImpl();
    //The first time you take this request, it must be the first page, and the page size is fixed
    int pageSize = 5;//Fixed size
    int currentPageNo = 1;
    int queryUserRole_num = 0;
    System.out.println("queryName servlet--------" + queryName);
    System.out.println("queryUserRole servlet--------" + queryUserRole);
    System.out.println("query pageIndex--------- > " + pageIndex);

2. Judge whether the parameter value needs to be executed

//Take out the name to query
    if (queryName == null){
        queryName = "";
    }
    //Remove the selected role
    if (queryUserRole !=null && !queryUserRole.equals("")){
        queryUserRole_num = Integer.parseInt(queryUserRole);//Convert the role value obtained from the front end into a number, and 0 1 2 3 will be displayed, which will not be empty
    }
    //Take out the current page
    if (pageIndex!=null){
        try {//If an error occurs, redirect to error
            currentPageNo = Integer.parseInt(pageIndex);//Parse current page number
        } catch (Exception e) {
            try {
                resp.sendRedirect("error.jsp");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

3. In order to realize paging, you need to calculate the page

//Gets the total number of users (if the page has previous and next pages)
    int usertotalCount = userService.getUserCount(queryName, queryUserRole_num);
    System.out.println(usertotalCount);
    PageSupport pageSupport = new PageSupport();//Total pages support
    pageSupport.setCurrentPageNo(currentPageNo);
    pageSupport.setPageSize(pageSize);
    pageSupport.setTotalCount(usertotalCount);//Set total number of users

    int totalPageCount = pageSupport.getTotalPageCount();
    //Control first and last pages
    //If the current page is smaller than, the first page is displayed
    if (currentPageNo < 1){
        currentPageNo =1;
    }else if (currentPageNo > totalPageCount){//The current page is larger than the last page
        currentPageNo = totalPageCount;
    }

4. User list display and return to the front end

  //Get user list display
    List<User> userList = userService.getUserList(queryName, queryUserRole_num, currentPageNo, pageSize);
   /* for (User user : userList) {
        System.out.println(user.getPhone());
    }*/
    req.setAttribute("userList",userList);

    //Get the user list of all roles
    List<Role> roleList = roleService.getRoleList();
    /*for (Role role : roleList) {
        System.out.println(role.getId());
    }*/
    req.setAttribute("roleList",roleList);
    req.setAttribute("queryUserName", queryName);
    req.setAttribute("queryUserRole", queryUserRole);
    req.setAttribute("totalCount",usertotalCount);
    req.setAttribute("currentPageNo",currentPageNo);
    req.setAttribute("totalPageCount",totalPageCount);
    System.out.println(totalPageCount);

    //Return to previous paragraph
    try {
        req.getRequestDispatcher("userlist.jsp").forward(req,resp);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
public void query(HttpServletRequest req, HttpServletResponse resp){
    //Query user list
    //Get data from the front end
    String queryName = req.getParameter("queryname");
    String queryUserRole = req.getParameter("queryUserRole");
    String pageIndex = req.getParameter("pageIndex");

    //Get user list
    UserServiceImpl userService = new UserServiceImpl();
    roleServiceImpl roleService = new roleServiceImpl();
    //The first time you take this request, it must be the first page, and the page size is fixed
    int pageSize = 5;//Fixed size
    int currentPageNo = 1;
    int queryUserRole_num = 0;
    System.out.println("queryName servlet--------" + queryName);
    System.out.println("queryUserRole servlet--------" + queryUserRole);
    System.out.println("query pageIndex--------- > " + pageIndex);
    //Take out the name to query
    if (queryName == null){
        queryName = "";
    }
    //Remove the selected role
    if (queryUserRole !=null && !queryUserRole.equals("")){
        queryUserRole_num = Integer.parseInt(queryUserRole);//Convert the role value obtained from the front end into a number, and 0 1 2 3 will be displayed, which will not be empty
    }
    //Take out the current page
    if (pageIndex!=null){
        try {//If an error occurs, redirect to error
            currentPageNo = Integer.parseInt(pageIndex);//Parse current page number
        } catch (Exception e) {
            try {
                resp.sendRedirect("error.jsp");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    //Gets the total number of users (if the page has previous and next pages)
    int usertotalCount = userService.getUserCount(queryName, queryUserRole_num);
    System.out.println(usertotalCount);
    PageSupport pageSupport = new PageSupport();//Total pages support
    pageSupport.setCurrentPageNo(currentPageNo);
    pageSupport.setPageSize(pageSize);
    pageSupport.setTotalCount(usertotalCount);//Set total number of users

    int totalPageCount = pageSupport.getTotalPageCount();
    //Control first and last pages
    //If the current page is smaller than, the first page is displayed
    if (currentPageNo < 1){
        currentPageNo =1;
    }else if (currentPageNo > totalPageCount){//The current page is larger than the last page
        currentPageNo = totalPageCount;
    }

    //Get user list display
    List<User> userList = userService.getUserList(queryName, queryUserRole_num, currentPageNo, pageSize);
   /* for (User user : userList) {
        System.out.println(user.getPhone());
    }*/
    req.setAttribute("userList",userList);

    //Get the user list of all roles
    List<Role> roleList = roleService.getRoleList();
    /*for (Role role : roleList) {
        System.out.println(role.getId());
    }*/
    req.setAttribute("roleList",roleList);
    req.setAttribute("queryUserName", queryName);
    req.setAttribute("queryUserRole", queryUserRole);
    req.setAttribute("totalCount",usertotalCount);
    req.setAttribute("currentPageNo",currentPageNo);
    req.setAttribute("totalPageCount",totalPageCount);
    System.out.println(totalPageCount);

    //Return to previous paragraph
    try {
        req.getRequestDispatcher("userlist.jsp").forward(req,resp);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

5. Implementation of addition, deletion and modification

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nzzqek74-1639619842301) (C: / users / 77 / appdata / roaming / typora / typora user images / image-20211215143026281. PNG)]

Order management and supplier management are similar to user management

They are all done by the basic MVC framework

Extended application

1. File upload

In web applications, the file upload and download function is a very common function. Today, let's realize the file upload and download function in Java Web

1. Preparation

For file upload, the browser submits the file to the server in the form of stream during the upload process.

Generally, the file upload component is common file upload, an open source tool of apache.

Common file upload depends on the common IO package, so you also need to download this package.

Download the latest jar package

https://mvnrepository.com/artifact/commons-io/commons-io
https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload

2. Introduction to usage class

[precautions for file upload]

  1. In order to ensure the security of the server, the uploaded files should be placed in a directory that cannot be directly accessed by the outside world, such as the WEB-INF directory.
  2. To prevent file overwriting, a unique file name should be generated for the uploaded file
  3. To limit the maximum number of uploaded files.
  4. You can limit the type of uploaded file and judge whether the suffix is legal when you receive the uploaded file name.

[detailed description of classes to be used]

ServletFileUpload is responsible for processing the uploaded file data and encapsulating each input item in the form into a FileItem object. The DiskFileItemFactory object is required when using the ServletFileUpload object to parse the request. Therefore, we need to construct the DiskFileItemFactory object before parsing, and set the fileItemFactory property of the ServletFileUpload object through the construction method of = = ServletFileUpload object or setFileItemFactory() = = method.

FileItem class

In HTML pages, input must have name < input type = "file" name = "filename" >

If the form contains a file upload input item, the enctype attribute of the form must be set to multipart / form data

If the type of browser form is multipart / form data, you need to go through the stream to get data on the server side.

<%--
  Created by IntelliJ IDEA.
  User: 77
  Date: 2021/12/15
  Time: 19:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <%--Upload via form
  get: Upload file size is limited
  post:  There is no limit on the size of uploaded files--%>
  <form action = "" method = "post" enctype="multipart/form-data">
    Upload user:<input type="text" name="username"><br/>
    <p><input type="file" name="file1"></p>
    <p><input type="file" name="file2"></p>
    <p><input type="submit"> |<input type="reset"></p>
  </form>
  </body>
</html>

[introduction to common methods]

//The isFormField method is used to judge that the data encapsulated by the FileItem class object is a normal text form
//It is also a file form. If it is an ordinary form field, it returns true; otherwise, it returns false
boolean isFormField();

//The getFieldName method is used to return the value of the name property of the form label.
String getFieldName();

//The getString method is used to return the data stream content saved in the FileItem object as a string
String getString();

//The getName method is used to obtain the file name in the file upload field.
String getName();

//Return the data content of the uploaded file in the form of stream.
InputStream getInputStream()

//The delete method is used to empty the body content stored in the FileItem class object
//If the body content is saved in a temporary file, the delete method deletes the temporary file.
void delete();

ServletFileUpload class

ServletFileUpload handles the uploaded file data and encapsulates each input item in the form into a FileItem object Using its parseRequest(HttpServletRequest) method, the data submitted through each HTML tag in the form can be encapsulated into a FileItem object, and then returned in the form of List. Using this method to process uploaded files is simple and easy to use.

3. Coding

UploadServlet

package servlet;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;
 
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        try {
            //Determine whether the uploaded file is an ordinary form or a form with a file
            if (!ServletFileUpload.isMultipartContent(request)) {
                return;//If it is an ordinary file, we can return it directly
            } //If this if is passed, it means that our form is uploaded with files;
 
            //Create a save path for the uploaded file. It is recommended that it be safe under the WEB-INF path. Users cannot directly access the uploaded file;
            String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
            File uploadFile = new File(uploadPath);
            if (!uploadFile.exists()) {//If the directory does not exist, create such a directory;
                uploadFile.mkdir();
            }
 
            //Temporary path. If the file exceeds the expected size, we will put it into a temporary file and delete it automatically in a few days, or remind the user to save it permanently
            String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
            File file = new File(tmpPath);
            if (!file.exists()) {//If the directory does not exist, create such a directory;
                file.mkdir();
            }
 
            //To process the uploaded files, we usually need to obtain them through the stream. We can use request Getinputstream(), the original file upload stream, is very troublesome
            //However, we all recommend using Apache's file upload component, common file upload, which depends on the common IO component;
 
            //1. Create a DiskFileItemFactory object to handle file upload path or size restrictions;
            DiskFileItemFactory factory = getDiskFileItemFactory(file);
            //2. Get ServletFileUpload
            ServletFileUpload upload = getServletFileUpload(factory);
            //3. Process uploaded files
            String msg = uploadParseRequest(upload, request, uploadPath);
 
            //servlet request forwarding message
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("msg.jsp").forward(request,response);
 
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
 
    }
 
 
    public static DiskFileItemFactory getDiskFileItemFactory(File file) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //Set a buffer through the factory. When the uploaded file is larger than the buffer, it will be put into the temporary file;
        factory.setSizeThreshold(1024 * 1024); //The cache size is 1M
        factory.setRepository(file);//A File is required to save the temporary directory
        return factory;
    }
 
    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        //Monitor file upload progress;
        upload.setProgressListener(new ProgressListener() {
            @Override
            //pBytesRead: the size of the file that has been read
            //pContentLength: file size
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("Total size:" + pContentLength + "Uploaded:" + pBytesRead);
            }
        });
 
        //Dealing with garbled code
        upload.setHeaderEncoding("UTF-8");
        //Sets the maximum value for a single file
        upload.setFileSizeMax(1024 * 1024 * 10);
        //Set the total size of files that can be uploaded
        //1024 = 1kb * 1024 = 1M * 10 = 10M
        upload.setSizeMax(1024 * 1024 * 10);
 
        return upload;
    }
 
 
    public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest request,String uploadPath)
            throws FileUploadException, IOException {
 
        String msg = "";
 
        //3. Parse the front-end request and encapsulate it into a FileItem object
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()){ //Determine whether the uploaded file is an ordinary form or a form with a file
                //getFieldName refers to the name of the front-end form control;
                String name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8"); //Deal with garbled code
                System.out.println(name+":"+value);
            }else { //Judge whether it is an uploaded file
 
                //=======================Processing files===============================//
 
                //Get the file name
                String uploadFileName = fileItem.getName();
                System.out.println("Uploaded file name:"+uploadFileName);
 
                if (uploadFileName.trim().equals("")||uploadFileName==null){
                    continue;
                }
 
                //Get the uploaded file name / images / girl / paojie png
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\") + 1);
                //Get the suffix of the file
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                    /*
                        If the file suffix fileExtName is not what we need
                        Just return without processing and tell the user that the file type is wrong.
                    */
 
                System.out.println("file information [Item name:"+fileName+"---file type"+fileExtName+"]");
 
                //UUID (unique universal code) can be used to ensure that the file name is unique;
                //UUID.randomUUID(), randomly generating a unique universal code;
                String uuidPath = UUID.randomUUID().toString();
 
                //=======================Finished processing files===============================//
 
                //Where? uploadPath
                //The real path of the file realPath
                String realPath =   uploadPath+"\\"+uuidPath;
                //Create a folder for each file
                File realPathFile = new File(realPath);
                if (!realPathFile.exists()){
                    realPathFile.mkdir();
                }
 
                //=======================Storage address completed===============================//
 
                //Get the stream of file upload
                InputStream inputStream = fileItem.getInputStream();
 
                //Create a file output stream
                //realPath = real folder;
                //Missing a file; Add the name of the output file + "/" + uuidFileName
                FileOutputStream fos = new FileOutputStream(realPath+"\\"+fileName);
 
                //Create a buffer
                byte[] buffer = new byte[1024*1024];
 
                //Judge whether the reading is completed
                int len = 0;
                //If it is greater than 0, data still exists;
                while ((len=inputStream.read(buffer))>0){
                    fos.write(buffer,0,len);
                }
 
                //Close flow
                fos.close();
                inputStream.close();
 
                msg = "File upload succeeded!";
                fileItem.delete(); //Upload succeeded. Clear the temporary file
                //=======================File transfer completed===============================//
            }
        }
 
        return msg;
    }
}

upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File upload</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
        Upload user:<input type="text" name="username"><br/>
        Upload file 1:<input type="file" name="file1"><br/>
        Upload file 2:<input type="file" name="file2"><br/>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

msg.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Message prompt</title>
</head>
<body>
    ${msg}
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0">
   <servlet>
        <servlet-name>upload</servlet-name>
        <servlet-class>com.kuang.servlet.UploadFileServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>upload</servlet-name>
        <url-pattern>/upload.do</url-pattern>
    </servlet-mapping>
</web-app>

2. Email sending

javaWeb madness_ 10 (email).

Implementation of website registration mail sending function.

Keywords: Java server

Added by bidnshop on Thu, 16 Dec 2021 04:09:42 +0200