Simple introduction to Servlet

Posted by a-mo on Tue, 18 Jan 2022 06:19:58 +0100

509 Servlet for dynamic web page development

Myservlet:

package com.bjsxt.servlet;

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

public class Myservlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         PrintWriter out = resp.getWriter();
         out.print("<html>");
         out.print("<head>");
         out.print("</head>");
         out.print("<body>");
         out.print("<h3>This is my first servlet ha-ha</h3>");
         out.print("</body>");
         out.print("</html>");

    }
}
How to display the web page written by Myservlet in the browser?
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>a</servlet-name>
        <servlet-class>com.bjsxt.servlet.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>a</servlet-name>
        <url-pattern>/abc</url-pattern>
    </servlet-mapping>
</web-app>
As a result, there are garbled codes in Chinese. How to solve them?

Plus: server response code!

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

package com.bjsxt.servlet;

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

public class MyServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.print("<html>");
        out.print("<head>");
        out.print("</head>");
        out.print("<body>");
        out.print("<h3>This is my first servlet ha-ha</h3>");
        out.print("</body>");
        out.print("</html>");

    }
}

Use this way to develop dynamic web pages! It's too troublesome!

510 Servlet for process control

What are the disadvantages of Login and doLogin?
  1. Success should jump to a new interface! Failed to return to the original page!

Solution: request getRequestDispatcher(“success.jsp”). forward(request,response);

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Process login operation</title>
</head>
<body>
<%--http://localhost:8080/jsp01/doLogin.jsp?uname=2&pwd=4--%>
<%
    //[A] Receive login Data from JSP

    String u = request.getParameter("uname");
    String p = request.getParameter("pwd");
    //[B] Data processing -- take the user and password to the database for comparison
    boolean flag = false;
    if("sxt".equals(u)&&"123".equals(p)){
        flag =true;
    }
    //[C] Respond to users
    if(flag){
        //out.print("login succeeded");
        //Page Jump forwarding can be realized
        request.getRequestDispatcher("success.jsp").forward(request,response);
    }else {
        //out.print("login failed");
        request.getRequestDispatcher("Login.jsp").forward(request,response);
    }
%>
</body>
</html>
  1. JSP itself is responsible for content display, but now JSP is used for process control

How to solve it?

package com.bjsxt.servlet;

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

public class DoLogin extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //[A] Receive login Data from JSP

        String u = request.getParameter("uname");
        String p = request.getParameter("pwd");
        //[B] Data processing -- take the user and password to the database for comparison
        boolean flag = false;
        if("sxt".equals(u)&&"123".equals(p)){
            flag =true;
        }
        //[C] Respond to users
        if(flag){
            //out.print("login succeeded");
            //Page Jump forwarding can be realized
            request.getRequestDispatcher("success.jsp").forward(request,response);
        }else {
            //out.print("login failed");
            request.getRequestDispatcher("Login.jsp").forward(request,response);
        }
    }
}
<servlet>
    <servlet-name>doLogin</servlet-name>
    <servlet-class>com.bjsxt.servlet.DoLogin</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>doLogin</servlet-name>
    <url-pattern>/doLogin</url-pattern>
</servlet-mapping>

Subsection: what is a Servlet

Servlet is a dynamic web page technology based on Java technology. It runs on the server and is managed by servlet container to generate dynamic content. Is the predecessor of JSP

Servlet is a platform independent java class conforming to specific specifications. Writing a servlet is actually writing a java class according to the servlet specification.

Servlet s are not directly called by users or programmers, but managed by the container (Tomcat) without the main() method.

Relationship between Servlet and JSP

All JSP S must first be translated into servlets, then compiled into class es, and finally executed

JSP is essentially a Servlet

JSP execution process

. jsp - Translation - long java(Servlet) -- compile - class ------ execution -

Has the Servlet been eliminated after the emergence of JSP?

No,

No longer use servlets to implement dynamic web pages

Servlet s are now used to control operations

511 Servlet lifecycle

1. Life cycle

servlet is a single instance multithreaded program

servlet lifecycle

[1] class loading

​ "com.bjsxt.servlet.LifeServlet"

​ Class clazz= Class.forName("com.bjsxt.servlet.LifeServlet");

[2] instantiation (inseparable from reflection)

​ Object obj= clazz.newInstance();

[3] initialization (inseparable from reflection)

[4] service request (inseparable from reflection)

[5] destruction (inseparable from reflection)

Class loading timing

[1] by default, the class is loaded when the servlet is accessed for the first time

[2] 0 (loaded when the server is started) the smaller the number, the more forward the loading time

The Servlet life cycle can be defined as the whole process from creation to destruction. The following is the procedure followed by the Servlet:

  • After Servlet initialization, the init () method is called.
  • The Servlet calls the service() method to process the client's request.
  • The destroy() method is called before Servlet destroys.
  • Finally, the Servlet is garbage collected by the JVM's garbage collector.

https://www.runoob.com/servlet/servlet-life-cycle.html

The following figure shows a typical Servlet lifecycle scenario.

  • The first HTTP request to the server is delegated to the Servlet container.
  • The Servlet container loads the Servlet before calling the service() method.
  • Then the Servlet container processes multiple requests generated by multiple threads, and each thread executes the service() method of a single Servlet instance.

512 Servlet API content

  1. Why do I have to write a service method?

web.xml

<servlet>
    <servlet-name>myServlet2</servlet-name>
    <servlet-class>com.bjsxt.servlet.MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet2</servlet-name>
<url-pattern>/MyServlet2</url-pattern>
</servlet-mapping>

Run directly to view the results:

HTTP Status 405 - HTTP method GET is not supported by this URL

Find the reason in combination with the source code:

public interface Servlet {
    //init has parameters!
    void init(ServletConfig var1) throws ServletException;

    ServletConfig getServletConfig();
    //The parameter is ServletRequest and servletresponse! You can guess with HttpServletRequest HttpServletResponse

    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

    String getServletInfo();

    void destroy();
}

GenericServlet

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    
public void init(ServletConfig config) throws ServletException {
    this.config = config;
    this.init();
}

public void init() throws ServletException {
}
    //No rewriting
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

HttpServlet

public abstract class HttpServlet extends GenericServlet implements Serializable {

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request;
        HttpServletResponse response;
        try {
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)res;
        } catch (ClassCastException var6) {
            throw new ServletException("non-HTTP request or response");
        }
		//Jump to your overloaded service method
        this.service(request, response);
    }
}

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //get or post the submission method
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                //Call your own doGet
                this.doGet(req, resp);
            } else {
                long ifModifiedSince = req.getDateHeader("If-Modified-Since");
                if (ifModifiedSince < lastModified) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //Get the Protocol http protocol 1.1 https protocol...
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_get_not_supported");
        if (protocol.endsWith("1.1")) {
            //It's a mistake in the picture!
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, 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")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }

It can be seen from the source code that an error will be reported if the service method is not rewritten!

You can override doGet() and doPost()!

513 Servlet reads initialization values and global parameters

Problem: the code changes. You need to modify the utf-8 - > GBK of the service method in all servlet s!

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

Parameter extraction:

package com.bjsxt.servlet;

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

public class ParamServlet extends HttpServlet {
    String enc ;
    @Override
    public void init() throws ServletException {
        //Read properties file
        //Read initialization parameters
         enc = this.getInitParameter("abc");
        //Mode 2 is equivalent to only one servlet class
       // enc=this.getServletConfig().getInitParameter("abc");
        System.out.println("Initialization parameters"+enc);

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset="+enc);


    }
}
<servlet>
    <servlet-name>paramServlet</servlet-name>
    <servlet-class>com.bjsxt.servlet.ParamServlet</servlet-class>
    <!--Initialization parameters-->
    <init-param>
        <param-name>abc</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>paramServlet</servlet-name>
    <url-pattern>/ParamServlet</url-pattern>
</servlet-mapping>
    <!--Global parameters can be defined by multiple parameters servlet read-->
<context-param>
    <param-name>ab</param-name>
    <param-value>utf-8</param-value>
</context-param>
/Read global parameters
       ab = this.getServletContext().getInitParameter("ab");

Processing of Chinese garbled code in 514 Servlet

1. How to solve the request garbled code?
2. Differences between get and Post submission methods

[1] The transfer of get data is not secure, and the transfer of post data is more secure

[2] There is a size limit for get data transfer and no limit for post data transfer

[3] The data transfer speed of get is relatively fast and post is relatively slow

How to solve the problem of post submission in Chinese?

request.setCharacterEncoding("utf-8");

public class DoLogin extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //[A] Receive login Data from JSP
        request.setCharacterEncoding("utf-8");
How to solve the problem? Mode 1:
//Solve the garbled code of get method
//1. Get the element encoded array
byte[] bytes = u.getBytes("ISO-8859-1");
//2. Convert the original encoded byte array to UTF-8 encoding format
String str = new String(bytes,"utf-8");

System.out.println("after"+str);

//[B] Data processing -- take the user and password to the database for comparison
boolean flag = false;
if("Shang Xuetang".equals(str)&&"123".equals(p)){
    flag =true;
}

Mode 2:

On the server Specify the corresponding server code in XML

URIEncoding="utf-8"

Topics: Java servlet