JavaWeb

Learn summary B station up “crazy god say Java” “JavaWeb” notes, delete

1. Basic concepts

1.1, the preface

Web development:

  • Web, meaning web page, www.baidu.com
  • Static web
    • HTML, CSS
    • The data for all to see will never change!
  • Dynamic web
    • Taobao, almost all websites;
    • The data available to everyone changes all the time, and everyone sees different information in different places at different times!
    • Technology stack: Servlet/JSP, ASP, PHP

In Java, the technology of dynamic Web resource development is called JavaWeb.

1.2. Web Applications

Web applications: programs that can be accessed by a browser;

  • A.h HTML, b.h HTML… Multiple Web resources, which can be accessed by the outside world and provide services to the outside world;
  • Every page or resource you can access exists on a computer somewhere in the world.
  • URL
  • The unified Web resource will be placed in the same folder, Web Applications –>Tomcat: Server
  • A Web application consists of several parts (static Web, dynamic Web)
    • HTML, CSS, JS
    • JSP, servlet
    • Java program
    • The jar package
    • Configuration file (Properties)

Once a Web application is written, if you want to make it accessible to the outside world, you need a server to manage it.

1.3. Static Web

  • *.htm, *.html, these are all suffixes for web pages, and if these things are always on the server, we can just read them. T2dm.

  • Disadvantages of the static Web
    • The Web page cannot be dynamically updated, and all users see the same page
      • Rotation map, click effect: Pseudo-dynamic
      • JavaScript [most used in actual development]
      • VBScript
    • It can’t interact with the database (data can’t be persisted, users can’t interact)

1.4. Dynamic Web

Pages will be displayed dynamically: “Web page presentation effects vary from person to person”;

Disadvantages:

  • There was an error with the dynamic Web resource added to the server and we need to rewrite ourdaemon, re-release;
    • downtime

Advantages:

  • Web pages can be updated dynamically, and all users see different pages
  • It can interact with databases (data persistence: registration, product information, user information……..)

Novice village: — devil training (analysis principle, see source code) –> PK field

2. Web server

2.1. Technical explanation

ASP:

  • Microsoft: the earliest domestic popular is ASP;

  • Embedded in HTML VB script, ASP + COM;

  • In ASP development, a basic page has thousands of lines of business code, the page is extremely chaotic

  • High maintenance costs!

  • C#

  • IIS

    <h1>
        <h1><h1>
            <h1>
                <h1>
                    <h1>
            <h1>
                <%
                System.out.println("hello")
                %>
                <h1>
                    <h1>
       <h1><h1>
    <h1>
    Copy the code

PHP:

  • PHP is fast, powerful, cross-platform, and has simple code (70%, WP)
  • Unable to handle large volume of traffic (limitations)

**JSP/Servlet : **

B/S: Browsing and server

C/S: client and server

  • Sun’s B/S architecture
  • Java language-based (all big companies, or open source components, are written in Java)
  • Can carry the impact of the three high problems;
  • Syntax like ASP, ASP–>JSP, strengthen market strength;

.

2.2. Web Server

A server is a passive operation, used to process some of the user’s requests and give the user some response information;

IIS

Microsoft’s; ASP… , built-in in Windows

Tomcat

Programming for Baidu;

Tomcat is a core project of the Apache Software Foundation’s Jakarta project, where the latest Servlet and JSP specifications are always reflected, Because of its advanced technology, stable performance, and free, Tomcat is deeply loved by Java enthusiasts and recognized by some software developers, and has become a popular Web application server.

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

Tomcat actually runs JSP pages and servlets. The latest version of Tomcat is 9.0.

.

After 3-5 years, try writing Tomcat servers by hand;

Download tomcat:

  1. Install or unpack
  2. Understand configuration files and directory structure
  3. What this thing does

3, Tomcat

3.1. Install Tomcat

Tomcat official website: tomcat.apache.org/

3.2 Tomcat startup and configuration

Folder functions:

Start. To shut down Tomcat

Visit the test: http://localhost:8080/

Possible problems:

  1. The Java environment variable is not configured
  2. Flash Rollback Problem: Compatibility needs to be configured
  3. Garbled problem: Settings in the configuration file

3.3, configuration,

You can configure the boot port number

  • The default tomcat port number is 8080
  • Mysql: 3306
  • 80 HTTP:
  • HTTPS: 443
<Connector port="8081" protocol="HTTP / 1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
Copy the code

You can configure the host name

  • The default host name is localhost->127.0.0.1
  • The default directory for storing web applications is Webapps
  <Host name="www.qinjiang.com"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">
Copy the code

Tough interview questions:

Please talk about how the website is accessed!

  1. Enter a domain name; enter

  2. Check the C:\Windows\System32\drivers\etc\hosts configuration file for this domain name mapping.

    1. Yes: directly returns the corresponding IP address, this address, we need to access the Web program, you can directly access

      127.0. 01.       www.qinjiang.com
      Copy the code
    2. No: go to the DNS server to find, find the words to return, can not find the return can not find;

  3. Environment variables can be configured (optional)

Publish a Web site

Don’t imitate first

  • Put your website into the folder (Webapps) of the web application specified in the server (Tomcat) and you can access it

The structure your website should have

--webapps: Tomcat server directory -root-kuangstudy: website directory -web-INF -classes: Java program -lib: jar package that web applications depend on -web. XML: website configuration file -index.html Default home page -static 
            -css
            	-style.css
            -js
            -img
         -.....
Copy the code

HTTP protocol: interview

Maven: build tool

  • Maven installation package

Introduction to the Servlet

  • The HelloWorld!
  • The Servlet configuration
  • The principle of

4, the Http

4.1. What is HTTP

HTTP (Hypertext Transfer Protocol) is a simple request-response protocol that typically runs on top of TCP.

  • Text: HTML, string, ~… .
  • Hypertext: pictures, music, video, location, maps… .
  • 80

Https: secure

  • 443

4.2. Two Eras

  • http1.0

    • HTTP/1.0: The client can connect to the Web server and obtain only one Web resource
  • http2.0

    • HTTP/1.1: The client can connect to the Web server and obtain multiple Web resources. ‘

4.3. Http Requests

  • The client sends requests to the server

Baidu:

Request URL:https://www.baidu.com/ request an addressRequest Method:GET GET Method/Post Method Status Code:200OK status code:200A. Address B. Address C. Address D. Address14.215177.. 39:443
Copy the code
Accept:text/html Accept-Encoding:gzip, deflate, br Accept-Language:zh-CN,zh; q=0.9Language cache-control: Max - age =0
Connection:keep-alive
Copy the code

1. Request line

  • Request in the request line: GET
  • Request method:The Get and Post, the HEAD, DELETE, PUT, TRACT…
    • Get: A request can carry fewer parameters and has a limited size. Data content is displayed in the URL bar of the browser, which is insecure but efficient
    • Post: The number of parameters that can be carried by a request is unlimited. The data content will not be displayed in the URL bar of the browser. It is secure but inefficient.

2. Message headers

Accept: tells the browser which data type it supports accept-encoding: which Encoding is supported GBK UTF-8   GB2312  ISO8859-1Accept-language: tells the browser its locale cache-control: Cache Control Connection: tells the browser whether to disconnect or keep the Connection when the request is completed HOST: HOST.... /.Copy the code

4.4 Http response

  • Server — Responds to —– client

Baidu:

Cache-Control:privateCache control Connection: keep-alive Connection Content-Encoding:gzip Encoding Content-Type:text/ HTML TypeCopy the code

1. The response body

Accept: tells the browser which data type it supports accept-encoding: which Encoding is supported GBK UTF-8   GB2312  ISO8859-1Accept-language: tells the browser its locale cache-control: Cache Control Connection: tells the browser whether to disconnect or keep the Connection when the request is completed HOST: HOST.... /. Refresh: Tells the client how often to Refresh; Location: Reposition the page;Copy the code

2. Response status code

200: Request response succeeded 200

3xx: Request redirection

  • Redirect: You go back to the new position I gave you;

4xx: Resource 404 not found

  • Resources do not exist;

5xx: server code error 500 502: gateway error

Often meet try:

What happens when you type your address in the browser’s address bar and press enter and it comes back to the page?

5, Maven

Why should I learn this technique?

  1. In Javaweb development, we need to use a large number of jar packages, we manually import;

  2. How can I get something to automatically import and configure this JAR for me?

    Thus Maven was born!

5.1 Maven Project Architecture Management tool

We are currently used to facilitate the import of JAR packages!

Maven’s core idea: Conventions outweigh configurations

  • There are constraints, don’t break them.

Maven dictates how you should write our Java code and must follow this specification;

5.2 Downloading and Installing Maven

Website; maven.apache.org/

After downloading, decompress it.

Small crazy god friendship advice: all the environment on the computer are placed in a folder, convenient management;

5.3 Configuring Environment Variables

In our system environment variables

The configuration is as follows:

  • Bin directory in the M2_HOME maven directory
  • MAVEN_HOME Directory for Maven
  • Configure %MAVEN_HOME%\bin in the system path

Test whether Maven is installed successfully and ensure that the configuration is complete!

5.4 Ali Cloud Image

  • Mirror: mirrors
    • What it does: Speeds up our downloads
  • Domestic suggestions to use ali Cloud mirror
<mirror>
    <id>nexus-aliyun</id>  
    <mirrorOf>*! jeecg,! jeecg-snapshots</mirrorOf>  
    <name>Nexus aliyun</name>  
    <url>http://maven.aliyun.com/nexus/content/groups/public</url> 
</mirror>
Copy the code

5.5 Local Warehouse

In local warehouses, remote warehouses;

Create a localRepository: **localRepository

<localRepository>D: \ Environment \ apache maven - 3.6.2 \ maven repo</localRepository>
Copy the code

5.6. Use Maven in IDEA

  1. Start the IDEA

  2. Create a MavenWeb project

  3. Wait until the project initialization is complete

  4. What is added to the Maven repository?

  5. Maven Settings in IDEA

    Note: After the IDEA project is successfully created, take a look at the Maven configuration

  6. Here, the configuration and use of Maven in IDEA is OK!

5.7. Create a normal Maven project

This is only available in Web applications!

5.8 Mark Folders

5.9 Configuring Tomcat in IDEA

Resolve warning issues

Mandatory configuration: Why there is a problem: we need to specify a folder name when accessing a website;

5.10 pom file

Pom.xml is Maven’s core configuration file


      

<! --Maven versions and headers -->
<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>

  <! GAV = GAV = GAV = GAV
  <groupId>com.kuang</groupId>
  <artifactId>javaweb-01-maven</artifactId>
  <version>1.0 the SNAPSHOT</version>
  <! Jar: Java application war: JavaWeb application -->
  <packaging>war</packaging>


  <! - configuration - >
  <properties>
    <! -- Default build code for the project -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <! -- Encoding version -->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <! -- Project dependencies -->
  <dependencies>
    <! Jar configuration file -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
  </dependencies>

  <! -- Project construction stuff -->
  <build>
    <finalName>javaweb-01-maven</finalName>
    <pluginManagement><! -- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <! -- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Copy the code

Because maven has more conventions than configurations, we can encounter the problem that the configuration files we write cannot be exported or take effect later. The solution is as follows:

<! Configure resources in build to prevent resource export failure.
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</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>
Copy the code

5.12 the IDEA of operating

5.13 Solve problems encountered

  1. Maven 3.6.2

    Solution: Downgrade to 3.6.1

  2. Tomcat flash back

  3. Maven is configured in the global default configuration of IDEA

  4. Tomcat cannot be configured in Maven project

  5. Maven defaults to web.xml versioning problems in Web projects

  6. Webapp4.0 is the same as tomcat

    
            
    <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"
             metadata-complete="true">
    
    
    
    </web-app>
    Copy the code
  7. Use of Maven repositories

    Address: mvnrepository.com/

6, the Servlet

6.1 introduction to Servlets

  • Servlets are one of sun’s technologies for developing the dynamic Web
  • Sun provides an interface in these apis called servlets. If you want to develop a Servlet application, there are only two small steps to complete:
    • Write a class that implements the Servlet interface
    • Deploy the developed Java classes to a Web server.

Java programs that implement the Servlet interface are called servlets

6.2, HelloServlet

Serlvet interface Sun has two default implementation classes: HttpServlet and GenericServlet

  1. Create a regular Maven project and delete the SRC directory. We will learn how to create Moudel in this project. This empty project is the Maven main project;

  2. Maven parent-child Project:

    There will be in the parent project

        <modules>
            <module>servlet-01</module>
        </modules>
    Copy the code

    Subprojects will have

        <parent>
            <artifactId>javaweb-02-servlet</artifactId>
            <groupId>com.kuang</groupId>
            <version>1.0 the SNAPSHOT</version>
        </parent>
    Copy the code

    Java subprojects in the parent project can be used directly

    son extends father
    Copy the code
  3. Maven Environment Optimization

    1. Modify web.xml to the latest
    2. Complete the Architecture of Maven
  4. Write a Servlet program

    1. Write a normal class

    2. Implement the Servlet interface, here we directly inherit HttpServlet

      public class HelloServlet extends HttpServlet {
          
          // Since get or POST are just different ways of implementing requests, they can be called to 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.print("Hello,Serlvet");
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
  5. Write the mapping for the Servlet

    Why we need mapping: We are writing a JAVA application, but we need to access it through a browser, and the browser needs to connect to the Web server, so we need to register our Servlet with the Web service and give it a path that the browser can access.

        <! - the registration Servlet -- -- >
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
        </servlet>
        <! --Servlet request path -->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
    Copy the code
  6. Configure Tomcat

    Note: Just configure the path for the project to publish

  7. Start the test, OK!

6.3. Principle of Servlet

A Servlet is invoked by a Web server that, upon receiving a browser request, :

6.4. Mapping Problem

  1. A Servlet can specify a mapping path

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

        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello2</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello3</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello4</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello5</url-pattern>
        </servlet-mapping>
    
    Copy the code
  3. A Servlet can specify a generic mapping path

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

        <! -- Default request path -->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/ *</url-pattern>
        </servlet-mapping>
    Copy the code
  5. Specify suffixes or prefixes, etc… .

    <! Note - you can customize the suffix implementation request mapping points, * added project mapping path in front of the hello/sajdlkajda qinjiang - >
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>*.qinjiang</url-pattern>
    </servlet-mapping>
    Copy the code
  6. The priority problem specifies that the inherent mapping path has the highest priority, and if it cannot be found, the request will be processed by default.

    <! - $404 - >
    <servlet>
        <servlet-name>error</servlet-name>
        <servlet-class>com.kuang.servlet.ErrorServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>error</servlet-name>
        <url-pattern>/ *</url-pattern>
    </servlet-mapping>
    
    Copy the code

6.5, the ServletContext

When the Web container is started, it creates a ServletContext object for each Web application, which represents the current Web application.

1. Share data

The data I save in one Servlet is available in the other;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // this.getinitparameter () initializes the parameter
        / / this. GetServletConfig () Servlet configuration
        //this.getServletContext() Servlet context
        ServletContext context = this.getServletContext();

        String username = "Qin jiang"; / / data
        context.setAttribute("username",username); // Save a data in the ServletContext named username. Value the username}}Copy the code
public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print("Name"+username);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>getc</servlet-name>
        <servlet-class>com.kuang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>
Copy the code

Test access results;

2. Obtain initialization parameters

    <! Set some Web application initialization parameters -->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
Copy the code
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    String url = context.getInitParameter("url");
    resp.getWriter().print(url);
}
Copy the code

3. Request forwarding

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext context = this.getServletContext();
    System.out.println("Entered ServletDemo04");
    //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); // Forward the request path
    //requestDispatcher.forward(req,resp); // Call forward to forward the request;
    context.getRequestDispatcher("/gp").forward(req,resp);
}
Copy the code

4. Read the resource file

Properties

  • Create properties under the Java directory
  • Create new Properties under the Resources directory

Found: all packed into the same path: classes, commonly known as classpath:

Idea: Need a file stream;

username=root12312
password=zxczxczxc
Copy the code
public class ServletDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");

        Properties prop = new Properties();
        prop.load(is);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");

        resp.getWriter().print(user+":"+pwd);

    }

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

Access test ok;

6.6, HttpServletResponse

The Web server receives the HTTP request from the client. For this request, an HttpServletRequest object representing the request is created, representing an HttpServletResponse of the response.

  • To get the parameters requested by the client: look for HttpServletRequest
  • If you want to give the client response some information: look for HttpServletResponse

1. Simple classification

The method responsible for sending data to the browser

ServletOutputStream getOutputStream(a) throws IOException;
PrintWriter getWriter(a) throws IOException;
Copy the code

The method responsible for sending the response header to the browser

    void setCharacterEncoding(String var1);

    void setContentLength(int var1);

    void setContentLengthLong(long var1);

    void setContentType(String var1);

    void setDateHeader(String var1, long var2);

    void addDateHeader(String var1, long var2);

    void setHeader(String var1, String var2);

    void addHeader(String var1, String var2);

    void setIntHeader(String var1, int var2);

    void addIntHeader(String var1, int var2);
Copy the code

The status code of the response

    int SC_CONTINUE = 100;
    int SC_SWITCHING_PROTOCOLS = 101;
    int SC_OK = 200;
    int SC_CREATED = 201;
    int SC_ACCEPTED = 202;
    int SC_NON_AUTHORITATIVE_INFORMATION = 203;
    int SC_NO_CONTENT = 204;
    int SC_RESET_CONTENT = 205;
    int SC_PARTIAL_CONTENT = 206;
    int SC_MULTIPLE_CHOICES = 300;
    int SC_MOVED_PERMANENTLY = 301;
    int SC_MOVED_TEMPORARILY = 302;
    int SC_FOUND = 302;
    int SC_SEE_OTHER = 303;
    int SC_NOT_MODIFIED = 304;
    int SC_USE_PROXY = 305;
    int SC_TEMPORARY_REDIRECT = 307;
    int SC_BAD_REQUEST = 400;
    int SC_UNAUTHORIZED = 401;
    int SC_PAYMENT_REQUIRED = 402;
    int SC_FORBIDDEN = 403;
    int SC_NOT_FOUND = 404;
    int SC_METHOD_NOT_ALLOWED = 405;
    int SC_NOT_ACCEPTABLE = 406;
    int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
    int SC_REQUEST_TIMEOUT = 408;
    int SC_CONFLICT = 409;
    int SC_GONE = 410;
    int SC_LENGTH_REQUIRED = 411;
    int SC_PRECONDITION_FAILED = 412;
    int SC_REQUEST_ENTITY_TOO_LARGE = 413;
    int SC_REQUEST_URI_TOO_LONG = 414;
    int SC_UNSUPPORTED_MEDIA_TYPE = 415;
    int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    int SC_EXPECTATION_FAILED = 417;
    int SC_INTERNAL_SERVER_ERROR = 500;
    int SC_NOT_IMPLEMENTED = 501;
    int SC_BAD_GATEWAY = 502;
    int SC_SERVICE_UNAVAILABLE = 503;
    int SC_GATEWAY_TIMEOUT = 504;
    int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
Copy the code

2. Download files

  1. Output messages to the browser
  2. The download file
    1. To get the path to the downloaded file
    2. What is the file name of the download?
    3. Set up a way for the browser to support downloading what we need
    4. Gets the input stream for the downloaded file
    5. Creating a buffer
    6. Get the OutputStream object
    7. Writes the FileOutputStream to the buffer buffer
    8. Output buffer data to the client using OutputStream!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. Obtain the path for downloading the file
    String realPath = "F: Class Management [19525] \2, code \JavaWeb\ javaweb-02-servlet\ Response \target\ classes\ chinjiang.png";
    System.out.println("Download file path:"+realPath);
    // 2. What is the file name of the download?
    String fileName = realPath.substring(realPath.lastIndexOf("\ \") + 1);
    Try to make the browser support (content-disposition) downloading what we need, urlencoder.encode, otherwise it's possible to get a content-disposition
    resp.setHeader("Content-Disposition"."attachment; filename="+URLEncoder.encode(fileName,"UTF-8"));
    // 4. Get the input stream for the downloaded file
    FileInputStream in = new FileInputStream(realPath);
    // 5. Create buffer
    int len = 0;
    byte[] buffer = new byte[1024];
    // 6. Get the OutputStream object
    ServletOutputStream out = resp.getOutputStream();
    // 7. Write the FileOutputStream to the buffer, and output the data in the buffer to the client with OutputStream!
    while ((len=in.read(buffer))>0){
        out.write(buffer,0,len);
    }

    in.close();
    out.close();
}
Copy the code

3. Verification code function

Where does verification come from?

  • The front-end implementation
  • Back-end implementation, need to use Java image class, produce an image
package com.kuang.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 refresh the browser automatically every 3 seconds;
        resp.setHeader("refresh"."3");
        
        // Create an image in memory
        BufferedImage image = new BufferedImage(80.20,BufferedImage.TYPE_INT_RGB);
        // get the image
        Graphics2D g = (Graphics2D) image.getGraphics(); / / pen
        // Set the background color of the image
        g.setColor(Color.white);
        g.fillRect(0.0.80.20);
        // Write data to the image
        g.setColor(Color.BLUE);
        g.setFont(new Font(null,Font.BOLD,20));
        g.drawString(makeNum(),0.20);

        // Tell the browser that the request is opened as an image
        resp.setContentType("image/jpeg");
        // The site has cache, do not let the browser cache
        resp.setDateHeader("expires", -1);
        resp.setHeader("Cache-Control"."no-cache");
        resp.setHeader("Pragma"."no-cache");

        // Write the image to the browser
        ImageIO.write(image,"jpg", resp.getOutputStream());

    }

    // Generate a random number
    private String makeNum(a){
        Random random = new Random();
        String num = random.nextInt(9999999) + "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 7-num.length() ; i++) {
            sb.append("0");
        }
        num = sb.toString() + num;
        return num;
    }


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

4. Implement redirection

After A Web resource B receives A request from client A, it notifies client A to access another Web resource C. This process is called redirection

Common scenarios:

  • The user login
void sendRedirect(String var1) throws IOException;
Copy the code

Testing:

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

    /* resp.setHeader("Location","/r/img"); resp.setStatus(302); * /
    resp.sendRedirect("/r/img");/ / redirection
}
Copy the code

Interview question: Can you talk about the difference between redirection and forwarding?

The same

  • The page jumps

The difference between

  • The URL does not change when a forward request is made
  • During redirection, the URL address bar changes.

5. Simply implement login redirection

< % - submit path here, the need to find the path of the project - % > < % - ${pageContext. Request. ContextPath} represents the current project - % > < 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>

Copy the code
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Process the request
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println(username+":"+password);

        // When redirecting, you must pay attention to the path, otherwise 404;
        resp.sendRedirect("/r/success.jsp");
    }

Copy the code
  <servlet>
    <servlet-name>requset</servlet-name>
    <servlet-class>com.kuang.servlet.RequestTest</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>requset</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
Copy the code
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>Success</h1>

</body>
</html>

Copy the code

6.7, it

HttpServletRequest represents the request of the client. The user accesses the server through Http protocol. All information in the Http request is encapsulated in HttpServletRequest.

Gets parameters and requests forwarding

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

    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");

    String username = req.getParameter("username");
    String password = req.getParameter("password");
    String[] hobbys = req.getParameterValues("hobbys");
    System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
    // The background receives Chinese garbled characters
    System.out.println(username);
    System.out.println(password);
    System.out.println(Arrays.toString(hobbys));
    System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = =");


    System.out.println(req.getContextPath());
    // Forward by request
    // The/here represents the current Web application
    req.getRequestDispatcher("/success.jsp").forward(req,resp);

}
Copy the code

Interview question: Can you talk about the difference between redirection and forwarding?

The same

  • The page jumps

The difference between

  • The URL does not change when a forward request is made
  • During redirection, the URL address bar changes. 302

7. Cookie and Session

7.1, session,

Session: a user opens a browser, clicks many hyperlinks, accesses several Web resources, and closes the browser. This process can be called a session.

Stateful conversation: a student has been in the classroom, and the next time we come in, we will know that the student has been in the classroom, and we call it stateful conversation;

How can you prove that you are a student of Xikai University?

You open

  1. Invoice west to give you the invoice
  2. The school’s west register says you checked in

A website. How do you prove you’ve been there?

Client Server

  1. The server sends a letter to the client. The next time the client visits the server, it can bring the letter. cookie
  2. Server registration you have come, the next time you come to me to match you; seesion

7.2. Two Techniques for Saving sessions

cookie

  • Client technology (response, request)

session

  • Server technology, with which the user’s session information can be saved? We can put information or data in Session!

Common common: website login, you do not need to log in the next time, the second visit directly up!

7.3, Cookie,

  1. Retrieve cookie information from the request
  2. The server responds to the client with a cookie
Cookie[] cookies = req.getCookies(); / / get a Cookie
cookie.getName(); // Get the key in the cookie
cookie.getValue(); // Get the vlaue in the cookie
new Cookie("lastLoginTime", System.currentTimeMillis()+""); // Create a cookie
cookie.setMaxAge(24*60*60); // Set the cookie validity period
resp.addCookie(cookie); // Responds to the client with a cookie
Copy the code

Cookie: generally, it is saved in the local user directory AppData.

Does a website cookie have an upper limit! Talk about the details

  • A Cookie can only hold one message;
  • A Web site can send multiple cookies to the browser and store up to 20 cookies.
  • Cookie size has a limit of 4KB;
  • Cookie browser cap of 300

Delete the Cookie;

  • If you do not set the validity period, close the browser and the browser automatically becomes invalid.
  • Set the validity period to 0.

Encoding and decoding:

URLEncoder.encode("Qin jiang"."utf-8")
URLDecoder.decode(cookie.getValue(),"UTF-8")
Copy the code

7.4 Session (key)

What is a Session?

  • The server creates a Seesion object for each user (browser);
  • A Seesion monopolizes a browser, and as long as the browser is not closed, the Session exists;
  • Once the user logs in, the entire site is accessible! –> Save user information; Save 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 (can save more than one)
  • Session Writes user data to the user-exclusive Session, which is saved on the server (saves important information and reduces the waste of server resources).
  • The Session object is created by the service;

Usage Scenarios:

  • Save a logged-in user’s information;
  • Shopping cart information;
  • Data that is commonly used throughout the site, we keep it in Session;

Use Session:

package com.kuang.servlet;

import com.kuang.pojo.Person;

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 {
        
        // Resolve garbled characters
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        
        / / get the Session
        HttpSession session = req.getSession();
        // Save something to Session
        session.setAttribute("name".new Person("Qin jiang".1));
        // Get the Session ID
        String sessionId = session.getId();

        // Check whether the Session is newly created
        if (session.isNew()){
            resp.getWriter().write(Session created successfully,ID:+sessionId);
        }else {
            resp.getWriter().write("Session exists on the server,ID:"+sessionId);
        }

        // What was done when the Session was created;
// Cookie cookie = new Cookie("JSESSIONID",sessionId);
// resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}/ / get the Session
HttpSession session = req.getSession();

Person person = (Person) session.getAttribute("name");

System.out.println(person.toString());

HttpSession session = req.getSession();
session.removeAttribute("name");
// Manually cancel the Session
session.invalidate();
Copy the code

Automatic session expiration: web.xml configuration

<! -- Set the default Session expiration time -->
<session-config>
    <! -- The Session expires automatically after 15 minutes.
    <session-timeout>15</session-timeout>
</session-config>
Copy the code

8, JSP

8.1. What is JSP

Java Server Pages: Java server-side Pages, also like servlets, for dynamic Web technologies!

The biggest features:

  • Writing JSP is like writing HTML
  • The difference between:
    • HTML only provides static data to the user
    • JAVA code can be embedded in JSP pages to provide dynamic data for users;

8.2 principle of JSP

JSP exactly how to execute!

  • There are no problems at the code level

  • Server internal work

    Tomcat has a work directory;

    IDEA uses Tomcat to produce a work directory in Tomcat for IDEA

    Address of my computer:

    C:\Users\Administrator\.IntelliJIdea20181.\system\tomcat\Unnamed_javaweb-session-cookie\work\Catalina\localhost\ROOT\org\apache\jsp
    Copy the code

    Found the page turned into a Java program!

When the browser sends a request to the server to access any resource, it is actually accessing a Servlet!

JSP will eventually be converted into a Java class too!

A JSP is essentially a Servlet

/ / initialization
  public void _jspInit(a) {}/ / destroy
  public void _jspDestroy(a) {}//JSPService
  public void _jspService(.HttpServletRequest request,HttpServletResponse response)
      
Copy the code
  1. Determine the request

  2. Built-in objects

    final javax.servlet.jsp.PageContext pageContext;  // Page context
    javax.servlet.http.HttpSession session = null;    //session
    final javax.servlet.ServletContext application;   //applicationContext
    final javax.servlet.ServletConfig config;         //config
    javax.servlet.jsp.JspWriter out = null;           //out
    final java.lang.Object page = this;               / / page: the current
    HttpServletRequest request                        / / request
    HttpServletResponse response                      / / response
    Copy the code
  3. The added code in front of the output page

    response.setContentType("text/html");       // Set the page type 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;
    Copy the code
  4. These objects can be used directly in JSP pages!

In the JSP page;

As long as the JAVA code will be output unchanged;

If it is HTML code, it is converted to:

out.write("<html>\r\n");
Copy the code

Such format, output to the front end!

8.3. JSP basic syntax

Any language has its own syntax. JAVA has it. JSP as an application of Java technology, it has some of its own expanded syntax (understand, know! Java all syntax support!

JSP expressions

< % - JSP expressions: used to program the output, the output to the client < % = variable or expression % > -- % > < % =new java.util.Date()%>
Copy the code

JSP script snippet

<%-- JSP script fragment --%> <%int sum = 0;
    for (int i = 1; i <=100 ; i++) {
      sum+=i;
    }
    out.println("<h1>Sum="+sum+"</h1>"); % >Copy the code

Re-implementation of script fragments

The < %int x = 10; out.println(x); %> <p> This is a JSP document </p> <%int y = 2; out.println(y); %> <hr> <%-- Embed HTML elements in code --%> <%for (int i = 0; i < 5; i++) {
  %>
    <h1>Hello,World  <%=i%> </h1>
  <%
    }
  %>
Copy the code

JSP declaration

The < %!static {
      System.out.println("Loading Servlet!");
    }

    private int globalVar = 0;

    public void kuang(a){
      System.out.println("Entered method Kuang!"); } % >Copy the code

JSP declarations: are compiled into JSP generated Java classes! Anything else will be generated in the _jspService method!

In JSP, embed Java code!

The < % % > < % = % > < %! %> <%-- comment --%>Copy the code

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

8.4. JSP instructions

The < %@pageargs.... % > < %@include file=""- % > < %@includeThe two pages are merged into one --%> <%@include file="common/header.jsp"%> <h1> Page body </h1> <%@include file="common/footer.jsp"%> <hr> <%--jSP tag jSP :include page, essentially three --%> < jSP :include page="/common/header.jsp"/> <h1> < JSP :include page="/common/footer.jsp"/>

Copy the code

8.5, 9 built-in objects

  • The PageContext save things
  • The Request to save things
  • Response
  • The Session to save things
  • Application [SerlvetContext] stores things
  • The config [SerlvetConfig]
  • out
  • Page, don’t understand
  • exception
pageContext.setAttribute("name1"."Qinjiang No.1"); // The saved data is only valid in one page
request.setAttribute("name2"."Qinjiang No.2"); // The saved data is only valid in one request, and the request forwarding carries this data
session.setAttribute("name3"."Qinjiang No. 3"); // The saved data is only valid for one session, from opening to closing the browser
application.setAttribute("name4"."Qinjiang No. 4");  // The saved data is only valid in the server, from opening to closing the server
Copy the code

Request: The client sends a request to the server. The generated data, such as news, is useless after the user finishes reading it.

Session: The client sends a request to the server, generating data that the user can use later, such as shopping cart;

Application: The client sends a request to the server. The data generated by the request is used up by one user and may be used by other users, such as chat data.

8.6. JSP tags, JSTL tags, EL expressions

<! -- JSTL expression dependencies -->
<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>

Copy the code

${}

  • To get the data
  • Perform operation
  • Get common objects for Web development

JSP tags

<%--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>
Copy the code

JSTL expression

The JSTL tag library is used to make up for the deficiency of HTML tags. It custom many tags, can be used by us, tag function and Java code!

Formatting label

SQL TAB

XML tags

Core Tags (Mastery)

JSTL label library usage steps

  • Import the corresponding taglib
  • Use one of the methods
  • JSTL packages need to be imported in Tomcat, otherwise an error will be reported: JSTL parsing error

C: if

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


<h4>ifTest </h4> <hr> <form action="coreif.jsp" method="get"${param. parameter name} --%> <input type="text" name="username" value="${param.username}">
    <input type="submit" value="Login"> </form> <%-- if the user name submitted is administrator, the login is successful --%> <c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="Welcome to the caretaker!"/>
</c:if> <%-- self-closing label --%> <c:out value="${isAdmin}"/>

</body>
Copy the code

c:choose c:when

<body> <%-- defines a variable score with a value of85--%>
<c:set var="score" value="55"/>

<c:choose>
    <c:when test="${score>=90}"<c:when test= <c:when test="${score>=80}"<c:when > <c:when test= <c:when test="${score>=70}"<c:when > <c:when test="${score<=60}"</c:when> </c:choose> </body>Copy the code

c:forEach

<%

    ArrayList<String> people = new ArrayList<>();
    people.add(0."Zhang");
    people.add(1."Bill");
    people.add(2."Fifty");
    people.add(3."Daisy");
    people.add(4."Tian six");
    request.setAttribute("list",people); - % > < %varBegin, where to start end, where to step, step size --%> <c:forEachvar="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>

Copy the code

9, JavaBean

Entity class

Javabeans are written in a specific way:

  • There must be a no-parameter construct
  • Attributes must be privatized
  • There must be corresponding get/set methods;

General used and database field mapping ORM;

ORM: Object relational mapping

  • Table – > class
  • Field –> Properties
  • Line record —-> object

People watch

id name age address
1 Qin jiang no. 1 3 Xi ‘an
2 Qin jiang no. 2 18 Xi ‘an
3 Qin jiang no. 3 100 Xi ‘an
class People{
    private int id;
    private String name;
    private int id;
    private String address;
}

class A{
    new People(1."Qinjiang No.1".3."Xi 'an");
    new People(2."Qinjiang No.2".3."Xi 'an");
    new People(3."Qinjiang No. 3".3."Xi 'an");
}
Copy the code
  • The filter
  • File upload
  • Mail delivery
  • JDBC Review: How to use JDBC, JDBC CRUD, JDBC transactions

10. MVC three-tier architecture

What is MVC: Model View Controller

10.1 the early years

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

Servlet --CRUD--> Database drawbacks: The program is bloated and not easy to maintain in servlet code: handle requests, responses, view jumps, HANDLE JDBC, handle business code, handle logic code architecture: there is nothing that can't be solved by adding another layer! Program apes call | | JDBC Mysql, Oracle is essentially...Copy the code

10.2. MVC three-tier architecture

Model

  • Business Processing: Business logic (Service)
  • Data Persistence Layer: CRUD (Dao)

View

  • Display data
  • Provide links to initiate Servlet requests (a, form, img…)

The Controller (Servlet)

  • Receiving requests from users: (REQ: request parameters, Session information… .).

  • Hand over the corresponding code to the business layer

  • Controls the jump of the view

    Login --> receive user login request --> process user request (obtain user login parameters, username, password) ----> hand over to the business layer to handle login business (determine whether the username and password is correct: transaction) -->Dao layer to query whether the username and password are correct --> databaseCopy the code

11. Filter (key point)

Filter: a Filter used to Filter data from a website.

  • Handle Chinese garbled characters
  • Login verification… .

Filter development steps:

  1. Guide package

  2. Writing filters

    1. Guide the package don’t go wrong

      Implement Filter interface, rewrite the corresponding method can be

      public class CharacterEncodingFilter implements Filter {
      
          // Initialize: the web server is started, and initialized, waiting for the filter object to appear!
          public void init(FilterConfig filterConfig) throws ServletException {
              System.out.println("CharacterEncodingFilter Initialization");
          }
      
          / / Chain: Chain
          /* all code in the filter is executed when filtering a specific request. The filter must continue along chain. DoFilter (request,response); * /
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              request.setCharacterEncoding("utf-8");
              response.setCharacterEncoding("utf-8");
              response.setContentType("text/html; charset=UTF-8");
      
              System.out.println("CharacterEncodingFilter before execution....");
              chain.doFilter(request,response); // Let our request continue, if not written, the program will be intercepted at this point stop!
              System.out.println("CharacterEncodingFilter after execution....");
          }
      
          // Destroy: The filter is destroyed when the Web server is down
          public void destroy(a) {
              System.out.println("CharacterEncodingFilter destroyed"); }}Copy the code
  3. Configure Filter in web. XML

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <! -- Any request for /servlet will pass through this filter -->
        <url-pattern>/servlet/*</url-pattern>
        <! --<url-pattern>/*</url-pattern>-->
    </filter-mapping>
    Copy the code

12. Listeners

Implement a listener interface; (There are N kinds)

  1. Write a listener

    Implement listener interface…

    // Count the number of online websites: count the number of sessions
    public class OnlineCountListener implements HttpSessionListener {
    
        // Create session listener: Watch your every move
        // This event is emitted 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 listeners
        // This event is emitted 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. Automatically destroy */
    }
    
    Copy the code
  2. Register listeners in web.xml

    <! -- Register listener -->
    <listener>
        <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
    </listener>
    Copy the code
  3. See if the situation is used!

13. Common applications of filters and listeners

Listener: Often used in GUI programming;

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

        frame.setBounds(300.300.500.500);
        frame.setBackground(new Color(0.0.255)); // Set the background color

        panel.setBounds(50.50.300.300);
        panel.setBackground(new Color(0.255.0)); // Set the background color

        frame.add(panel);

        frame.setVisible(true);

        // Listen on events, listen on closed events
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e); }}); }}Copy the code

Users can only access the home page after logging in! Users can not access the main page after logging out!

  1. Once the user logs in, the user’s data is added to Sesison

  2. To enter the home page to determine whether the user is logged in; Requirement: Implement in 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);
    Copy the code

14, JDBC

What is JDBC: Java connecting to a database!

Jar package support is required:

  • java.sql
  • javax.sql
  • Mysql – conneter – Java… Connect driver (must be imported)

Experimental environment construction

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.'Joe'.'123456'.'[email protected]'.'2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2.'bill'.'123456'.'[email protected]'.'2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3.'Cathy'.'123456'.'[email protected]'.'2000-01-01');


SELECT	* FROM users;

Copy the code

Importing database dependencies

<! -- Mysql driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
Copy the code

Connect to database in IDEA:

Fixed JDBC steps:

  1. The load driver
  2. Connects to the database, representing the database
  3. Statement: CRUD, the object that sends the SQL to the database
  4. Write SQL (different SQL by business)
  5. Execute SQL
  6. Close the connection
public class TestJdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // Configuration information
        //useUnicode=true&characterEncoding= UTF-8
        String url="jdbc:mysql://localhost:3306/jdbc? useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

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

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

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

        //5. Run the query SQL, return a ResultSet: ResultSet
        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 (do this)rs.close(); statement.close(); connection.close(); }}Copy the code

Precompiled SQL

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

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

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

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

        preparedStatement.setInt(1.2);// Give the first placeholder? Is assigned to 1;
        preparedStatement.setString(2."Crazy God says Java.");// For the second placeholder? The value assigned to the crazy god said Java;
        preparedStatement.setString(3."123456");// For the third placeholder? Is assigned the value 123456;
        preparedStatement.setString(4."[email protected]");// For the fourth placeholder? Is assigned to 1;
        preparedStatement.setDate(5.new Date(new java.util.Date().getTime()));// Give the fifth placeholder? Assigns the value to 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 (do this)preparedStatement.close(); connection.close(); }}Copy the code

The transaction

It’s all or nothing!

ACID Principle: Ensure data security.

Rollback () Close transaction transfer: A:1000
B:1000
    
A(900) -100-->   B(1100) 
Copy the code

Junit unit tests

Rely on

<! -- Unit tests -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
Copy the code

Simple to use

The @test annotation is valid only for methods, as long as the annotated method is run directly!

@Test
public void test(a){
    System.out.println("Hello");
}
Copy the code

Red when it fails:

Set up 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);
Copy the code
    @Test
    public void test(a) {
        // Configuration information
        //useUnicode=true&characterEncoding= UTF-8
        String url="jdbc:mysql://localhost:3306/jdbc? useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        Connection connection = null;

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

            //3. Tell the database to enable transaction. False enable transaction
            connection.setAutoCommit(false);

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

            // make an error
            //int i = 1/0;

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

            connection.commit();SQL > commit transaction;
            System.out.println("success");
        } catch (Exception e) {
            try {
                // If an exception occurs, the database is notified to roll back the transaction
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            } catch(SQLException e) { e.printStackTrace(); }}}Copy the code