Servlets are the core components of Java Web applications

Servlets run in a Servlet container and can serve a wide variety of customer requests. Servlets can easily accomplish the following tasks:

  • Generate HTML documents dynamically
  • Forward requests to other Servlet components in the same Web application
  • Forward requests to Servlet components in other Web applications
  • Read and write cookies to the client
  • Accessing other server resources (such as databases or Java-based applications)

Servlets are so powerful for two main reasons:

  • Servlet is a class written in Java language. As long as developers have a deep Java programming foundation, they can write all kinds of complex servlets
  • Servlet objects are created by the Servlet container and can easily call various resources in the container

1. Servlet API

The JavaDoc documentation for the Servlet API is available on the Oracle and Apache websites:

Http:tomcat.apache.org/tomcat-9.0-…

1.1 the Servlet interface

At the heart of the Servlet API is the Javax.servlet.servlet interface, which must be implemented by all Servlet classes.

There are five methods defined in the Servlet interface, three of which are called by the Servlet container, which calls specific methods at different stages of the Servlet life cycle:

methods Related instructions
init(ServletConfig config) This method is responsible for initializing the Servlet object; This method is called by the container after the Servlet object has been created
service(ServletRequest req, ServletResponse req) Responsible for responding to client requests and providing corresponding services for the client; When the container receives a request from a client for access to a specific Servlet object, it calls that Servlet objectservice()methods
destroy() Responsible for releasing resources occupied by Servlet objects; The container calls this method when the Servlet object ends its life cycle
getServletConfig() Returns a ServletConfig object containing information about the Servlet initialization parameters
getServletInfo() Returns a String containing information about the author, version, and copyright of the Servlet

javax.servlet.GenericServlet implements Servlet, and javax.servlet.http.HttpServlet extends GenericServlet.

When users develop their own Servlet, they can choose to extend the GenericServlet or the HttpServlet .

1.2 GenericServlet abstract class

The GenericServlet abstract class implements the ServletConfig interface and Serializable interface in addition to the Servlet interface. Here is some important source code for the GenericServlet class:

public abstract class GenericServlet implements Servlet.ServletConfig.java.io.Serializable {

    private transient ServletConfig config;

    public GenericServlet(a) {}
            
    /** * implements this method, but does nothing */
    public void destroy(a) {}

    public String getInitParameter(String name) {
        return getServletConfig().getInitParameter(name);
    }

    public Enumeration<String> getInitParameterNames(a) {
        return getServletConfig().getInitParameterNames();
    }

    public ServletConfig getServletConfig(a) {
        return config;
    }

    public ServletContext getServletContext(a) {
        return getServletConfig().getServletContext();
    }

    public String getServletInfo(a) {
        return "";
    }

    public void init(ServletConfig config) throws ServletException {
        // Associate the current Servlet object with the ServletConfig object passed in to the Servlet container!
        this.config = config;
        this.init();
    }

    public void init(a) throws ServletException {
        // Subclasses can reimplement the method
    }

    /** * The only abstract method in GenericServlet class */
    public abstract void service(ServletRequest req, ServletResponse res) 
        throws ServletException, IOException;

    public String getServletName(a) {
        returnconfig.getServletName(); }... }Copy the code

GenericServlet class source code can be seen: It implements the init(ServletConfig Config) initialization method in the Servlet interface, and the GenericServlet class has a private instance variable config of type ServletConfig. When the Servlet container calls GenericServlet’s init(ServletConfig Config) method, the method causes the private instance variable config to refer to the ServletConfig object passed in by the container, That is, associate the GenericServlet object with the ServletConfig object.

GenericServlet uses the decorator design pattern to attach the ServletConfig decorator identity to itself. An instance of the ServletConfig interface is used to implement the methods in its interface.

Decorative design patterns can be referenced in the blog:Juejin. Cn/post / 684490…

The GenericServlet class also has a custom init() method that takes no arguments and is called by init(ServletConfig Config). There are two ways to override the initialization methods of the parent class (GenericServlet) :

(1) Coverageinit()Methods:

public void init(a){
    // Subclass specific initialization method. }Copy the code

(2) Coverageinit(ServletConfig config)Methods:

public void init(ServletConfig config){
    // Init (config) must be called first, otherwise "null pointer exception" will occur
    super.init(config);
    // Subclass specific initialization behavior. }Copy the code

1.3 HttpServlet abstract class

The HttpServlet class is a subclass of the GenericServlet class. The HttpServlet class provides a generic implementation of the Servlet interface related to the Http protocol. When developing Java Web applications, custom Servlet classes generally extend the HttpServlet class.

HTTP protocol divides client requests into GET, POST, PUT, DELETE and other methods. HttpServlet class provides corresponding service methods for each request mode, such as: Methods such as doGet(), doPost(), doPut(), and doDelete(). The following provides some important source code for the HttpServlet class:

public abstract class HttpServlet extends GenericServlet {
	
    private static final String METHOD_GET = "GET";
    private static final String METHOD_POST = "POST"; .public HttpServlet(a) {}
    
    
    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);
    }
    
    
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        // Obtain the client request mode to invoke the corresponding service method such as doGet(), doPost()...
        String method = req.getMethod();

        if (method.equals(METHOD_GET)) {
            // "GET_METHOD"
            long lastModified = getLastModified(req);
            if (lastModified == -1) {
                doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                } catch (IllegalArgumentException iae) {
                    ifModifiedSince = -1;
                }
                if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else{ resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); }}}else if (method.equals(METHOD_HEAD)) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);
        } else if (method.equals(METHOD_POST)) {
            // "POST_METHOD"
            doPost(req, resp);
        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);
        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);
        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);
        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); }}protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_get_not_supported");
        if (protocol.endsWith("1.1")) {
            // If HTTP1.1 is used, return an error with the response status code 405
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            // If HTTP1.0 is used, return an error with a response status code of 400resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); }}protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_post_not_supported");
        if (protocol.endsWith("1.1")) {
            // If HTTP1.1 is used, return an error with the response status code 405
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
        } else {
            // If HTTP1.0 is used, return an error with a response status code of 400resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); }}protected void doPut(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {...}
    
    ...
    
}
Copy the code

For concrete subclasses of the HttpServlet class, the appropriate doXXX() method in the HttpServlet parent class will generally be overridden for client-specific requests. In order for the doXXX() method to be accessible by the Servlet container, the access should be set to public.

Assuming that the HttpServletSub class is a subclass of the HttpServlet class, reimplement doGet() and doPost() as follows:

public class HttpServletSub extends HttpServlet{
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    	throws ServletException, IOException{
        // Provide the concrete implementation code. }public void doPost(HttpServletRequest req, HttpServletResponse resp)
    	throws ServletException, IOException{
        // Service is the same as doGet()doGet(req, resp); }}Copy the code

1.4 ServletRequest interface

The service(ServletRequest req, ServletResponse res) method of the Servlet interface takes a parameter of type ServletRequest. The ServletRequest class represents the request from the client. When the Servlet container receives a request from a client to access a particular Servlet, the container first parses the original request data from the client and wraps it into a ServletRequest object. When the container calls the service() method of the Servlet object, it passes the ServletRequest object as an argument to the service() method.

The ServletRequest interface provides a series of methods for reading client request data:

methods instructions
getContentLength() Returns the length of the request body, or -1 if the length of the request body is unknown
getContentType() Gets the MIME type of the request body, unknown return NULL
getInputStream() Returns the input stream used to read the request body
getLocalAddr() Returns the IP address of the server
getLocalName() Returns the host name on the server
getLocalPort() Returns the FTP port number of the server
getParameter(String name) Returns the matching request parameter value from the customer request, based on the given request parameter name
getProtocol() Returns the name and version number of the protocol used by the client to communicate with the server
getReader() Returns a BufferedReader object used to read the request body as a string
getRemoteAddr() Returns the IP address of the client
getRemoteHost() Returns the host name of the client
getRemotePort() Returns the FTP port number of the client

In addition, the ServletRequest interface defines a set of methods for accessing shared data within the scope of the request:

methods instructions
setAttribute(String name, java.lang.Object object) Store a property within the scope of the request, with parameter name representing the property name and parameter object representing the property value
getAttribute(String name) Returns the value of the matching attribute within the request range, based on the attribute name given by the name parameter
removeAttribute(String name) Removes an attribute from the scope of the request

1.5 it interface

The HttpServletRequest interface is a subinterface of the ServletRequest interface.

The HttpServletRequest interface provides methods for reading the relevant information in an HTTP request:

methods instructions
getContextPath() Returns the URL entry of the Web application requested by the client

For example, the access URL ishttp://localhost:8080/hello_world/info, then the method returns “/hello_world”
getCookies() Returns all cookies in the HTTP request
getHeader(String name) Returns a specific item in the HTTP request header
getHeaderNames() Returns an Enumeration object containing all the item names in the HTTP request header
getMethod() Returns the HTTP request mode
getRequestURI() Returns the URI in line 1 of the header of the HTTP request
geetQueryString() Returns the query string in the HTTP request, i.eThe URL “?” What follows

For example, the access URL ishttp://localhost:8080/hello_world/info?name=Octocat, then the method returns “name=Octocat”

If you use service() in a subclass that implements the Servlet interface to parse the request parameters in an HTTP request, the process of parsing the original request data is tedious. When creating servlets based on Oracle’s Servlet API, you don’t have to parse the raw HTTP requests; the Servlet container does all the work. The Servlet container wraps the HTTP request as an HttpServletRequest object, and the Servlet simply calls the various getXXX() methods of the object to easily read the data in the HTTP request.

1.6 ServletResponse interface

The Servlet interface’s service(ServletRequest req, ServletResponse res) method takes a parameter of type ServletResponse, The Servlet generates the response through a ServletResponse object. When the Servlet container receives a request from a client to access a particular Servlet, it creates a ServletResponse object and passes it as an argument to the Servlet’s service() method.

The ServletResponse interface defines a series of methods related to generating response results:

methods instructions
setCharacterEncoding(String charset) Sets the character encoding of the response body. The default to the ISO – 8859-1
setContentLength(int length) Set the length of the response body
setContentType(String type) Set the MIME type of the response body
getCharacterEncoding() Returns the character encoding of the response body
getContentType() Returns the MIME type of the response body
setBufferSize(int size) Sets the size of the buffer used to hold the response body data
getBufferSize() Gets the size of the buffer used to hold the response body data
reset() Clear the body data in the buffer, and clear the response status code and the response header
resetBuffer() Empty only the body data in the buffer, not the response status code and the response header
flushBuffer() The response body data in the buffer is forcibly sent to the client
isCommitted() Return a value of type Boolean; If true, the data in the buffer has been committed to the client, that is, the data has been sent to the client
getOutputStream() Returns a ServletOutputStream object that the Servlet uses to output binary body data
getWriter() Returns a PrintWriter object that the Servlet uses to output body data in the form of a string

The default MIME type of the response body in a ServletResponse is TEXT /plain. The default MIME type for the corresponding body in HttpServletResponse is TEXT/HTML, which is the HTML document type.

ServletResponse objects are used by ServletResponse ServletResponse objects to produce the main body of the HTTP response.

To improve the efficiency of output data, the ServletOutputStream and PrintWriter first write the data to a buffer. The data in the buffer is delivered to the client in the following cases:

  • When the buffer is full, the ServletOutputStream or PrintWriter automatically sends the buffer to the client and clears the buffer
  • The Servlet calls the ServletResponse objectflushBuffer()methods
  • A Servlet calling a ServletOutputStream or PrintWriter objectflush()Method orclose()methods

To ensure that all the data output by a ServletOutputStream or PrintWriter is delivered to the customer, it is safer to call the ServletOutputStream or PrintWriter after all the data has been outputclose()Methods.

Note: To set the MIME type and character encoding of the corresponding body, you must first call the setContentType() and setCharacterEncoding() methods of the ServletResponse object, The ServletResponse’s getOutputStream() or getWriter() methods are then called and the body data in the buffer is committed. The Settings take effect only when the order of operations is met.

1.7 the HttpServletResponse interface

The HttpServletResponse interface is a subinterface of the ServletResponse.

The HttpServletResponse interface provides methods related to the HTTP protocol by which servlets can set HTTP response headers or write cookies to clients:

methods instructions
addHeader(String name, String value) Adds an entry to the HTTP response header
sendError(int sc) An HTTP response status code is sent to the client representing a specific error
sendError(int sc, String msg) An HTTP response status code representing a specific error is sent to the client, along with a specific error message
setHeader(String name, String value) Sets an item in the HTTP response header that is overridden if it exists
setStatus(int sc) Sets the status code for the HTTP response
addCookie(Cookie cookie) Adds a Cookie to the HTTP response

The HttpServletResponse interface defines static constants that represent HTTP response status codes, such as:

constant instructions
HttpServletResponse.SC_BAD_REQUEST 400
HttpServletResponse.SC_FOUND 302
HttpServletResponse.SC_NOT_FOUND 404
HttpServletResponse.SC_OK 200
HttpServletResponse.FORBIDDEN 403
. .

You can set the MIME type and character encoding of the HTTP response body in the following three methods, and the three methods are equivalent:

/ / way
response.setContentType("text/html; charsetr=GBK");
2 / / way
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
3 / / way
response.setHeader("Content-type"."text/html; charset=GBK");
Copy the code

1.8 ServletConfig interface

The init(ServletConfig Config) method of the Servlet interface has a parameter of type ServletConfig. When the Servlet container initializes a Servlet object, a ServletConfig object is created for that Servlet object. The ServletConfig object contains the initialization parameter information for the Servlet. In addition, the ServletConfig object is associated with the ServletContext object for the current Web application.

The ServletConfig interface defines the following methods:

methods instructions
getInitParameter(String name) Returns the matching value of the initialization parameter given by the initialization parameter name
getInitParameterNames() Return an Enumeration object containing the names of all the initialization parameters
getServletContext() Return a ServletContext object
getServletName() Returns the name of the Servlet, the value of the child element of the corresponding element in web.xml, or the name of the Servlet class if not configured

The following code sets two initialization parameters for a HelloServlet class, username and URL:

<servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.one.servlet.HelloServlet</servlet-class>

    <! -- init-param is an initialization parameter and can have multiple groups of parameters -->
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
    <init-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/test</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
Copy the code

1.9 the ServletContext interface

ServletContext is the interface through which servlets communicate with Servlet containers. Each Web application has a unique ServletContext object. The ServletContext object can be visually understood as a Web application manager. All Servlet objects in the same Web application share a manager. Servlet objects can access various resources in the container through this manager.

Methods provided by the ServletContext interface fall into the following types:

(1) Access to shared data within the scope of Web applications

methods instructions
setAttribute(String name, java.lang.Object object) Bind Java objects to property names
getAttribute(String name) Returns an Object of type Object based on the name of the property given by the argument
getAttributeNames() Return an Enumeration object containing the names of all the properties stored in the ServletContext
removeAttribute(String name) The matching property is removed from the ServletContext based on the property name specified by the argument

(2) Access the resources of the current Web application

methods instructions
getContextPath() Returns the URL entry of the current Web application
getInitParameter(String name) Returns the matched initialization parameter in the Web application scope based on the given parameter name
getInitParameterNames() Return an Enumeration object containing the names of all the Web application-wide initialization parameters
getServletContextName() Returns the name of the Web application, i.e
getRequestDispatcher(String path) Returns a RequestDispatcher object used to forward requests to other Web components

(3) Access other Web applications in the Servlet container

methods instructions
getContext(String uripath) Returns a ServletContext object for other Web applications in the current Servlet container, based on the URI

(4) Access information about the Servlet container

methods instructions
getMajorVersion() Returns the major version number of the Java Servlet API supported by the Servlet container
getMinorVersion() Returns the subversion number of the Java Servlet API supported by the Servlet container
getServerInfo() Returns the name and version of the Servlet container

(5) Access the file system resources on the server

methods instructions
getRealPath(String path) Returns a real path in the file system based on the virtual path specified by the parameter
getResource(String path) Returns a URL mapped to the path specified by the parameter
getResourceAsStream(String path) Returns an input stream for reading the file specified by the parameter
getMimeType(String file) Returns the MIME type of the file specified by the argument

(6) Output logs

methods instructions
log(String msg) Log to the Servlet’s log file
log(String message, java.lang.Throwable throwable) Writes the error log, along with stack information about the exception, to the Servlet log file

The getServletContext() method can be called directly from the HttpServlet or GenericServlet classes and subclasses to get the ServletContext object for the current Web application.

2. Servlet life cycle

2.1 Initialization phase

The initialization phase of a Servlet consists of four steps:

  1. The Servlet container loads the Servlet class and reads data from its.class file into memory.
  2. The Servlet container creates the ServletConfig object and associates it with the ServletContext object for the current Web application.
  3. The Servlet container creates Servlet objects.
  4. The Servlet container calls the Servlet objectinit(ServletConfig config)Methods.

A Servlet enters the initialization phase in one of the following situations:

  • A Web application is at run time and a particular Servlet is first requested by a client. Most servlets are initialized by the Servlet container in this case.
  • By setting the element for the Servlet in the web.xml file, the Servlet is initialized when the Servlet container starts the Web application to which the Servlet belongs. If there are servlets that are specifically responsible for doing some initialization for the Web application during the Web application startup phase, they can be initialized at Web application startup.
  • When the Web application is restarted, all servlets are reinitialized at a certain point.

2.2 Runtime phase

When the Servlet container receives a customer request requesting access to a particular Servlet, the Servlet container creates a ServletRequest object and a ServletResponse object for that request. It then calls the service() method on the corresponding Servlet object. The service() method takes the customer request information from the ServletRequest object, processes the request, and generates the response through the ServletResponse object.

When the Servlet container sends the ServletRequest and ServletResponse objects to the customer, the Servlet container destroys the ServletRequest and ServletResponse objects.

2.3 Destruction Phase

When a Web application is terminated, the Servlet container calls the destroy() method on all Servlet objects in the Web application before destroying them. In the implementation of the destroy() method, resources occupied by the Servlet can be released (such as closing file input and output streams, closing connections to the database, and so on).

In addition, the container destroys the ServletConfig object associated with the Servlet object.

3. ServletContextListener

There is a ServletContextListener interface in the Servlet API that listens for the life cycle of the ServletContext object, which is actually listening for the life cycle of the Web application.

When the Servlet container starts or terminates a Web application, the ServletContextEvent event is triggered, which is handled by the ServletContextListener. Two methods for the ServletContextEvent event are defined in the ServletContextListener interface:

methods instructions
contextInitialized(ServletContextEvent sce) This method is called when the Servlet container starts the Web application
contextDestroyed(ServletContextEvent sce) This method is called when the Servlet container terminates the Web application

Here is how to use a ServletContextListener:

public class MyServletContextListenerImpl implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("ServletContext object is created");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("ServletContext object destroyed"); }}Copy the code

Configure in web.xml:

<! -- configure the listener -->
<listener>
    <listener-class>com.one.listener.MyServletContextListenerImpl</listener-class>
</listener>
Copy the code

The above is an example of the use of listeners, and in practical applications, listeners are often used to count the number of pages accessed by clients…

4. Use annotations to configure servlets

To simplify publishing a Web component, instead of configuring the Web component in the web.xml file, you can annotate the configuration directly in the related class using annotations.

For example, @webServlet, @webListener, @webFilter…

The following example uses @webservlet to annotate:

@WebServlet(name="MyServlet", urlPatterns={"/myServlet"}, initParams={ @WebInitParam(name="username",value="w"), @WebInitParam(name="age",value="19") })
public class MyServlet extends HttpServlet {... }Copy the code

5. Process the Encoding of Chinese characters in the HTTP request parameters

If the browser and server use different character encodings for parsing the request parameters, it will result in garbled characters!

Here are some effective ways to solve Chinese garbled characters:

(1) Conduct character encoding conversion for the read request parameters:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html; charset=UTF-8"); . }Copy the code

(2) For POST requests, use the following methods:

request.setCharacterEncoding("GBK");
Copy the code

This code can only set the character encoding in the request body, not in the request header. The request parameters in a GET request are in the request header, so you cannot set the request parameter encoding in a GET request in this way.

(3) using ServletContet object getRequestCharacterEncoding () and setRequestCharacterEncoding () method to read and set the current Web applications request body data of the character encoding.

6. Servlets download/upload files

6.1 Downloading Files

To download a file, you send a file from the server to the client.

Here is the key code to download the sample file:

// 1. Obtain the file name to be downloaded
String downloadFileName = request.getParameter("filename");

// 2. Read the contents of the file to be downloaded (read by the ServletContext object)
ServletContext servletContext = getServletContext();
// Get the type of file to download
String mimeType = servletContext.getMimeType("/file/" + downloadFileName);

// 3. Before sending back, tell the client the returned data type through the response header
resp.setContentType(mimeType);

// 4. Also tell the client that the data received is for download use (again using the response header)
Content-disposition = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
resp.setHeader("Content-Disposition"."attachment; filename=" + downloadFileName);

// Get the input stream that reads the local file
InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
// Get the output stream of the response
ServletOutputStream outputStream = resp.getOutputStream();

// 5. Send the downloaded file back to the client
IOUtils.copy(resourceAsStream, outputStream);
Copy the code

6.2 Uploading a File

Uploading files means sending files from the client to the server.

When a client uploads a file to the server, the HTTP request body sent by the client is of the “multipart/form-data” data type, which represents a complex composite form with multiple sub-parts.

The Apache Open Source software organization provides two software packages related to file uploads:

  • commons-io-xxx.jar
  • commons-fileupload-xxx.jar

For an HTTP request with a body part of type “Multipart /form-data,” the UploadFile package treats each subpart of the composite form contained in the request body as a FileItem object. FileItem objects fall into two types:

  • FormField: a common formField type, such as a text field in a form and a submit button
  • Non-formfield: Upload file type, which is the file field in the form

The following is the basic implementation of uploading files:

// Check whether the file is uploaded with multiple data segments (only if the file is uploaded with multiple data segments).
if (ServletFileUpload.isMultipartContent(req)) {
    // Create a FileItemFactory factory implementation class
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    // Create the ServletFileUpload class for parsing the uploaded data
    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

    // Parse the uploaded data to get each FileItem
    try {
        List<FileItem> list = servletFileUpload.parseRequest(req);

        // Iterate to determine whether each form item is a normal type or an uploaded file
        for (FileItem fileItem : list) {
            if (fileItem.isFormField()) {
                // Normal form items
                System.out.println("The name attribute of the form item:" + fileItem.getFieldName());
                // The utF-8 parameter solves garbled characters
                System.out.println("The value attribute of a form item:" + fileItem.getString("UTF-8"));
            } else {
                // The uploaded file
                System.out.println("The name attribute of the form item:" + fileItem.getFieldName());
                System.out.println("Upload file name:" + fileItem.getName());
				// Save to the specified address of the server
                fileItem.write(new File("D:\\"+ fileItem.getName())); }}}catch(Exception e) { e.printStackTrace(); }}Copy the code

FileItemFactory is the factory that creates FileItem objects.

The DiskFileItemFactory class and the DiskFileItem class implement the FileItemFactory interface and the FileItem interface respectively.

7. Request forwarding

Request forwarding, is the behavior of the server, the request is forwarded by the server to another page for processing, how to forward, when to forward, how many times forward, the client can not know. At Request forwarding, the Servlet container creates the Request and Response objects only once between the first and last Request, and the new page continues to process the same Request. It can also be understood as the server passing Request objects between pages. Request forwarding is essentially a call to another Servlet within a Servlet.

The process of requesting forwarding occurs inside the server. Only the corresponding forwarding resources can be found in the current application, but cannot be forwarded to the resources of other applications. Solves the problem of data sharing among different servlets within one request, but there is a risk of repeated submission of data ~

Core code:

RequestDispatcher dispatcher = getServletContext.getRequestDispatcher("/"); dispatcher.forward(request, response);Copy the code

Features:

  1. The client browser sends the request once and the server processes the rest (request forwarding is a single request regardless of how many pages it jumps to)
  2. The address bar does not change, and the data in the RRL may be repeatedly submitted, which may cause security problems
  3. Parameters can always be passed, and the participating servlets share the Request and Response
  4. Can only jump to internal resources (in the project), cannot jump to external resources (outside the project)
  5. Access to protected resources (WEB-INF)

8. Redirects

Redirection is the behavior of the client. Each Request redirection is initiated by the client. That is to say, once the Request object is redirected, the properties of the Request object are refreshed.

Redirects address one of the risks of request forwarding: data duplication!

Function:

  • Protect the first request, avoid because the user refreshes the action triggered the first request to the Servlet repeat frequently (because of the way if it is GET to submit, using the forward requests to address in the address bar will not change and with the related data, refresh the page once, equal to submit data at a time, there is a dirty data and security risks, To solve this problem, redirection techniques are needed.)

Features:

  • Response redirection is implemented through response objects, jumping several pages to send several requests
  • Address bar will change (last requested path)
  • The parameter cannot be passed all the time, it needs to be passed manually (because it is not the same request)
  • You can jump to either internal or external resources
  • Unable to access protected resources (WEB-INF)

Core code:

response.sendRedirect("/hello");
Copy the code

9. Other advanced uses of servlets

There are many more advanced uses for servlets, including:

  • The image is dynamically generated and sent to the client
  • Read and write cookies to the client
    • For more information on cookies, refer to my next post: To be updated
  • Access the working directory that the Servlet container provides for Web applications
  • Collaborate between Web components
  • Access other Web applications in the Servlet container
  • Handle the concurrency problem caused by multiple clients accessing related resources in Web applications at the same time
  • Asynchronous processing of customer requests
  • Server push (in many cases, the server needs to proactively send some information to the client)
  • .

As I said at the beginning, the upper limit of servlets depends on the Java technical upper limit of the programmer, as long as he has a deep Java programming background, he can write a variety of servlets to achieve a variety of complex functions…

Original is not easy to 🧠 reprint please indicate the source if 💕 ~ in this paper, some help to you, thumb up support and 🥰 this is my lot warehouse, welcome to onlookers ~ 👻