JavaWeb

Split into Java (language) Web (Web page)

1 Basic Concepts

1.1 introduction

Java Web, is to use Java technology to solve the relevant Web Internet domain technology stack. The Web consists of a Web server and a Web client. Java applications on the client side have Java applets, but they are rarely used. **Java applications on the server side are very rich, such as servlets, JSPS, third-party frameworks, and so on. **Java technology has given a powerful impetus to the development of the Web.

Web development:

  • Web, meaning web page, www.baidu.com
  • Static Web resources (such as HTML pages)
    • html, css
    • The data in a Web page for people to browse is always the same
  • Dynamic Web Resources
    • Taobao, almost all websites
    • The data in the Web page for people to browse is generated by the program, and the content of the Web page is different at different points in time
    • Technology stack: JSP/ Servlet, ASP, PHP, JavaScript

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


1.2 Web Applications

Web applications: programs that can be accessed by a browser

  • a.html, b.html…… Multiple Web resources that can be accessed by the outside world and provide services to the outside world
  • Any page or resource accessed exists on a computer somewhere in the world
  • Providing urls externally (Uniform Resource Locator)
  • The unified Web resource is placed in the same folder, Web Applications (dependent)–>Tomcat: Server
  • A Web application consists of several parts (static Web, dynamic Web)
    • html, css
    • jsp, servlet
    • Java program
    • The jar package
    • Configuration file (Properties)
    • Once a Web application is written, you want to make it accessible to the outside world: you need a server to centrally manage it

1.3 static web

*.html, etc. These are suffixes for web pages, and if these things are always on the server, we can just read them

  • Disadvantages of the static Web
    • The Web page cannot be dynamically updated, and all users see the same page
      • Rotation map, click effects (pseudo dynamic)
      • JavaScript
    • It can’t interact with the database (data can’t be persisted, users can’t interact)

1.4 dynamic web

Pages are displayed dynamically: “Web pages are displayed differently from person to person”

Disadvantages:

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

Advantages:

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

2 Web Server

2.1 Technical Explanation

ASP

  • Microsoft: the earliest domestic popularity is ASP
  • Embedded in HTML VB script, ASP+COM;
  • In ASP development, basically a page

PHP:

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

JSP/Servlet:

B/S: browser and server

C/S: client and server

  • Sun’s B/S architecture
  • Java language-based
  • Can host the effects of three high (high concurrency, high performance, high availability) problem proxies
  • Syntax like ASP, ASP–>JSP

2.2 Web Server

Web servers can handle requests from Web clients such as browsers and return corresponding responses. They can also place web files for the world to browse. You can place data files for the world to download.

IIS

Microsoft’s; ASP, Windows

Tomcat

Tomcat is a core project of the Apache Software Foundation’s Jakarta project, developed by Apache, Sun, and other companies and individuals. With Sun’s involvement and support, the latest Servlet and JSP specifications are always present in Tomcat. 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 beginner, the best choice

Tomcat actually runs JSP pages and servlets

.

3 years experience, can try to write Tomcat server;


3 Tomcat

3.1 a Tomcat installation

Download Tomcat:

  1. Install or unpack
  2. Learn about configuration files and structure directories
  3. The role of products

As shown above, the JDK directory, the loading mechanism of Java = = > rt. The jars in the lib folder


  • Download the installation package or compressed package from the official website

  • Take a look at the Tomcat structure directory


3.2 Starting and Configuring Tomcat

  • The script starts, as shown below:

Default localhost:8080Tomcat can be turned off with shutdown.bat

  • Server core configuration file

You can configure the boot port number

  • The default tomcat port number is 8080

  • mysql: 3306

  • http: 80

  • https: 443

  • <Connector port="8080" 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

You can change the localhost domain name

After changing the domain name of the file, change the domain name host-name in the Tomcat configuration file

Difficult interview questions

Can you 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.0.1        www.zisu.com
    Copy the code
    1. No: go to DNS

3. You can configure environment variables (optional)

3.3 Publishing a Web site

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

The structure your website should have

-root -zisu: specifies the directory name of the website. -WEB-INF -classes: specifies the Java program. -lib: specifies the JAR package that the Web application depends on. Site profile -index.html: default home page -static
            -css
            	-style.css
            -js
            -img
        -......
Copy the code

4 HTTP

4.1 What is HTTP

Hypertext Transfer Protocol (HTTP) is a simple request-response Protocol that usually runs on top of TCP. It specifies what messages the client might send to the server and what responses it might get.

  • Text: HTML, string……
  • Hypertext: images, music, videos, maps……
  • Default port: 80

HTTPS: safe

  • Default port: 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 access multiple Web resources after connecting to the Web server

4.3 the Http request

  • Client === send request ===> 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. Address36.15244.96.:443
Referrer Policy: strict-origin-when-cross-origin
Copy the code
Accept: text/html Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: www.baidu.com
Copy the code
  1. The request line
    1. Request in the request line: GET
    2. GET, POST, HEAD, DELETE, and TRACT……
      1. 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
      2. Post: There is no limit on the number of parameters or size that can be carried by a request. Data content will not be displayed in the URL bar of the browser, which is secure and inefficient
  2. The message header
Accept Supported data type Accept-encoding Supported Encoding format GBK UTF-8  ISO8859-1Accept-language Language environment cache-Control Cache Control Connection Whether to disconnect or hold the Host after the request is completeCopy the code

4.4 the Http response

  • Server === response ===> client

Baidu:

Cache-Control: privateConnection: keep-alive Content-Encoding: gzip Content-Type: text/html; charset=utf-8
Date: Wed, 19 May 2021 09:05:37 GMT
Expires: Wed, 19 May 2021 09:05:37 GMT
Copy the code
  1. Response body
Accept Supported data type Accept-encoding Supported Encoding format GBK UTF-8  ISO8859-1Accept-language Cache-Control Cache Control Connection Whether the request is disconnected or kept Host Host Refresh How often it is refreshed Location Repositions the web pageCopy the code
  1. Status code
    1. 200: The request response succeeded
    2. 3xx: Request redirection
    3. 404: Resource not found
    4. 5xx: Server code 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 learn this technique

  1. In Javaweb development, we need to use a large number of jar packages that we have to import
  2. Maven automatically imports and configures jar packages

5.1 Maven Project Architecture Management tool

Maven’s core idea: Conventions outweigh configurations

  • There are constraints, don’t break them

Maven dictates how you write Java code. Must you follow this specification

5.2 Downloading and Installing Maven

Website: maven.apache.org

When the download is complete, unzip it

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

Check whether Maven is successfully installed. Ensure that the configuration is complete

5.4 Ali Cloud Image

  • Mirror: mirrors
    • Effect: Speed up the download of required JAR packages
  • Domestic recommendation 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

At a local warehouse, and a remote one

Create a localRepository with the setting file localRepository in the configuration folder

<localRepository>/path/to/local/repo</localRepository>
Copy the code

5.6 Using Maven in IDEA


5.6.1 Configuring Maven globally in IDEA

# Emergency patch #

Configure Maven globally in IDEA

5.6.2 the body

# # text

  1. Start the IDEA
  2. Create a Maven project

3. The first time you create a Maven project, you will download a lot of JARS4. The project is set up successfully6. Check maven configuration in IDEA after the project is successfully created

7. ok

5.7 Creating a Project Without a Template

Hand build directory

Mark the created folder as an available directory

5.8 Project Structure configuration (Project Structure…)

It can also be configured using a project structure

Click in to configure

5.9 Configuring Tomcat in IDEA

When you do not have artifacts, you can click Fix to add them, or you can build the configuration from the project

  • This is a Maven project with templates

  • This is the Template-free Maven project
  • Note: no template is not the home page index.jsp, manually add, watch the directory structure and web-INF layer below

5.10 the pom. The XML 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>

  <! -- Config GAV -->
  <groupId>com.zisu</groupId>
  <artifactId>javaweb-01-maven</artifactId>
  <version>1.0 the SNAPSHOT</version>

  <! -- Package: how the project is packaged -->
  <! -- jar: Java application -->
  <! -- war: Java Web 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>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <! -- Deleteable -->
  <build>
  </build>
</project>
Copy the code

5.101 Configure Resources in build


    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
Copy the code

5.11 structure tree


6 Servlet

6.1 introduction of the Servlet

Server applets (Servlets) are short for Java servlets. They are called small service programs or service connectors. Server-side programs written in Java are platform – and protocol-independent and can interactively browse and generate data and generate dynamic Web content.

A Servlet narrowly refers to an interface implemented by the Java language, and a Servlet broadly refers to any class that implements this Servlet interface

  • Servlets are one of sun’s technologies for developing the dynamic Web
  • Sun provides an interface to these apis called Servlets. If you want to develop a Servlet application, there are only two 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 HellowServlet

Write a Servlet applet

  1. Create a Maven parent project without selecting a template, and remove the SRC that is not needed. The core is POM.xml

  2. Import servlet and JSP dependencies in the parent project’s POM file

  3. <! -- Servlet dependencies -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <! -- JSP dependencies -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
    </dependency>
    Copy the code
  4. The child project can inherit the parent project’s dependencies. Next, create a Web template module(child project).

  5. When a child Module is created, a tag appears in its POM file

  6.     <modules>
            <module>servlet-01</module>
        </modules>
    Copy the code
  7. The corresponding parent project poM file will also have the corresponding tag (all three elements must have), remember that if not, you can add it manually

  8.   <parent>
        <! -- Location of parent project -->
        <groupId>com.sama</groupId>
        <artifactId>javaweb-02-servlet</artifactId>
        <version>1.0 the SNAPSHOT</version>
      </parent>
    Copy the code
  9. Create maven directory resources, com.sama.xxxx under Java

  10. Next, configure the Tomcat server, keeping in mind that there are two steps

    • Create a new server configuration
    • Resolve no artifacts issues
    • It is important to note that after adding artifacts, the default access path is changed to the desired default
  11. With everything configured, it’s time to write our servlet

  12. First analysis:

    1. Servlet is an interface, but there are also two classes that implement it in the source code, the one known as HttpServlet

    2. The problem here is that a child project that wants to inherit the parent project’s dependencies can add dependencies without adding versions

    3. All submodules that want to use the jar declared in this module need to add the corresponding groupId and artifactId to the submodule without declaring the version number. Note that this is a dependency declaration, not a real download JAR. Dependencies will only be downloaded if they are used in child modules.

    4. <! -- Added parent project -->
      <dependencyManagement></dependencyManagement>
      <! -- Subproject references Servlet dependencies -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
      </dependency>
      
      Copy the code
    5. Create a class that inherits HttpServlet first and then look at the source code

      1. Jakarta EE 9, which marks the final transition from the Javax.* namespace to Eclipse’s Jakarta.*, updates all apis to use Jakarta.* in package names.
      2. So the dependency I referenced is no longer available, in version 10.0 of Tomcat, the package name in servlet-api.jar has been changed to jakart.servlet
    6. We import the Servlet dependencies that work

    7. <! -- Tomcat-servlet-API: This is the latest servlet package -->
      <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-servlet-api</artifactId>
          <version>10.0.6</version>
      </dependency>
      Copy the code
    8. Now you can inherit HttpServlet, look at its source code

      1. // It is an abstract class and inherits GenericServlet
        public abstract class HttpServlet extends GenericServlet {}Copy the code
      2. The HttpServlet then goes to GenericServlet

      3. // It is an abstract class and implements servlets, ServletConfig, Serializable
        public abstract class GenericServlet implements Servlet.ServletConfig.Serializable {}
        Copy the code
      4. GenericServlet then enters the Servlet

      5. // It is an interface and has four methods, which are also its lifecycle
        public interface Servlet {
            / / initialization
            void init(ServletConfig var1) throws ServletException;
        
            ServletConfig getServletConfig(a);
        
            // Service (core)
            void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
        
            // Get information
            String getServletInfo(a);
        
            / / destroy
            void destroy(a);
        }
        Copy the code
      6. Return to GenericServlet and see how the service method was implemented

      7. So go back to the HttpServlet and look at the Service method

      8. Notice what kind of method is it, and then call the corresponding method

      9. It has several default implementations, doGet(), doPost()…… Let’s just rewrite the methods that we need

    9. Let’s figure out the general structure of the servlet

  13. Now that the analysis is complete, we can write our servlet and override doGet(), doPost()

  14. public class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // Define the content format
            resp.setContentType("text/html");
            // Define the encoding format
            resp.setCharacterEncoding("utf-8");
            // Get the output stream
            //ServletOutputStream outputStream = resp.getOutputStream();
            PrintWriter out = resp.getWriter();
            out.write("<html>");
            out.write("<head>");
            out.write("<title>");
            out.write("zisusama");
            out.write("</title>");
            out.write("</head>");
            out.write("<body>");
            out.write("<h1>");
            out.write("Lord Zisu!");
            out.write("</h1>");
            out.write("</body>");
            out.write("</html>");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
  15. After writing the servlet, remember to register with web.xml and write the mapping for the servlet

    • Why do we need mapping: We are writing a Java program, but we need to access it through a browser, and the browser needs to connect to a Web server, so we need to register our Servlet in the Web service and give it a path that the browser can access
  16. 
      <servlet>
        <servlet-name>hello-servlet</servlet-name>
        <servlet-class>com.sama.servlet.HelloServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>hello-servlet</servlet-name>
        <url-pattern>/hw</url-pattern>
      </servlet-mapping>
    Copy the code
  17. All right, register, start the server, see if Lord Zisu’s here yet? (low low ◡)

  18. Scatter the flowers

6.3 the Servlet principle

6.4 the Mapping problem

1. Exact path matching. Example: For example, if the url-pattern of a servletA is /test and the url-pattern of a servletB is /*, if the URL I visited is http://localhost/test, the container will match the exact path first. If /test is exactly matched by servletA, the servletA is called and the other servlets are ignored.

2. The longest path matches. Example: The url-pattern of servletA is /test/, while the url-pattern of servletB is /test/a/. When accessing http://localhost/test/a, the container will select the servlet with the longest path to match. So servletB here.

3. Extension matching. If the last section of the URL contains an extension, the container will select the appropriate servlet based on the extension. Example: url-pattern for servletA: *.action

4. If none of the previous three rules finds a servlet, the container selects the requested resource based on the URL. If the application defines a default servlet, the container throws the request to the default servlet (what is a default servlet? More on that later).

What is a Default servlet

  • First, all requests entering Tomcat will flow through the servlet, and if there is no match for any application-specific servlet, it will flow to the default servlet.
  • The default servlet is configured in $CATALina /conf/web.xml.
  • Some of the application’s static resources can be handed over to this servlet to reduce server stress and save resources!

6.5 Servlet life cycle

Each Servlet runs following the following lifecycle:

  1. createServletInstance.
  2. WebContainer callsServlettheinit()Methods,ServletInitialize.
  3. ServletAfter initialization, will always exist in the container, used to respond to client requests if the client sendsGETRequest, container callServletthedoGet()Method to process and respond to requests; If the client sendsPOSTRequest, container callServlet* the doPost ()Method to process and respond to requests. Or all of themThe service()* method is handled in response to user requests.
  4. WebThe container decides to destroyServletIs called firstServletthedestory()Method, usually in closeWebIn-application destructionServletThe instance

6.6 the ServletContext

1 Sharing Data

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

  • Sharing Data The data I saved to the ServletContext in this Servlet is available in the other Servlet

Write an example:

  1. Create a new subproject and modify Tomcat, adding only artifacts for the new Module

  2. To complete the directory structure of the project, start writing a servlet that stores things to the ServletContext: HelloServlet

  3. public class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // Get the ServletContext object
            ServletContext context = this.getServletContext();
            String info = "Lord Zisu manifest!";
            // Put info into the ServletContext
            context.setAttribute("info",info); }}Copy the code
  4. Let’s write another servlet that fetches things from the ServletContext: GetServlet

  5. public class GetServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // Get the ServletContext object
            ServletContext context = this.getServletContext();
            String info = (String) context.getAttribute("info");
    
            // Output what you get
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            PrintWriter out = resp.getWriter();
            out.write("Meow, meow, meow."+info); }}Copy the code
  6. After the two servlets are written, go to web.xml to register and add the mapping

  7.  <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/h</url-pattern>
      </servlet-mapping>
       
      <servlet>
        <servlet-name>getInfo</servlet-name>
        <servlet-class>com.sama.servlet.GetServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>getInfo</servlet-name>
        <url-pattern>/getInfo</url-pattern>
      </servlet-mapping>
    Copy the code

2 Obtain the initialization parameters

There is a getInitParameter() method in ServletContext that gets the initialization value of web.xml

  1. Start by creating a new servlet to get the initialization parameters: getInitParamServlet

  2. public class getInitParamServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // Get the ServletContext object
            ServletContext context = this.getServletContext();
            String param = context.getInitParameter("mysql");
    
            / / output
            resp.getWriter().write("Initialization parameter:"+param); }}Copy the code
  3. Write an arbitrary context parameter in web.xml and read it as a key-value pair

  4.   <context-param>
        <param-name>mysql</param-name>
        <param-value>jdbc:mysql://localhost:sama</param-value>
      </context-param>
    Copy the code
  5. Write the servlet registration and mapping in web.xml

  6.   <servlet>
        <servlet-name>getParam</servlet-name>
        <servlet-class>com.sama.servlet.GetInitParamServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>getParam</servlet-name>
        <url-pattern>/getParam</url-pattern>
      </servlet-mapping>
    Copy the code
  7. Just test it out

3 Request Forwarding

There is a getRequestDispatcher(” URL “) method in the ServletContext that can be forwarded to the page in the specified path

  1. First create a new servlet to forward to the page at the specified path: DispatcherToInitServlet

  2. public class DispatcherToInitServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //ServletContext object
            ServletContext context = this.getServletContext();
            // Request a forwarding object
            RequestDispatcher requestDispatcher = context.getRequestDispatcher("/getParam");// Schedule the path to this page
            requestDispatcher.forward(req, resp);// Forward to place the request and response in}}Copy the code
  3. Write the servlet registration and mapping in web.xml

  4.  <servlet>
        <servlet-name>goParam</servlet-name>
        <servlet-class>com.sama.servlet.DispatcherToInitServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>goParam</servlet-name>
        <url-pattern>/goParam</url-pattern>
      </servlet-mapping>
    Copy the code
  5. Start the test and successfully analyze the process

4 Read the resource file

There is a **getResourceAsStream(” relative path of resource “)** method in ServletContext, which converts the resource file to the desired stream

  1. New properties

    1. Create properties under the Java directory

    2. fileName=javaProp
      author=susama
      Copy the code
    3. Create new Properties under the Resources directory

    4. fileName=resProp
      author=susama
      Copy the code
  2. But how do we find the path of these two files after publication?

    1. Target is the war package generated by maven after publication. You can find the desired path here

    2. Use maven’s command line to clean it up

    3. After clearing, we find that the Target package has disappeared, and we restart the project to see if the new target contains the properties we wrote

    4. We found only one load, indicating that one load failed, indicating that no relevant read configuration was added to build in our pom. XML file

    5. We add the relevant configuration

    6. <resources>
          <resource>
              <directory>src/main/resources</directory>
              <includes>
                  <include>**/*.properties</include>
                  <include>**/*.xml</include>
              </includes>
              <filtering>false</filtering>
          </resource>
          <resource>
              <directory>src/main/java</directory>
              <includes>
                  <include>**/*.properties</include>
                  <include>**/*.xml</include>
              </includes>
              <filtering>false</filtering>
          </resource>
      </resources>
      
      Copy the code
    7. Clean and start again, and then look at the path to the properties file

    8. Write the corresponding servlet that reads these files: getPropServlet

    9. public class getPropServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              ServletContext context = this.getServletContext();
              // Properties file in Java directory
              InputStream javaStream = context.getResourceAsStream("/WEB-INF/classes/com/sam/servlet/javaProp.properties");
              // Properties file in the resources directory
              InputStream resStream = context.getResourceAsStream("/WEB-INF/classes/resProp.properties");
      
              // Use the Properties class to receive
              Properties javaProp = new Properties();
              javaProp.load(javaStream);
              String fileName1 = javaProp.getProperty("fileName");
              String author1 = javaProp.getProperty("author");
      
              Properties resProp = new Properties();
              javaProp.load(resStream);
              resProp.getProperty("");
              String fileName2 = javaProp.getProperty("fileName");
              String author2 = javaProp.getProperty("author");
      
              / / output
              PrintWriter out = resp.getWriter();
              out.write(fileName1+":"+author1+","+fileName2+":"+author2+"res#"); }}Copy the code
    10. / web-inf: / web-inf: / web-inf: / web-inf: / web-inf: / web-inf: / web-inf: / web-inf: / web-inf: / web-inf

    11. Write the servlet registration and mapping in web.xml

    12.   <servlet>
          <servlet-name>goProp</servlet-name>
          <servlet-class>com.sama.servlet.GetPropServlet</servlet-class>
        </servlet>
        <servlet-mapping>
          <servlet-name>goProp</servlet-name>
          <url-pattern>/goProp</url-pattern>
        </servlet-mapping>
      Copy the code
    13. Discovery: Project releases are packaged into the same path in Target: classes, commonly known as classpath

    14. The test is complete

5 HttpServletResponse

The Web server receives an HTTP request from the client and for this request creates an HttpServletRequest object representing the request

An HttpServletResponse object that represents the response

  • To get the parameters requested by the client: look for HttpServletRequest, which implements the ServletRequest interface
  • If you want to give the client response some information: look for HttpServletResponse, which implements the ServletResponse interface
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 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
2 Downloading Files
  1. Output a message to the browser

  2. The download file

    1. Gets the path to the file

    2. Download file name

    3. Set your browser to support downloads

    4. Gets the input stream for the downloaded file

    5. Creating a buffer

    6. Get the OutputStream object

    7. Write the FileOutputStream stream to the buffer buffer, and use the OutputStream to output the data in the buffer to the client

    8. public class FileServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              //1. Obtain the file path
              String realPath = this.getServletContext().getRealPath("/ WEB - INF/classes/meow. PNG");
              System.out.println("File path:"+realPath);
              //2. Obtain the file name of the download
              String fileName = realPath.substring(realPath.lastIndexOf("\ \") +1);
              (" content-disposition ","attachment; Filename ") can be downloaded
              resp.setHeader("Content-Disposition"."attachment; filename="+ 
                      // The Chinese name file will also display normally
                      URLEncoder.encode(fileName,"UTF-8"));
              //4. Get the input stream for the downloaded file
              FileInputStream inputStream = new FileInputStream(realPath);
              //5. Create buffer
              int len = 0;
              byte[] buffer = new byte[1024*8];
              //6. Get the OutputStream object
              ServletOutputStream outputStream = resp.getOutputStream();
              //7. Read the FileInputStream into the buffer and output the data in the buffer to the client using OutputStream
              while((len=inputStream.read(buffer))! = -1){
                  outputStream.write(buffer,0,len);
              }
              
              / / close the flowinputStream.close(); outputStream.close(); }}Copy the code
    9. Register the servlet and start the test

    10. There is a problem. When writing the path, the file name is wrong. It took a long time to find it

    11. Input stream reads are put into the buffer

6 HttpServletRequest

1 Obtain parameters passed by the front-end
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        / / code
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        // Get parameters
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobbies = req.getParameterValues("hobbies");

        HttpSession session = req.getSession();
        session.setAttribute("username", username);

        / / jump
        req.getRequestDispatcher("/success.jsp").forward(req,resp); }}Copy the code
  • Notice here that there are two ways to get parameters
2 Request Forwarding
request.getRequestDispatcher("/success.jsp").forward(req,resp);
Copy the code
  • **”/”** this symbol represents the project root path in the forward, nothing more
3. Interview question: The difference between forwarding and redirecting

7 Session, Cookie,

7.1 Session(Session)

The session

  • Session: Called Session control. The Session object stores properties and configuration information required for a specific user Session.

  • Variables stored in the Session object are not lost when the user jumps between Web pages of the application. When a user requests a Web page from an application, the Web server automatically creates a Session object if the user does not already have a Session. When a session expires or is abandoned, the server terminates the session.

  • Note that session state is reserved only in browsers that support cookies.

Stateful session

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 to match you; session

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? You can put information or data in a session

Common scenario: After logging in to a website, you do not have to log in again for a short period of time

7.3 the Cookie

public class CookieDemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// First access to the tag
        boolean flag = false;
        // Encode and format
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        // Date formatting tool object
        DateFormat dateFormat = new SimpleDateFormat();

        / / the output stream
        PrintWriter out = resp.getWriter();
        // Get cookies from the request
        Cookie[] cookies = req.getCookies();
        // Iterate to get the login time we saved
        for (Cookie cookie : cookies) {
            if("lastLoginTime".equals(cookie.getName())){
                // Change the first access tag and optimize it
                if(! flag){flag =true; }long time = Long.parseLong(cookie.getValue());
                Date date = new Date(time);
                out.write("When was your last visit:"+ dateFormat.format(date)); }}// If our flag is not changed, it is the first time to visit
        if(! flag){ out.write("This is your first visit. Welcome to the Dark Night group.");
        }

        // Create a cookie to store the current time
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        // Set the cookie validity period to 7 days
        cookie.setMaxAge(7*24*60*60);
        // Put the cookie in response
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
  • It can be used when transmitting Chinese

    • URLEncoder.encode(“info”,”UTF-8″); Transmission encryption

    • URLDecoder.decode(“info”,”UTF-8″); Access to decrypt

7.4 Session(Key)

  • Session: Called Session control. The Session object stores properties and configuration information required for a specific user Session.

  • Variables stored in the Session object are not lost when the user jumps between Web pages of the application. When a user requests a Web page from an application, the Web server automatically creates a Session object if the user does not already have a Session. When a session expires or is abandoned, the server terminates the session.

  • Note that session state is reserved only in browsers that support cookies.

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 the user’s data to the user Session and saves it on the server (saves important information and reduces the waste of server resources).
  • The Session object is created by the server

Usage Scenarios:

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

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 introduction

Java Server Pages: Java server-side Pages, like servlets, for dynamic Web development

  • // Write the original page
    public class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // Define the content format
            resp.setContentType("text/html");
            // Define the encoding format
            resp.setCharacterEncoding("utf-8");
            // Get the output stream
            //ServletOutputStream outputStream = resp.getOutputStream();
            PrintWriter out = resp.getWriter();
            out.write("<html>");
            out.write("<head>");
            out.write("<title>");
            out.write("zisusama");
            out.write("</title>");
            out.write("</head>");
            out.write("<body>");
            out.write("<h1>");
            out.write("Lord Zisu!");
            out.write("</h1>");
            out.write("</body>");
            out.write("</html>");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
  • And writing JSP is like writing HTML, convenient and simple

  • The difference between JSP and HTML

    • HTML only provides static data
    • JSP pages can be embedded in Java code, you can achieve the provision of dynamic data

8.2 the JSP principle