jsp - initial jsp and servlet

Keywords: Java JSP Tomcat servlet

1, JSP

JSP is a special file format. It can embed Java code in html, but it is essentially a subclass of Servlet

JSP execution process:
The browser requests JSP from the server - > the server finds the corresponding JSP file - > translates it into Java code and compiles it for execution - > returns the execution result to the server
Here is a simple JSP code

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>MyJSP</title>
</head>
<body>
//Declarative: used to declare member variables in Jsp
<%!
    int count = 0;
%>
//Used for business logic operation in JSP
<% count++;
%>
<h3>
//Expression: used to output content in jsp
    <%="Number of visits"+count%>
</h3>
</body>
</html>

After the above JSP is translated into java

public final class MyJsp_jsp extends HttpJspBase implements JspSourceDependent, JspSourceImports {
    int count = 0;
    private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    private static Map<String, Long> _jspx_dependants;
    private static final Set<String> _jspx_imports_packages = new HashSet();
    private static final Set<String> _jspx_imports_classes;
    private volatile ExpressionFactory _el_expressionfactory;
    private volatile InstanceManager _jsp_instancemanager;

    static {
        _jspx_imports_packages.add("javax.servlet");
        _jspx_imports_packages.add("javax.servlet.http");
        _jspx_imports_packages.add("javax.servlet.jsp");
        _jspx_imports_classes = null;
    }

    public MyJsp_jsp() {
    }

    public Map<String, Long> getDependants() {
        return _jspx_dependants;
    }

    public Set<String> getPackageImports() {
        return _jspx_imports_packages;
    }

    public Set<String> getClassImports() {
        return _jspx_imports_classes;
    }

    public ExpressionFactory _jsp_getExpressionFactory() {
        if (this._el_expressionfactory == null) {
            synchronized(this) {
                if (this._el_expressionfactory == null) {
                    this._el_expressionfactory = _jspxFactory.getJspApplicationContext(this.getServletConfig().getServletContext()).getExpressionFactory();
                }
            }
        }

        return this._el_expressionfactory;
    }

    public InstanceManager _jsp_getInstanceManager() {
        if (this._jsp_instancemanager == null) {
            synchronized(this) {
                if (this._jsp_instancemanager == null) {
                    this._jsp_instancemanager = InstanceManagerFactory.getInstanceManager(this.getServletConfig());
                }
            }
        }

        return this._jsp_instancemanager;
    }

    public void _jspInit() {
    }

    public void _jspDestroy() {
    }

    public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if (!DispatcherType.ERROR.equals(request.getDispatcherType())) {
            String _jspx_method = request.getMethod();
            if ("OPTIONS".equals(_jspx_method)) {
                response.setHeader("Allow", "GET, HEAD, POST, OPTIONS");
                return;
            }

            if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
                response.setHeader("Allow", "GET, HEAD, POST, OPTIONS");
                response.sendError(405, "JSPs only permit GET, POST or HEAD. Jasper also permits OPTIONS");
                return;
            }
        }

        JspWriter out = null;
        JspWriter _jspx_out = null;
        PageContext _jspx_page_context = null;

        try {
            response.setContentType("text/html;charset=UTF-8");
            PageContext pageContext = _jspxFactory.getPageContext(this, request, response, (String)null, true, 8192, true);
            _jspx_page_context = pageContext;
            pageContext.getServletContext();
            pageContext.getServletConfig();
            pageContext.getSession();
            out = pageContext.getOut();
            out.write("\r\n");
            out.write("\r\n");
            out.write("<html>\r\n");
            out.write("<head>\r\n");
            out.write("    <title>MyJSP</title>\r\n");
            out.write("</head>\r\n");
            out.write("<body>\r\n");
            out.write(13);
            out.write(10);
            ++this.count;
            out.write("\r\n");
            out.write("<h3>\r\n");
            out.write("    ");
            out.print("Number of visits" + this.count);
            out.write("\r\n");
            out.write("</h3>\r\n");
            out.write("</body>\r\n");
            out.write("</html>\r\n");
        } catch (Throwable var13) {
            if (!(var13 instanceof SkipPageException)) {
                out = (JspWriter)_jspx_out;
                if (_jspx_out != null && ((JspWriter)_jspx_out).getBufferSize() != 0) {
                    try {
                        if (response.isCommitted()) {
                            out.flush();
                        } else {
                            out.clearBuffer();
                        }
                    } catch (IOException var12) {
                    }
                }

                if (_jspx_page_context == null) {
                    throw new ServletException(var13);
                }

                _jspx_page_context.handlePageException(var13);
            }
        } finally {
            _jspxFactory.releasePageContext(_jspx_page_context);
        }

    }
}

2, Servlet

Servlet is a Java class used to accept the browser's request and return it to the browser's response. Its writing process is as follows

  1. Write an inherited HttpServlet class
  2. Override service method
  3. Configure the access path in web.xml in the WEB-INF folder

web.xml

<?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">
    <context-param>
        <param-name>enc</param-name>
        <param-value>utf-8</param-value>
    </context-param>
    <servlet>
        <servlet-name>test1</servlet-name>
        <servlet-class>com.bigWhiteXie.servlet.MyServelet</servlet-class>
        <init-param>
            <param-name>enc</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>test1</servlet-name>
        <url-pattern>/test1</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>DoLogin</servlet-name>
        <servlet-class>com.bigWhiteXie.servlet.DoLogin</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DoLogin</servlet-name>
        <url-pattern>/DoLogin</url-pattern>
    </servlet-mapping>
</web-app>

A Servlet class

package com.bigWhiteXie.servlet;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;


public class MyServelet extends HttpServlet {
    private String message;
    static int count = 0;
    @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("<h1>Welcome to visit</h1>");

            out.print("Number of visits:"+(++count));
        out.print("</body>");
        out.print("</html>");
    }
}

3, Life cycle of Servlet

  1. Class loading
    • Class loading time: the default is when the servlet subclass is accessed for the first time
    • < load on startup > 0 < / load on startup > (load when starting the server, set in the < servlet > tab) the smaller the number, the more forward the loading time
  2. Instantiation, instantiation using reflection
  3. initialization
  4. service request
  5. Destroy

Execution sequence of life cycle function of a servlet:
Execute constructor - > execute init() (generally used to load or read configuration files) - > execute service() -- > execute destroy()

4, Servlet core source code

  • First, let's take a look at the inheritance relationship of Serlet
    • Servlet - > genericservlet - > httpservlet - > Custom servlet subclass

Servlet

public interface Servlet {
    void init(ServletConfig var1) throws ServletException;

    ServletConfig getServletConfig();

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

    String getServletInfo();

    void destroy();
}

As you can see, the servlet provides us with the five main functions as an interface

ServletConfig

public interface ServletConfig {
	//Gets the name set by the Servlet in web.xml
    String getServletName();
    
	//Gets the global variable set in web.xml
    ServletContext getServletContext();
    
	//Gets the initial variable of the Servlet
    String getInitParameter(String var1);
    
	//Gets the name of the Servlet initial variable
    Enumeration<String> getInitParameterNames();
}

GenericServlet

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
    private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.LocalStrings");
    private transient ServletConfig config;

    public GenericServlet() {
    }

    public void destroy() {
    }
	//Method for obtaining initialization parameters
    public String getInitParameter(String name) {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getInitParameter(name);
        }
    }

    public Enumeration<String> getInitParameterNames() {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getInitParameterNames();
        }
    }

    public ServletConfig getServletConfig() {
        return this.config;
    }

    public ServletContext getServletContext() {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getServletContext();
        }
    }

    public String getServletInfo() {
        return "";
    }
    
	//Pass in a ServletConfig implementation class and set it as a member variable
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {
    }

    public void log(String msg) {
        this.getServletContext().log(this.getServletName() + ": " + msg);
    }

    public void log(String message, Throwable t) {
        this.getServletContext().log(this.getServletName() + ": " + message, t);
    }

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

    public String getServletName() {
        ServletConfig sc = this.getServletConfig();
        if (sc == null) {
            throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
        } else {
            return sc.getServletName();
        }
    }
}

As can be seen from the above code, GenericServlet implements all methods except Service.

HttpServlet

The source code of HttpServlet will not be posted. We only know that HttpServlet mainly implements the service method. The purpose is to return an error to the browser when the subclass does not rewrite the service method.

5, Servlet reads initial parameters and global parameters

To read initialization parameters and global parameters, you first need to set them in the web.xml file

//Global parameters
<context-param>
        <param-name>enc</param-name>
        <param-value>utf-8</param-value>
    </context-param>
    <servlet>
        <servlet-name>test1</servlet-name>
        <servlet-class>com.bigWhiteXie.servlet.MyServelet</servlet-class>
        //Initialization parameters
        <init-param>
            <param-name>enc</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </servlet>

read

Reading initialization parameters only needs to be in the corresponding servlet Class
String enc = this.getInitParameter("enc");
Read global parameters
String enc1 = this.getServletContext().getInitParameter("enc");

6, Servlet handles Chinese garbled code of request

When the request is post
request.setCharacterEncoding("utf-8");
When the request is get
Specify the corresponding server code in server.xml
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8" />

Posted by gerrydewar on Sun, 19 Sep 2021 04:18:36 -0700