JavaWeb (continuously updated) learning resources come from Crazy God of station B

JavaWeb

1. Basic concepts

1.1 Preface

web development:

  • Web, the meaning of web page
  • Static web
    • html,css
    • The data provided to people will never change
  • Dynamic web
    • Taobao, almost all websites;
    • The data provided will always change
    • Technology stack: Serverlet, JSP, ASP, PHP

In Java, the technology of dynamic web resource development is collectively referred to as Javaweb;

1.2. web application

web application: a program that can provide browser access;

  • a.html, b.html... Multiple web resources that can be accessed by the outside world;
  • Any page and resource that can be accessed exist on a computer in a corner of the world;
  • URL
  • The agreed web resource will be placed in the same folder, web application – > Tomcat: server
  • A web application consists of many parts
    • HTML,css,js
    • jsp,servlet
    • java program
    • jar package
    • Configuration file (properties)

After the web application is written, if you want to provide external access: you need a server to manage it uniformly;

1.3. Static web

  • *. HTML and *. HTM are suffixes of web pages. If they always exist on the server, they can be read.

  • shortcoming

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

1.4 dynamic web

The page will display dynamically: "the small shadow displayed on the web page varies from person to person";

Disadvantages:

  • There is an error in the dynamic web resource added to the server. You need to rewrite the back-end program

advantage:

  • Dynamic update of web pages
  • Can interact with database

2. web server

2.1 technical explanation

ASP

  • Microsoft: the earliest popular in China;
  • Embedded VB script in HTML, ASP+C;
  • In ASP development, a page has thousands of lines of business logic code, and the page is extremely chaotic
  • High maintenance cost
  • C#
  • IIS

PHP

  • Fast development speed, powerful function, cross platform and simple code
  • Unable to carry large traffic (limitations)

JSP/Servlet

B/S: browser and server

C/S: client and server

  • B/S architecture mainly promoted by sun company
  • Based on java language (all large companies or some open source components are written in java)
  • It can bear the impact of the three high problems
  • The syntax is like ASP,

2.2. web server

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

IIS

Microsoft's; ASP... Built in windows

Tomcat

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-MfKFiPN5-1630979020795)(D: / software / typora / pictures / image-20210722153547075. PNG)]

Tomcat is a core project of the Jakarta project of the Apache Software Foundation. The latest Servlet and JSP specifications can always be reflected in Tomcat. Tomcat 5 supports the latest Servlet 2.4 and JSP 2.0 specifications. Because Tomcat technology is advanced, stable and free, it is loved by Java enthusiasts and has been recognized by some software developers. It has become a popular Web application server.

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

Tomcat actually runs JSP pages and servlets. At present, the latest version of Tomcat is 10.0.5.

Download Tomcat:

  1. Install or unzip
  2. Understand the configuration file and directory structure
  3. Understanding role

3,Tomcat

3.1. Installing Tomcat

Official website: https://tomcat.apache.org/

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-BN4G1xLZ-1630979020799)(D: / software / typora / pictures / image-20210722154617440. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG gnyjjtk5-1630979020800) (D: / software / typora / pictures / image-20210722154732688. PNG)]

3.2. Tomcat startup and configuration

What folders do:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zJoFV3Kn-1630979020802)(D: / software / typora / pictures / image-20210722155310804. PNG)]

Starting and shutting down Tomcat

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-kn0Eu8Gd-1630979020803)(D: / software / typera / pictures / image-20210722155621601. PNG)]

Possible problems:

  1. Java environment variables are not configured
  2. Flashback problem: compatibility setting required
  3. Garbled code problem: set in the configuration file

3.3 configuration

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-OoeI19NJ-1630979020805)(D: / software / typera / pictures / image-20210722155933809. PNG)]

You can configure the port number for startup

  • Tomcat default port number: 8080
  • mysql default port number: 3306
  • http: 80
  • HTTPS: 443
 <Connector port="9999" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

You can configure the name of the host

  • Default host name: localhost -- > 127.0.1
  • The default site app location is webapps
Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

Difficult interview questions:

How do you visit the website?

  1. Enter a domain name; enter
  2. Check whether there is domain name mapping under the local configuration file
    • Yes: directly return the corresponding IP address
    • No, go to the DNS server

3.4. Publish a web site

  • You can access the website written by yourself by putting it under the specified web Applications folder (webapps) in the server (Tomcat)

The structure that a website should have

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

4,HTTP

4.1. What is HTTP

Hypertext Transfer Protocol (HTTP) is a simple request response protocol, which usually runs on TCP above.

  • Text: html, string
  • Hypertext: picture, music, video, location, map
  • 80

https: Secure

  • 443

4.2 two times

  • http1.0
    • http/1.0: the client can connect to the web server. Only one web resource can be obtained. Disconnect
  • http2.0
    • http/1.1: the client can connect to the web server and obtain multiple web resources

4.3 http request

  • Client – Request – server

4.3.1 request line

  • Request method in request line: Get
  • Request method: Get, Post
    • get: the request can carry fewer parameters and is limited in size. The data content will be displayed at the URL address of the browser. It is unsafe but efficient
    • post: parameters are not limited, size is not limited, content is not displayed, safe but not efficient

4.3.2 request header

  • Accept: tells the browser the supported data types
  • Accept encoding: encoding format
  • Accept language: locale
  • Cache control: cache control
  • ...

4.4 http response

  • Server – Response – client

4.4.1 responder

  • Accept: tells the browser the supported data types
  • Accept encoding: encoding format
  • Accept language: locale
  • Cache control: cache control
  • Refresh: tells the client how long to refresh
  • Location: reposition the web page

4.4.2 response status code

200: request response succeeded

3XX: request redirection

  • Redirect: to the specified new location

404: resource not found

5XX: server code error

Common interview questions:

When you enter the address in the address bar of your browser and press enter, the page can show what happened back?

5,Maven

Why study?

  1. In Java Web development, a large number of jar packages are needed;

  2. How to make something automatically help us import and configure jar packages;

    Thus, maven was born!

5.1 Maven project architecture management tool

We are currently using to import jar packages

Maven's core idea: Convention is greater than configuration

  • Don't break the constraint.

Maven will specify how to write Java code, which must be in accordance with the specification;

5.2 downloading and installing Maven

Maven official website: https://maven.apache.org/

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RNosS6bw-1630979020805)(D: / software / typera / pictures / image-2021072217524785. PNG)]

After downloading, unzip it;

5.3 configuring environment variables

In our system environment variable

The configuration is as follows:

  • M2_HOME: bin directory under maven directory
  • MAVEN_HOME: maven installation directory
  • Configure% Maven in the path of the system_ HOME%\bin

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-YnBg7T2o-1630979020806)(D: / software / typera / pictures / image-20210722180044479. PNG)]

Test whether Maven is installed successfully and ensure that the configuration must be completed!

5.4 modifying alicloud images

  • Mirroring: mirrors
    • Function: speed up download
  • Alibaba cloud image is recommended in China
<mirror>
    <id>alimaven</id>
    <name>aliyun maven</name>
    <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    <mirrorOf>central</mirrorOf>       
</mirror> 
perhaps
<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> 

5.5 local warehouse

Local warehouse, remote warehouse;

Establish a local warehouse:

<localRepository>D:\Program Files\Maven\apache-maven-3.6.3\repostory</localRepository>

5.6 using Maven in IDEA

  1. Start IDEA
  2. Create a maven web project (normal Maven projects need not be checked)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-i5rsuNJb-1630979020807)(D: / software / typora / pictures / image-20210722182927422. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-UKexrKqT-1630979020808)(D: / software / typora/Typora/pictures/image-20210722183131025.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-VxajkEjv-1630979020808)(D: / software / typora/Typora/pictures/image-20210722183423766.png)]

  1. Wait a moment for the initial creation and wait for the automatic import in the lower right corner to complete.

  2. Watch what's in Maven's warehouse

  3. maven settings in IDEA

    After the IDEA project is successfully created, take a look at Maven's configuration

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-B0DPzWry-1630979020809)(D: / software / typora / pictures / image-20210722184951986. PNG)]

  1. Here, the configuration and use of Maven in the IDEA are OK!

5.7 create a normal Maven project

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-8sPj1nDz-1630979020810)(D: / software / typera / pictures / image-20210722185928727. PNG)]

[external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-BiOF8EVT-1630979020810)(D: / software / typora / pictures / image-20210722190436466. PNG)]

The following are only available in web applications!

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-cHDOHTjh-1630979020811)(D: / software / typera / pictures / image-20210722190702026. PNG)]

5.8 marking folder function in idea

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-U0qUWNIJ-1630979020812)(D: / software / typera / pictures / image-20210722191121930. PNG)]

perhaps

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-5gyNrJ6m-1630979020812)(D: / software / typera / pictures / image-20210722191311498. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-hCfyIi3X-1630979020813)(D: / software / typera / pictures / image-20210722191630329. PNG)]

5.9 configuring Tomcat in IDEA

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-IUIQdh0D-1630979020813)(D: / software / typera / pictures / image-20210722192356410. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-DtA2OTlF-1630979020814)(D: / software / typora / pictures / image-20210722192728905. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-TYCkAQtb-1630979020815)(D: / software / typora / pictures / image-20210722192810462. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-guLkjlHY-1630979020816)(D: / software / typora/Typora/pictures/image-20210722193339967.png)]

Resolve warning issues

Must be configured: why is this problem: when we visit a website, we need to specify a folder name;

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG pqzkdgaw-1630979020817) (D: / software / typora / pictures / image-20210722204209491. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ol9cPaNd-1630979020818)(D: / software / typera / pictures / image-20210722204316239. PNG)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1EtL5pEW-1630979020818)(D: / software / typora/Typora/pictures/image-20210722213441402.png)]

5.10 pom documents

pom.xml is Maven's core configuration file

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-22xGbjYk-1630979020819)(D: / software / typora/Typora/pictures/image-20210723001916920.png)]

Maven's convention is greater than the configuration. We may encounter the problem that the configuration file we wrote cannot be exported or take effect. Solution: add a resource under build

<!--stay build Medium configuration resource,Prevent resource export failure-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>**/*.properties</exclude>
                    <exclude>**/*.xml</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

5.11 IDEA operation

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9QGkt2wY-1630979020821)(D: / software / typora/Typora/pictures/image-20210723002659888.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wU0Kuwzy-1630979020822)(D: / software / typora/Typora/pictures/image-20210723002634828.png)]

5.12 solve some problems encountered

  1. Maven 3.6.2

    Unable to import maven project : See logs for details

    Solution: downgrade the version to 3.6.1

  2. Tomcat flash back

  3. maven must be configured repeatedly every time in the IDEA

    Configure in the global default configuration in IDEA

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zMW7D4wv-1630979020823)(D: / software / typora / pictures / image-2021072300417694. PNG)]

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-pyxbqsm-1630979020823) (D: / software / typera / pictures / image-20210723004259061. PNG)]

  4. Tomcat cannot be configured in Maven project

  5. The version of web.xml in maven's default web project

    Solution: replace with webapp version 4.0, which is consistent with Tomcat

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    </web-app>
    
  6. Use of Maven warehouse

    Address: https://mvnrepository.com/

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-awjrccyb-1630979020824) (D: / software / typora/Typora/pictures/image-20210723093402925.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tEpj13BV-1630979020825)(D: / software / typora/Typora/pictures/image-20210723093511483.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ecnied3e-1630979020826)(D: / software / typora / pictures / image-20210723093616592. PNG)]

6,Servlet

6.1 introduction to Servlet

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

The java program that implements the Servlet interface is called Servlet.

6.2 HelloServlet

The Servlet interface has two default implementation classes in sun company: HttpServlet and GenericServlet

  1. Build an ordinary Maven project and delete the src directory. In the future, we will build Moudel in this project. This empty project is the main project of Maven

  2. Understanding of Maven father son project:

    There will be in the parent project

    <modules>
            <module>servlet-01</module>
        </modules>
    

    There will be in the subproject

    <parent>
        <artifactId>maven-javaweb-servlet</artifactId>
        <groupId>com.briup</groupId>
        <version>1.0-SNAPSHOT</version>
      </parent>
    

    The jar package subprojects in the parent project can be used directly

  3. Maven environment optimization

    • Modify web.xml to the latest
    • Complete the structure of maven
  4. Write a Servlet program

    • Write a common class
    • Implement the Servlet interface. Here we directly inherit HttpServlet
public class HelloServlet extends HttpServlet {
    //Because get and post are only different ways of request implementation, they can call each other because the business logic is the same;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Response flow
        PrintWriter writer = resp.getWriter();

        writer.print("Hello Servlet");
    }

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

  1. Write the mapping of servlets

    Why mapping is needed: we write a java program, but to access it through the browser, the browser needs to connect to the web server, so we need to register our Servlet in the web service and give it a path that the browser can access

        <!--register Servlet-->
        <servlet>
            <servlet-name>hello</servlet-name>
            <servlet-class>com.liang.servlet.HelloServlet</servlet-class>
        </servlet>
        <!--Servlet Request path-->
        <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  2. Configure Tomcat

    Note: just configure the project publishing path

  3. Start test

6.3 Servlet operation principle

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

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tRqEr6TA-1630979020827)(D: / software / typora / pictures / image-20210727142700851. PNG)]

6.4 Mapping problems

  1. A Servlet can specify a mapping path

    <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>/hello</url-pattern>
        </servlet-mapping>
    
  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>
    
  3. A Servlet can specify a common mapping path

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

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

    <!--You can customize the request path-->
    <servlet-mapping>
            <servlet-name>hello</servlet-name>
            <url-pattern>*.liangpei</url-pattern>
        </servlet-mapping>
    
  6. Priority questions:

    It specifies the inherent mapping path with the highest priority. If it cannot be found, it will go to the default processing request;

6.5 ServletContext

When the web container starts, it will create a corresponding ServletContext object for each web application, which represents the current web application;

1. Shared data

The data I saved in this Servlet can be obtained in another Servlet;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        this.getInitParameter() initialization parameter
//        this.getServletConfig() Servlet configuration
//        this.getServletContext() Servlet context
        System.out.println("Hello");
        ServletContext context = this.getServletContext();
        String username = "Liang Pei"; //data
        //A data is saved in the ServletContext with the name of username and the value of username
        context.setAttribute("username",username);
    }
}
public class GetServlet extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        Object username = (String)context.getAttribute("username");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print(username);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.liang.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.liang.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getc</servlet-name>
        <url-pattern>/getc</url-pattern>
    </servlet-mapping>

Test access results;

2. Get initialization parameters

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

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("/getp");// Forwarded request path
//        requestDispatcher.forward(req, resp);// Call the forward method to forward the request
        context.getRequestDispatcher("/getp").forward(req, resp);
    }

4. Read resource file

properties

  • Create properties in the java directory
  • Create properties in the resources directory

It is found that: all are packaged under the agreed path: classes, which we commonly call classpath;

Idea: need a file stream;

username=root
password=root
public class PropertiesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties properties = new Properties();
        properties.load(is);
        String user = properties.getProperty("username");
        String psw = properties.getProperty("password");
        resp.getWriter().print(user + " : " + psw);
    }

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

Just access the test;

6.6 HttpServletResponse

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

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

1. Simple classification

Methods responsible for sending data to the browser:

ServletOutoutStream getOutoutStream() throws IOException;
PrintWriter getWriter() throws IOException;

Methods responsible for sending response headers to browsers:

 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);

2. Common applications

  • Output message to browser
  • Download File
    • To get the download path
    • What is the download file name?
    • Try to make the browser support the download function
    • Gets the input stream of the downloaded file
    • Create buffer
    • Get output stream object
    • Writes the FileOutputStream stream to the buffer buffer
    • Use OutputStream to output the data of the buffer to the client
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        -To get the download path
        String realPath = "D:\\Program Files\\ideaIU-2021.1.3.win\\workspace\\maven-javaweb-servlet\\response\\target\\classes\\1.jpg";
        System.out.println("Lu Jin downloading files:" + realPath);
//        -What is the download file name?
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
//        -Try to make the browser support the download function
        resp.setHeader("Content-Disposition","attachment:filename=" + fileName);
//        -Gets the input stream of the downloaded file
        FileInputStream in = new FileInputStream(realPath);
//        -Create buffer
        int len = 0;
        byte[] buffer = new byte[1024];
//        -Get output stream object
        ServletOutputStream out = resp.getOutputStream();
//        -Writes the FileOutputStream stream to the buffer buffer
//        -Use OutputStream to output the data of the buffer to the client
        while ((len = in.read(buffer)) != -1){
            out.write(buffer,0,len);
        }
        in.close();
        out.close();
    }

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

6.7 HttpServletRequest

String fileName = realPath.substring(realPath.lastIndexOf("\") + 1);
//- find a way to make the browser support the download function
resp.setHeader("Content-Disposition","attachment:filename=" + fileName);
//- get the input stream of the downloaded file
FileInputStream in = new FileInputStream(realPath);
//- create buffer
int len = 0;
byte[] buffer = new byte[1024];
//- get output stream object
ServletOutputStream out = resp.getOutputStream();
//- write FileOutputStream stream to buffer
//- use OutputStream to output the data of the buffer to the client
while ((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
in.close();
out.close();
}

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

}



### 6.7 HttpServletRequest

Tags: Java

Posted on Wed, 24 Nov 2021 02:27:23 -0500 by siko