Servlet from entry to proficiency

Keywords: Java JDBC Web Server xml

Servlet from entry to proficiency

Introduction to Servlet

Servlet is a technology provided by sun Company for developing dynamic web resources.
Sun provides a servlet interface in its API. Users need to complete the following two steps if they want to send a dynamic web resource (that is, to develop a Java program to output data to the browser):
1. Write a Java class to implement the servlet interface.
2. Deploy the developed Java classes to the web server.
According to a convention of address, we usually call the java program that implements the servlet interface Servlet.

Running process of Servlet

The Servlet program is called by the WEB server. After the web server receives the Servlet access request from the client side:
The Web server first checks whether the instance object of the Servlet has been loaded and created. If so, step 4 will be implemented directly, otherwise step 2 will be implemented.
(2) Load and create an instance object of the Servlet. 
(3) Call the init() method of the Servlet instance object.
(4) Create an HttpServletRequest object for encapsulating HTTP request messages and an HttpServletResponse object representing HTTP response messages, then call the service() method of the Servlet and pass in the request and response objects as parameters.
Before the WEB application is stopped or restarted, the Servlet engine will uninstall the Servlet and call the destroy() method of the Servlet before uninstalling. 

Servlet interface implementation class

Servlet Interface SUN Company defines two default implementation classes: Generic Servlet and HttpServlet.
HttpServlet refers to a servlet that can handle HTTP requests. It adds some HTTP protocol processing methods to the original Servlet interface, which is more powerful than the Servlet interface. Therefore, when writing a servlet, developers should usually inherit this class instead of directly implementing the servlet interface.
When HttpServlet implements the Servlet interface, it overrides the service method. The code in this method can automatically determine the user's request mode. If it is a GET request, it calls the doGet method of HttpServlet, and if it is a Post request, it calls the doPost method. Therefore, when writing servlets, developers usually only need to override the doGet or doPost method, rather than the service method.

The Difference between Servlet and Ordinary Java Classes

Servlet is a Java class called by other Java programs (Servlet engine). It can not run independently. Its operation is completely controlled and scheduled by the Servlet engine.
For multiple Servlet requests from clients, usually the server will only create a Servlet instance object, that is to say, once the Servlet instance object is created, it will reside in memory and serve other subsequent requests until the web container exits, the servlet instance object will be destroyed.
The init method of the servlet is invoked only once throughout the lifecycle of the servlet. Each access request to a servlet causes the servlet engine to call the service method of the servlet once. For each access request, the Servlet engine creates a new HttpServletRequest request object and a new HttpServletResponse response object, then passes these two objects as parameters to the service() method of the Servlet it calls, and the service method calls the doXXX method separately according to the request mode.
If a < load-on-startup > element is configured in the < Servlet > element, the WEB application loads and creates instance objects of the Servlet and invokes init() method of the instance object of the Servlet when it starts.
    Give an example:
    <servlet>
        <servlet-name>invoker</servlet-name>
        <servlet-class>
            org.apache.catalina.servlets.InvokerServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

Purpose: Write an InitServlet for a web application. This servlet is configured to load at startup and create the necessary database tables and data for the entire web application.

Servlet's Single Multithreading (Thread Safety Problem)
Step: http://blog.csdn.net/qq_35712358/article/details/71124119

Create projects to learn Servlet

ServletConfig object

Each servlet has a ServletConfig object. Used to initialize Servlet parameters
Configure Servlet initialization parameters: In the Servlet configuration file web.xml, you can configure some initialization parameters for the servlet using one or more <init-param> tags.
<servlet>
    <servlet-name>servletConfigTest</servlet-name>
    <servlet-class>com.demo.servlet.ServletConfigTest</servlet-class>
    <init-param>
      <param-name>name</param-name>
      <param-value>dongyangyang</param-value>
    </init-param>
    <init-param>
      <param-name>password</param-name>
      <param-value>123456</param-value>
    </init-param>
    <init-param>
      <param-name>charset</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>servletConfigTest</servlet-name>
    <url-pattern>/servletConfig</url-pattern>
  </servlet-mapping>
package com.demo.servlet;

/**
 * ServletConfig Demonstration
 */
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletConfigTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * Define ServletConfig objects to receive configuration initialization parameters
     */
    private ServletConfig config;

    public ServletConfigTest() {
        super();
    }

    /**
     * When the servlet configures the initialization parameters, the web container creates the servlet instance object.
     * These initialization parameters are automatically encapsulated in the ServletConfig object, and when the init method of the servlet is invoked,
     * Pass the ServletConfig object to the servlet. Then you can use the ServletConfig object
     * Get the initialization parameter information of the current servlet.
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.config = config;
    }

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

        //---------------------ServletConfig---------------------start
        //Get the initialization parameters configured in web.xml
        String paramVal = this.config.getInitParameter("name");//Gets the specified initialization parameters
        response.getWriter().print(paramVal);   
        //ie supports hr/,br/. Firefox, Google does not support
        response.getWriter().print("<hr/>");
        //Get all initialization parameters
        Enumeration<String> e = config.getInitParameterNames();
        while(e.hasMoreElements()){
            String name = e.nextElement();
            String value = config.getInitParameter(name);
            response.getWriter().print(name + "=" + value + "<br/>");
        }
        //---------------------ServletConfig---------------------end

        //---------------------ServletContext---------------------start
        ServletContext context = this.config.getServletContext();
        String data = (String)context.getAttribute("data");
        response.getWriter().print( "data = " + data);
        //---------------------ServletContext---------------------end
    }

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

}

ServletContext object

When the WEB container starts, it creates a corresponding ServletContext object for each WEB application, which represents the current web application.
References to ServletContext objects are maintained in ServletConfig objects. When writing servlet s, developers can obtain ServletContext objects through the ServletConfig.getServletContext method.
Since all Servlets in a WEB application share the same ServletContext object, communication between ServletContext objects can be achieved through ServletContext objects. ServletContext objects are also commonly referred to as context domain objects.
1. Multiple Servlets Share Data through ServletContext Objects
 2. Get the initialization parameters of WEB application. web.xml add:
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/test</param-value>
    </context-param>

Here we show ServletContextTest and ServletConfigTest data sharing

package com.demo.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * WEB When the container starts, it creates a corresponding ServletContext object for each Web application, which represents the current web application.
  ServletConfig The reference of the ServletContext object is maintained in the object. When writing the servlet, the developer can obtain the ServletContext object through the ServletConfig.getServletContext method.
  Since all Servlets in a WEB application share the same ServletContext object, communication between ServletContext objects can be achieved through ServletContext objects. ServletContext objects are also commonly referred to as context domain objects.
 * @author 353654
 *
 */
@WebServlet("/servletContext")
public class ServletContextTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ServletContextTest() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data = "Hello!!!";
        //Getting ServletContext from ServletConfig object
        ServletContext context = this.getServletConfig().getServletContext();
        context.setAttribute("data", data);//Store data in the ServletContext object

        //Get the initialization parameter url for web container startup
        String parameter = context.getInitParameter("url");
        System.out.println(parameter);
        response.getWriter().print("url = " + parameter);
    }

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

}

SerletContext implements request forwarding

package com.demo.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/servletForward")
public class ServletForwardTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ServletForwardTest() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//      String data = "< H1 > < font color ='red'> servlet Forward forwarded to servlet Forward 2 < / font > < / H1 >";
//      response.setCharacterEncoding("utf-8");
//      response.getOutputStream().write(data.getBytes());
        //Get the ServletContext object
        ServletContext context = this.getServletContext();
        //Get the Request Dispatcher
        RequestDispatcher rd = context.getRequestDispatcher("/servletForward2");
        System.out.println("servletForward Forwarding to servletForward2");
        rd.forward(request, response);//Calling forward method to realize request forwarding
    }

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

}
package com.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/servletForward2")
public class ServletForwardTest2 extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ServletForwardTest2() {
        super();
    }

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


        //Use response.getOutputStream() to output Chinese to the browser. Whether it outputs characters, Chinese characters or numbers, it must output byte arrays.
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        //response.setContentType("text/html;charset=UTF-8");
        response.getOutputStream().write("Cao Jie".getBytes("UTF-8"));//Setting up the Server Code Set
//      response.getOutputStream().write("CaoJie". getBytes (); // Default Workspace Coding

        //Use response.getWriter() to output Chinese to the browser
//      response.setHeader("content-type", "text/html;charset=UTF-8");
//      response.setCharacterEncoding("UTF-8");
//      PrintWriter out = response.getWriter();
//      // Learn more: Use the <meta> tag in HTML to control the browser behavior, and simulate setting the response head to control the browser behavior.
//      //out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'/>");
//      out.write("Cao Jie"); use PrintWriter to output characters to the client
    }

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

}

ServletContext object reads resource files

package com.demo.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Read the resource file through the ServletContext object
 * @author 353654
 *
 */
@WebServlet("/servletContextReadFile")
public class ServletContextReadFileTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ServletContextReadFileTest() {
        super();
    }

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

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

    /**
     * Read the jdbc.properties configuration file in the conf directory through the ServletContext object
     */
    private void readResourceFile(HttpServletResponse response) throws IOException{
        /** 
         * getResourceAsStream()Refers to the webRoot/webapp directory 
         * Read the configuration file in the webRoot/webapp directory 
         * getResourceAsStream("db.properties") 
         * Read the configuration file under src 
         * getResourceAsStream("/WEB-INF/classes/db.properties") 
         */
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/jdbc.properties");
        InputStreamReader in = new InputStreamReader(new FileInputStream(path),"utf-8");
        Properties prop = new Properties();
//        InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/jdbc.properties");
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("read conf Catalogue jdbc.properties Configuration file:");
        response.getWriter().println(MessageFormat.format("driver={0},url={1},username={2},password={3}",driver,url,username,password));
    }
}

Class loader reads resource files

package com.demo.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Reading Resource Files with Class Loader
 */
@WebServlet("/classLoaderReadFile")
public class ClassLoaderReadFileTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ClassLoaderReadFileTest() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("content-type","text/html;charset=UTF-8");
        readResourceFile(response);
    }

    private void readResourceFile(HttpServletResponse response) throws IOException {
        //Gets the class loader that loads the current class
        ClassLoader loader = ClassLoaderReadFileTest.class.getClassLoader();
        //Read db1.properties configuration file in src directory with class loader
        InputStream in = loader.getResourceAsStream("jdbc.properties");
        Properties prop = new Properties();
        prop.load(in);
        String driver = prop.getProperty("driver");
        String url = prop.getProperty("url");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        response.getWriter().println("Read with class loader src Catalogue jdbc.properties Configuration file:");
        response.getWriter().println(
                MessageFormat.format("driver={0},url={1},username={2},password={3}", 
                                        driver,url, username, password));
    }

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

}

Caching the output of the Servlet on the client side

package com.demo.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/servletCache")
public class ServletCacheTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ServletCacheTest() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data = "Dong Yang-------servlet cache";
        /**
         * Setting a reasonable cache time value of data to avoid frequent requests from browsers to servers and improve the performance of servers
         * Here you set the data caching time to one day
         */
        response.setHeader("content-type","text/html;charset=UTF-8");
        response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000);
        response.getOutputStream().write(data.getBytes());
    }

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

}

Servlet download file

package com.demo.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * When downloading file functions, use OutputStream streams instead of PrintWriter streams.
 * Because the OutputStream stream is a byte stream, it can process any type of data.
 * PrintWriter stream is a character stream, which can only process character data. If byte data is processed with character stream, data will be lost.
 */
@WebServlet("/downLoad")
public class DownLoadServletTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public DownLoadServletTest() {
        super();
    }

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

    /**
     * Download the file through the Output Stream stream
     * @param response
     * @throws IOException 
     */
    private void downloadFileByOutputStream(HttpServletResponse response) throws IOException {
        //Get the absolute path of the file to download and read the download folder under the webapp directory
        String realPath = this.getServletContext().getRealPath("/download/Dong Yang.JPG");
        //Get the file name to download
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //Set content-disposition response header to control the browser to open the file in the form of download. The Chinese file name should be encoded by URLEncoder.encode method, otherwise the file name will be scrambled.
        response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
        InputStream in = new FileInputStream(realPath);//Get the file input stream
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer,0,len);//Output data from buffer to client browser
        }
        in.close();
    }

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

}

Posted by not_skeletor on Wed, 03 Jul 2019 18:11:59 -0700