Getting started with Servlet components

Chapter 1 Why do we need servlets?

What is a Servlet?

  • Broadly speaking, Servlet specification is a set of technical standards formulated by Sun company, including a series of interfaces related to Web applications. It is a macro solution for the implementation of Web applications. The specific Servlet container is responsible for providing the implementation of the standard.
  • In a narrow sense, Servlet refers to javax.servlet.Servlet interface and its sub interfaces, and can also refer to the implementation class that implements the Servlet interface.
  • Servlet (Server Applet), as a server-side component, originally means "server-side applet".
    • The Servlet instance object is created by the Servlet container;
    • Servlet methods are called by the container under specific circumstances;
    • The Servlet container will destroy the instance of the Servlet object when the Web application is unloaded.

web.xml: Web application deployment descriptor, which is mainly used for the registration of various web components.

How do I use servlets?

Operation steps

  • Review: the traditional way to use an interface:

    • Create a class to implement the interface
    • new implements the object of the class
    • Calling methods of classes, etc
  • How to use Servlet interface:

    ① Build a Web development environment

    ② Create a dynamic Web project

    ③ Create the implementation class of javax.servlet.Servlet interface: com.atguigu.servlet.MyFirstServlet

    ④ Write the following code in the service(ServletRequest, ServletResponse) method to output the response information:

@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		//1. Write an output statement to prove that the current method is called
		System.out.println("Servlet worked...");
		//2. Send response information to the browser through the PrintWriter object
		PrintWriter writer = res.getWriter();
		writer.write("Servlet response");
		writer.close();
	}

⑤ Register MyFirstServlet in the web.xml configuration file
The servlet object is created by the servlet container, not by us, so we need to give the full class name to tomcat to create it

<!-- Declare a Servlet,Configured is Servlet Class information for -->
<servlet>
	<!-- This is Servlet Alias of, one name for one Servlet. Equivalent to variable name -->
	<servlet-name>MyFirstServlet</servlet-name>
	<!-- Servlet The server will find the full class name based on the full class name Servlet -->
	<servlet-class>com.atguigu.servlet.MyFirstServlet</servlet-class>
</servlet>

<!-- establish Servlet Request mapping information for -->
<servlet-mapping>
	<!-- Servlet Alias, which means this Servlet Will respond to the following url-pattern Request for -->
	<servlet-name>MyFirstServlet</servlet-name>
	<!-- Servlet The request path of the response. If you access this path, this Servlet Will respond -->
	<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>

explain:

  • : multiple url patterns can be configured. In this case, accessing these URLs will trigger the Servlet to respond. Run the browser, access the url path just configured, and the service method of the Servlet will be called.

  • The text content in the path must start with / or *. It is equivalent to mapping resources to the project root directory to form a virtual resource file.

  • Multiple can be declared in and can be accessed through any one. However, only one will be configured in development.

⑥ create index.html in WebContent directory

⑦ add hyperlink < a href = "MyFirstServlet" > to servlet in index.html

⑧ click the hyperlink to test the Servlet

Operational analysis (execution principle)

  • index.html

Summary of Servlet functions

  • Receive request [parse data in request message: request parameters]

  • Processing request [DAO and database interaction]

  • Complete response [set response message]
    Web server such as Tomcat

Servlet lifecycle (important)

4.1 overview of servlet life cycle

  • Objects in an application not only have a hierarchical relationship in space, but also show different states and behaviors in time because they are in different stages of the program running process - this is the life cycle of objects.
  • Simply describe the life cycle, which is the process from creation to destruction of objects in the container.

4.2 Servlet container

Servlet objects are created by the servlet container, and life cycle methods are called by the container. This is very different from the code we wrote before. In the future study, we will see that more and more objects are created by containers or frameworks, and more and more methods are called by containers or frameworks. Developers should focus on the implementation of business logic as much as possible.

The main process of Servlet life cycle

① Servlet object creation: constructor

  • By default, the Servlet container creates the corresponding Servlet object the first time it receives an HTTP request.
  • The container can do this because we provide the full class name when registering the Servlet, and the container uses reflection technology to create the Servlet object.

② Servlet object initialization: init()

  • Servlet container * * after creating a servlet object, the init (ServletConfig) * * method will be called.
  • Function: performs some initialization operations after the Servlet object is created. For example, read some resource files, configuration files, or establish a connection (such as a database connection)
  • The init() method is executed only once when an object is created, and will not be executed when a request is received later
  • In the javax.servlet.Servlet interface, the public void init(ServletConfig config) method requires the container to pass in the instance object of ServletConfig, which is also the fundamental method for us to obtain the instance object of ServletConfig.

③ Processing request: service()

  • In the javax.servlet.Servlet interface, the * * service(ServletRequest req, ServletResponse res) * * method is defined to process HTTP requests.
  • It is executed every time a request is received.
  • The function of Servlet mentioned in the previous section is mainly reflected in this method.
  • At the same time, the container is required to pass in the ServletRequest object and ServletResponse object.

④ Servlet object destruction: destroy()

  • When the server restarts, the server stops executing or the Web application uninstalls, the Servlet object will be destroyed and the public void destroy() method will be called.
  • This method is used to perform operations such as releasing the cache, closing the connection, saving memory data, and persistence before destruction.

Servlet request process

  • First request
    • Call the constructor to create the object
    • Execute init() method
    • Execute the service() method
  • Subsequent request
    • Execute the service() method
  • Before object destruction
    • Execute the destroy() method

When the Servlet receives the request for the first time, the Servlet container [web container web server] creates the Servlet [execution constructor], and then executes the init() method for initialization. Finally, execute the service() method to process the request and respond. [after receiving the request again, only execute the service() method]. When the server is shut down or restarted, execute the destroy() method to destroy the Servlet.

<!--set up Servlet Creation time: created when the server is started Servlet If not configured, it is created on the first access
        index:set up Servlet Priority created[ int Type and positive integer, Min. 1]
            The lower the value, the higher the priority

-->
<load-on-startup>1</load-on-startup>

At this point, the Servlet life cycle is adjusted as follows

  • The constructor executes after the service is started
  • init() is executed when the server is started and the constructor is executed.
  • Other methods, no change.

Two important interfaces of Servlet

ServletConfig interface

  • The ServletConfig interface encapsulates the Servlet configuration information, which can be seen from the name of the interface.

  • Each Servlet has a unique corresponding ServletConfig object, which represents the configuration information of the current Servlet.

  • The object is created by the Servlet container and passed into the lifecycle method init(ServletConfig config). It can be obtained and used directly.

  • The ServletContext object representing the current Web application is also encapsulated in the ServletConfig object, making the ServletConfig object a bridge to obtain the ServletContext object.

  • Main functions of ServletConfig object

    • Get Servlet Name: getServletName()

    • Get global context ServletContext object: getServletContext()

    • Get Servlet initialization parameters: getInitParameter(String) / getInitParameterNames().

    • Use the following:

Through String info = config.getInitParameter("url"); Get value by

<init-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/dbname</param-value>
</init-param>

You can only test once in init
therefore

package com.edu.shengda.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

public class MyFirstServlet implements Servlet {

    //Change ServletConfig config from a local variable in the init method to a global variable
    private ServletConfig servletConfig;

    @Override
    public void init(ServletConfig config) throws ServletException {
        /*
        //1.Get ServletContext object
        ServletContext context = config.getServletContext();
        //2.Get the local path of index.html
        //index.html The virtual path of is "/ index.html", where "/" represents the root directory of the current Web application,
        //WebContent directory
        String realPath = context.getRealPath("/index.html");
        //realPath=D:\DevWorkSpace\MyWorkSpace\.metadata\.plugins\
        //org.eclipse.wst.server.core\tmp0\wtpwebapps\MyServlet\index.html
        System.out.println("realPath="+realPath);
        
         */

        //Property assigned to the current class
        this.servletConfig = config;
    }


    @Override
    public ServletConfig getServletConfig() {
        return null;
    }


    @Override
    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
        //1. Write an output statement to prove that the current method is called
        System.out.println("Servlet worked...");
        //2. Send response information to the browser through the PrintWriter object
        PrintWriter writer = res.getWriter();
        writer.write("Servlet response");
        writer.close();

        //This allows multiple calls
        String servletName = this.servletConfig.getServletName();
        System.out.println("getServletName  ----> " + servletName);
        ServletContext servletContext = this.servletConfig.getServletContext();
        System.out.println("getServletContext  ----> " + servletContext);
        String url = this.servletConfig.getInitParameter("url");
        System.out.println("url" + url);

    }


    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

ServletContext interface

Overview: this object represents the current web application, that is, the current project. Each web application has a unique ServletContext object. [ServletContext object, which is created by the web server when the tomcat service is started.]

  • When the Web container starts, it will create a unique corresponding ServletContext object for each Web application, which means Servlet context, representing the current Web application.

  • Since all servlets in a Web application share the same ServletContext object, the ServletContext object is also called application object (Web application object).

  • The object is created by the Servlet container when the project is started and obtained through the getServletContext() method of the ServletConfig object. Destroy when the project is unloaded.

  • Main functions of ServletContext object

effect:

  1. Get context path [with / project name, eg:/day05_tomcat_http_servlet]

    String contextPath = servletContext.getContextPath();
    
  2. Get the real path [D: / xxx (file upload & file download)]

    String realPath = servletContext.getRealPath("/index.html");
    
  3. Get context initialization parameters

    <context-param>
        <param-name>stuName</param-name>
        <param-value>caixukun</param-value>
    </context-param>
    
    String stuName = servletContext.getInitParameter("stuName");
    
  4. Domain object [web domain, 4 domain objects in total]

① Get the context path of the project (project name with /): getContextPath()

@Override
public void init(ServletConfig config) throws ServletException {
//getServletContext gets the ServletContext object first
	ServletContext servletContext= config.getServletContext();
	System.out.println("Global context object:"+application);
	//servletContext gets the context path from servletContext
	String path = servletContext.getContextPath();
	System.out.println("Global context path:"+path);// /06_Web_Servlet
	//Global context object: org. Apache. Catalina. Core ApplicationContextFacade@9d7ed7d
//Global context path: / javaee_war_exploded
}

② Get the local real path mapped by the virtual path: getRealPath(String path)

  • Virtual path: the path used by the browser to access resources in the Web application.

  • Local path: the actual save path of the resource in the file system.

  • Function: write the file uploaded by the user to the server hard disk through streaming.

@Override
public void init(ServletConfig config) throws ServletException {
	//1. Get ServletContext object
	ServletContext context = config.getServletContext();
	//2. Get the local path of index.html
	//The virtual path of index.html is "/ index. HTML", where "/" represents the root directory of the current Web application,
	//WebContent directory
	String realPath = context.getRealPath("/index.html");
	//Note that the real path deployed to the out directory is obtained
	//realPath=D:\DevWorkSpace\MyWorkSpace\.metadata\.plugins\
	//org.eclipse.wst.server.core\tmp0\wtpwebapps\MyServlet\index.html
	System.out.println("realPath="+realPath);
}

③ Get the global initialization parameters of WEB application (basically not used)

  • The way to set Web application initialization parameters is to add the following code under the root tag of web.xml
<web-app>
	<!-- Web Application initialization parameters -->
	<context-param>
		<param-name>ParamName</param-name>//key
		<param-value>ParamValue</param-value>//value
	</context-param>
</web-app>

Get Web application initialization parameters

@Override
public void init(ServletConfig config) throws ServletException {
	//1. Get ServletContext object
	ServletContext application = config.getServletContext();
	//2. Get Web application initialization parameters
	String paramValue = application.getInitParameter("ParamName");
	System.out.println("Global initialization parameters paramValue="+paramValue);
}

Share data as domain objects

  • As the largest domain object, share data in different web resources of the whole project.

Among them,

  • setAttribute(key,value): it can be retrieved and used anywhere in the future
  • getAttribute(key): get the set value

Servlet Technology System

Finally create Servlet mode

Insufficient way to create Servlet before

  1. In the implementation class that implements the Servlet interface, the methods are redundant [only service()]
  2. There is no prompt to register the Servlet
  • EndServlet : HttpServlet : GenericServlet : Servlet

  • GenericServlet role

    1. Provides methods to get ServletConfig and ServletContext objects

      • getServletConfig()
      • getServletContext()
    2. Abstract the service() method

      @Override
      public abstract void service(ServletRequest req, ServletResponse res)
              throws ServletException, IOException;
      
  • HttpServlet action

    1. Override service() [override service()]

      @Override
      public void service(ServletRequest req, ServletResponse res)
          throws ServletException, IOException {
      
          HttpServletRequest  request;
          HttpServletResponse response;
      
          try {
              request = (HttpServletRequest) req;
              response = (HttpServletResponse) res;
          } catch (ClassCastException e) {
              throw new ServletException("non-HTTP request or response");
          }
          service(request, response);
      }
      
    2. Overload service() [overload service()]

      protected void service(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {
      
          String method = req.getMethod();
          if("GET".eq(method)){
              doGet(req,resp);
          }else if("POST".eq(method)){
              doPost(req,resp);
          }else if(){
              //PUT  |  DELETE
              
          }...
          
      }
      

Servlet Interface

-Why extend the Servlet interface?

  • Packaging is not commonly used
  • Implementation class system
    • GenericServlet implements the Servlet interface
    • HttpServlet inherits GenericServlet
  • The final way to create a Servlet
    • Inherit HttpServlet

Source code analysis

GenericServlet abstract class

  • GenericServlet encapsulates and perfects the Servlet function and rewrites the init(ServletConfig config) method to obtain the ServletConfig object. At this time, if a subclass of GenericServlet (usually a custom Servlet) overrides the init(ServletConfig config) method, the ServletConfig object may not be obtained, so the subclass should not override the init() method with parameters.
  • If you want to initialize, you can override the parameterless init() method provided by GenericServlet, so that the acquisition of ServletConfig object will not be affected.
  • Keep the service(ServletRequest req,ServletResponse res) as an abstract method so that the user only cares about the business implementation.

HttpServlet abstract class

-A Servlet dedicated to handling Http requests.

  • Further encapsulate and extend GenericServlet. In the service(ServletRequest req, ServletResponse res) method, convert ServletRequest and ServletResponse into HttpServletRequest and HttpServletResponse, and call special methods for processing according to different HTTP request types.

  • **In the future, in actual use, you can inherit the HttpServlet abstract class and create your own Servlet implementation class** Rewrite doGet(HttpServletRequest req, HttpServletResponse resp) and doPost(HttpServletRequest req, HttpServletResponse resp) methods to realize request processing. There is no need to rewrite service(ServletRequest req, ServletResponse res) methods.

  • Because the processing methods of get and post in our business are the same, we only need to write one method and use another method to call the doXXX method we have written. The web.xml configuration is the same as before.

//Handle browser get requests
doGet(HttpServletRequest request, HttpServletResponse response){
	//Business code
}
//Handle post requests from browsers
doPost(HttpServletRequest request, HttpServletResponse response){
    doGet(request, response);
}

request and response objects

request

  • Type: HttpServletRequest

  • Overview: request is equivalent to that the browser sends a request message to the server and encapsulates it into the request object. The object is created by the server and sent to the service() method in the form of parameters, and finally passed into the doGet() or doPost() method.

  • effect:

    1. Get request parameters

      What parameters

      1. ? What follows: < a href = "endservlet? Uname = ZS & PWD = 123456" ></a>

      2. Parameter in the form: name attribute value

        <form action="EndServlet" method="post">
            user name:<input id="username" type="text" name="username" value="" /><br>
            password:<input id="pwd" type="password" name="password" value="123"/><br>
            <input id="btnSub" type="submit" value="Sign in" >
        </form>
        
      • request.getParameter(): get a single request parameter
      • request.getParameterValues(): get multiple request parameters
    2. Gets the information in the request header

      • request.getHeader("User-Agent|Cookie|Referer")
    3. Get URL information[ http://localhost:8080/day06_servlet/]

      • Get protocol: request.getScheme()
      • Get server name: request.getServerName()
      • Get server port: request.getServerPort()
      • Get context path [with / item name]: request.getContextPath()
    4. Forwarding request [path jump]

      //1. Get transponder
      RequestDispatcher requestDispatcher = request.getRequestDispatcher("login_success.html");
      //2. Execute forwarding
      requestDispatcher.forward(request,response);
      
    5. Domain objects [four in total, ServletContext|request]

Several other important interfaces

HttpServletRequest interface

  • This interface is a sub interface of ServletRequest interface and encapsulates the relevant information of HTTP request.

  • When the browser requests the server, it will encapsulate the request message and give it to the server. When the server receives the request, it will parse the request message and generate a request object.

  • The Servlet container creates its implementation class object and passes it into the service(HttpServletRequest req, HttpServletResponse res) method.

  • The HttpServletRequest object mentioned below refers to the HttpServletRequest implementation class object provided by the container.

The main functions of the HttpServletRequest object are:

Get request parameters

<form action="MyHttpServlet" method="post">
	Your favorite football team<br /><br />
	Brazil<input type="checkbox" name="soccerTeam" value="Brazil" />
	Germany<input type="checkbox" name="soccerTeam" value="German" />
	Netherlands<input type="checkbox" name="soccerTeam" value="Holland" />
	<input type="submit" value="Submit" />
</form>

Use the HttpServletRequest object to get the request parameters

//A name corresponds to a value
String userId = request.getParameter("userId");
//A name corresponds to a set of values
String[] soccerTeams = request.getParameterValues("soccerTeam");
for(int i = 0; i < soccerTeams.length; i++){
	System.out.println("team "+i+"="+soccerTeams[i]);
}

Get url address parameters

String path = request.getContextPath();//important
System.out.println("Context path:"+path);
System.out.println("Port number:"+request.getServerPort());
System.out.println("Host name:"+request.getServerName());
System.out.println("agreement:"+request.getScheme());

Get request header information

String header = request.getHeader("User-Agent");
System.out.println("user-agent:"+header);
String referer = request.getHeader("Referer");
System.out.println("Address of previous page:"+referer);//If the login fails, return to the login page to allow the user to continue logging in

Forwarding of requests

Forward the request to another URL address, see Chapter 7 - request forwarding and redirection.
This indicates that the request forwarding object is in the same level directory as success.html under the web directory

//Get request forwarding object
RequestDispatcher dispatcher = request.getRequestDispatcher("success.html");
dispatcher.forward(request, response);//Initiate forwarding

Save data to the request field

//Save the data to the property field of the request object
request.setAttribute("attrName", "attrValueInRequest");
//If two servlets want to share the data in the request object, it must be a forwarding relationship
request.getRequestDispatcher("/ReceiveServlet").forward(request, response);

//Get data from the request property field
Object attribute = request.getAttribute("attrName");
System.out.println("attrValue="+attribute);

7.2 HttpServletResponse interface

response

  • Type: HttpServletResponse
  • Overview: response is equivalent to the response message sent by the server to the browser and encapsulated in the response object. The object is created by the server and sent to the service() method in the form of parameters, and finally passed into the doGet() or doPost() method.
  • effect:
  1. Get response flow, response data
     - PrintWriter writer = response.getWriter();
     - writer.writer();|writer.print()
  2. Set response header
     - response.setHeader("Content-Type","text/html;charset=UTF-8");
  3. Redirect [path jump]
     - response.sendRedirect("url");
  • This interface is a sub interface of the ServletResponse interface, which encapsulates the information related to the HTTP response of the server. (for the time being, there is only the configuration information of the server, and there is no specific content related to the response body.)
- from Servlet The container creates its implementation class object and passes it in service(HttpServletRequest req, HttpServletResponse res)Method.

- What we'll talk about later HttpServletResponse Object refers to the object provided by the container HttpServletResponse Implement class objects.

HttpServletResponse The main functions of the object are:

Use the PrintWriter object to output data to the browser

//Send response information to the browser through the PrintWriter object
PrintWriter writer = res.getWriter();
writer.write("Servlet response");
writer.close();
  • The written data can be pages, page fragments, strings, etc

  • When the written data contains Chinese, the Response data received by the browser may be garbled. To avoid garbled code, you can use the Response object to set the Response header before outputting data to the browser.

Set response header

The response header is the configuration of the browser to parse the page. For example, tell the browser which encoding and file format to use to parse the content of the response body

response.setHeader("Content-Type", "text/html;charset=UTF-8");

After setting, you will see the information in the set response header in the browser's response message.

Redirecting Requests

  • For request redirection, see Chapter 8 - request forwarding and redirection.
  • For example, the user submits the login request data from the login.html page to LoginServlet for processing. If the account and password are correct, the user needs to jump to the success page. It is too complicated to write the success page to the response body through servlet. The browser will jump automatically by redirecting the address of the success page to the browser and setting the response status code as 302.
//Pay attention to the path problem. Adding / will fail. It will start with the host address. Generally, the redirection needs to add the project name
response.sendRedirect("success.html");

Forwarding and redirection of requests

Request forwarding and redirection are the main means of page Jump in web applications, which are widely used in web applications, so we must find out their differences.

Forwarding of requests

  • The first Servlet receives the request from the browser and processes it to some extent. Then it does not respond to the request immediately, but "hands over the request to the next Servlet" to continue processing. After the next Servlet completes processing, it responds to the browser. * * the server "hands over" the request to the browser The continued processing of other components is the forwarding of the request. * * for the browser, only one request is sent, and the "forwarding" within the server is not felt by the browser. At the same time, the address in the browser address bar will not become the virtual path of "next Servlet".
  • HttpServletRequest represents an HTTP Request. The object is created by the Servlet container. In case of forwarding, two servlets can share the data saved in the same Request object.
  • When you need to transfer the data obtained in the background to the JSP for display, you can first store the data in the Request object, and then forward it to the JSP to obtain it from the property field. At this time, because it is "forwarding", they share the data in the Request object.
  • In the case of forwarding, you can access the resources under WEB-INF.
  • Forwarding starts with "/" to indicate the project root path, and redirection starts with "/" to indicate the host address.
  • Function:
    • Get request parameters
    • Get information about the request path, i.e. URL address
    • Save data in request field
    • Forward request
  • Code example
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
	//1. Use the RequestDispatcher object to encapsulate the virtual path of the target resource
	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.html");
	//2. Call the forward() method of the RequestDispatcher object to "go" to the target resource
	//[Note: the passed in parameters must be passed to the service method of the current Servlet
	//The two ServletRequest and ServletResponse objects]
	dispatcher.forward(request, response);
}

Requested redirection

-The first Servlet receives the request from the browser, processes it to some extent, and then gives the browser a special response message. This special response message will inform the browser to access another resource. This action is automatically completed by the server and browser. In the whole process, the browser will send two requests, and the address change can be seen in the browser address bar, which is changed to the address of the next resource.

  • In the case of redirection, the request domain data cannot be shared between the original Servlet and the target resource.

  • HttpServletResponse represents the HTTP response, and the object is created by the Servlet container.

  • Function:

    • Output data to browser
    • Redirecting Requests
  • Header of redirected response message

HTTP/1.1 302 Found
Location: success.html
  • Application:

    • The user submits the login request data from the login.html page to the LoginServlet for processing.

      If the account password is correct, the user needs to jump to the success page. It is too complex to write the success page to the response body through the servlet. The browser will jump automatically by redirecting the address of the success page to the browser and setting the response status code as 302

  • Code example:

protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
	//1. Call sendRedirect() method of HttpServletResponse object
	//2. The parameter passed in is the virtual path of the target resource
	response.sendRedirect("index.html");
}

Compare forwarding and redirection of requests

forwardredirect
Browser awarenessIt is completed inside the server and is not perceived by the browserThe server notifies the browser to access the new address with 302 status code, and the browser is aware of it
Browser address barNo changechange
Number of requests sent in the whole processoncetwice
Execution efficiencyefficientLow efficiency
API (or initiator)Request objectResponse object
Can request object data be sharedcanno
Resources under WEB-INFCan accessCannot access
Target resourcesIt must be a resource in the current web applicationNot limited to current web applications

Note 1: by default, the browser cannot access the resources under the server web inf, but the server can access them.

Note 2: browser default absolute path: http://localhost:8080/

Absolute path in the code of the server project: http://localhost:8080/ Project name/

Character encoding settings in requests and responses

Character encoding problem

  • In the process of receiving and processing requests, if we do not pay attention to the encoding format and decoding format, it is easy to cause Chinese garbled code. What is the reason for this problem? How to solve it? We will discuss this in this section.
  • Speaking of this problem, let's first talk about the character set.
    • What is a character set is a collection of various characters, including Chinese characters, English, punctuation and so on. Different countries have different characters and symbols. The set of these text symbols is called the character set.
    • Existing character sets include ASCII, GB2312, BIG5, GB18030, Unicode, UTF-8, ISO-8859-1, etc
  • These character sets contain a lot of characters. However, to store the characters in binary form in the computer, we need to encode them and store the encoded binary into the computer. When we take it out, we have to decode it and decode the binary into our previous characters. At this time, we need to formulate a set of coding and decoding standards. Otherwise, it will lead to chaos, that is, our random code.

Encoding and decoding

  • Encoding: converts characters to binary numbers
chinese charactersCoding modecodeBinary
'medium 'GB2312D6D01101 0110-1101 0000
'medium 'UTF-164E2D0100 1110-0010 1101
'medium 'UTF-8E4B8AD1110 0100- 1011 1000-1010 1101
  • Decoding: converting binary numbers to characters

1110 0100-1011 1000-1010 1101 → E4B8AD → 'medium'

  • Garbled Code: A piece of text encoded with A character set and decoded with B character set will produce garbled code. Therefore, the fundamental way to solve the problem of garbled code is to unify the character set of encoding and decoding.

Type of garbled code [B/S]

  • Request garbled Code: garbled code occurs when the browser sends a request to the server
    • The browser encoding is inconsistent with the server decoding
  • Response garbled Code: garbled code occurs when the server responds to the browser
    • The server encoding is inconsistent with the browser decoding

Solve the problem of request garbled code

The solution to garbled Code: unified character coding.

GET request

  • The GET request parameter is after the address. We need to modify the configuration file of tomcat. You need to modify the Connector tag in the server.xml file and add the URIEncoding="utf-8" attribute.

Once configured, you can solve the garbled problem of all GET requests in the current workspace.

POST request

  • The post request submitted a Chinese request body, and there was a problem with the server parsing.

  • Solution: before obtaining the parameter value, set the decoding format of the request to be consistent with the page.

    request.setCharacterEncoding("utf-8");
    
  • The solution of POST request garbled code problem is only applicable to the class where the current operation is located. It cannot be solved uniformly like GET requests. Because the request body may upload files. Not all Chinese characters.

Solve the problem of response garbled code

Server and browser default encoding and decoding problems

  • The default encoding and decoding of the server are consistent: ISO-8859-1 [Chinese not supported]
  • Browser defaults
    • Code: UTF-8 [< meta charset = "UTF-8" >]
    • Decoding: GBK [GB2312]

8.4 garbled code solution

-Resolve request garbled code

-GET request

- Idea: find the settings URL Character set position
- ![Insert picture description here](https://img-blog.csdnimg.cn/752e76b5929d49b291659ee7c17c726a.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5piO5pyI5bi45paw,size_20,color_FFFFFF,t_70,g_se,x_16)



- code

  ```xml
  <Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"
                 connectionTimeout="20000"
                 redirectPort="8443" />
  ```

-POST request

- Idea: set the server decoding to: UTF-8. [Browser code: UTF-8 Decoding with server: ISO-8859-1]

- code

  ```java
  request.setCharacterEncoding("UTF-8");
  ```

-Resolve response garbled code

  • Idea & Code: [server code: ISO-8859-1, browser decoding: GBK]

    1. Set the server code: GBK [support a small amount of Chinese]

    response.setCharacterEncoding("GBK");   //Set server code
    

    2. Set server encoding and browser decoding: UTF-8 [recommended]

    //Mode 1
    response.setHeader("Content-Type","text/html;charset=UTF-8");
    //Method 2 [ recommended ]
    response.setContentType("text/html;charset=UTF-8");  
    
  • Summary: three lines of code to solve the garbled problem of request and response

  • When sending a response to the browser, tell the browser which character set I use, and the browser will decode it in this way. How to tell the browser the character encoding scheme of the response content. It's simple.

  • Solution 1:

    response.setHeader("Content-Type", "text/html;charset=utf-8");
    
  • Solution 2

    response.setContentType("text/html;charset=utf-8");
    

    Note: some people may think of using response.setCharacterEncoding("UTF-8") to set the reponse object to write the UTF-8 string into the response message, and the encoding is UTF-8. This is not enough. You must manually set the character set used by the browser for parsing in the browser.

Web app path settings

Problem reproduction:

① Create the Web application Path, and the directory structure is shown in the figure

② Hyperlinks in a.html < a href = "b.html" > to b.html

③ If you directly access a.html and then go to b.html through hyperlinks, there is no problem.

④ If you first forward to a.html through testservlet, the browser address bar will become http://localhost:8989/Path/TestServlet

At this point, click the hyperlink < a href = "b.html" > to b.html. A problem will occur and b.html cannot be found.

How to solve it?

The reason is that the hyperlink < a href = "b.html" > to b.html uses a relative path. When the browser parses, it can only be based on the path in the address bar of the current browser. For example, the content in the address bar of the current browser is: http://localhost:8989/Path/TestServlet

After being parsed by the browser, the access address of b.html becomes: http://localhost:8989/Path/TestServletb.html This obviously does not allow access to b.html.

The complete url composition is shown in the figure below:

Relative path and absolute path

Relative path: if the virtual path does not start with "/", it is a relative path. The browser will resolve the relative path based on the virtual path where the current resource is located, so as to generate the final access path. At this time, if you enter other directories through forwarding, and then use the relative path to access resources, an error will occur. Therefore, in order to prevent path errors, we often convert relative paths into absolute paths for requests.

Absolute path: the virtual path starts with "/", which is the absolute path.

What does "/" stand for

  • The server resolves "/", and "/" represents the current context path [current web application path] eg: http://localhost:8080/day06_servlet

    • "/" in the following two paths is resolved by the server

      1. "/" configured in web.xml

        <url-pattern>/RegistServlet</url-pattern>
        
      2. "/" in forward request

  • The browser resolves "/", and "/" represents the current server path. eg: http://localhost:8080/

    • The "/" in the following two paths is resolved by the browser
      1. "/" in redirection
      2. "/" written in static resources [finally load the running content in the browser]
        • For example: html css js
  • The compile time web directory in the IDEA is equivalent to the runtime context path / project name
    ① On the server side: the "/" at the beginning of the virtual path indicates the root directory of the current web application. The absolute path resolved by the server starts with the web root directory. The paths parsed by the server include: < 1 > the configuration path of web.xml and < 2 > the path of request forwarding.
    ② On the browser side: the "/" at the beginning of the virtual path indicates the current host address.
    For example, the link address "/ Path/dir/b.html" is resolved by the browser as:
    amount to http://localhost:8989/Path/dir/b.html
    The paths resolved by the browser include:
    <1> Redirection operation: response.sendRedirect("/xxx")
    <2> All HTML Tags: < a href = "/ xxx" >, < form action = "/ xxx" >, link, img, script, etc
    These last access paths are http://localhost:8989/xxx

Therefore, we can see that if the path is resolved by the browser, we must add the project name to correctly point to the resource. http://localhost:8989/Path/xxx

<1> Redirect operation:

response.sendRedirect(request.getContextPath()+"/xxx");

<2> All HTML Tags: < a href = "/ project name / xxx" >< Form action = "/ project name / xxx" >

  • On the browser side, in addition to the absolute path, we can also use the base tag + relative path to determine the effective access of resources.
  • The base tag affects all relative paths in the current page and will not affect the absolute path. It is equivalent to setting a reference address for the relative path.
  • It is customary to declare in the html tag:
<!-- Set the base address for the relative path in the page -->
<base href="http://localhost:8080/Test_Path/"/>

Then, the path in html can be accessed by relative path. For example:

<h4> base+Relative path</h4>
<!-- <base href="http://localhost:8080/Test_Path/"/> -->
<a href="1.html">1.html</a><br/>
<a href="a/3.html">a/3.html</a><br/>
<!-- servlet It is mapped to the project root directory and can be accessed directly -->
<a href="PathServlet">PathServlet</a><br/>

Create a Servlet based on Java EE 6 and above [web3.0]

@WebServlet(name = "Servlet30",value = "/Servlet30")
public class Servlet30 extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Servlet30!");
    }
}

Tags: Java Front-end Spring intellij-idea

Posted on Mon, 22 Nov 2021 10:54:37 -0500 by whatever