Java study notes-Day53 Servlet and JSP (1)



One, Servlet

1 Introduction


Servlet is a component that runs on the server side and can return dynamic pages to the client.

Servlet is multi-threaded, single-instance. When multiple clients request access to a Servlet at the same time, the Web application server will start a thread to serve each client's connection. When accessing a Servlet for the first time, the server will create an object of the Servlet class and call the doXxx method to generate a response. When multiple clients access the same Servlet, they no longer create new objects, but share the same Servlet object.

Servlet is a java class, this class must inherit from javax.servlet.http.HttpServlet class (abstract class), the parent class of HttpServlet is the GenericServlet abstract class. Servlet can also inherit the GenericServlet abstract class. Usually a new package named controller is created in the web project to store the servlet file.

Servlet instance variables are not thread-safe (not modified by the Synchronized keyword).

Insert picture description here
The Servlet class uses doXxx methods to provide services, which are inherited from the HttpServlet class. Looking at the API, you can see that the doXxx method has two parameters, which are request and response. The server will create a request object and a response object and pass it to the doXxx method. The request and response object can be used directly in the doXxx method.

HttpServlet method:

method description
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to process a DELETE request.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle a GET request.
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to handle an OPTIONS request.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to process a POST request.
protected void doPut(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to process a PUT request.
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) Called by the server (via the service method) to allow a servlet to process a TRACE request.
protected long getLastModified(HttpServletRequest req) Returns the time when the HttpServletRequest object was last modified, in milliseconds, starting at midnight on January 1, 1970, Greenwich Mean Time.
protected void service(HttpServletRequest req, HttpServletResponse resp) Receive a standard HTTP request from the public service method and assign it to the doXXX method defined in the class.
void service(ServletRequest req, ServletResponse res) Assign the client request to the protected service method.

doGet method:

(1) Set the request encoding format.

	// 程序最先做的事情是设置请求编码的格式
	request.setCharacterEncoding("utf-8");

(2) Get the value of op.

   <form action="bs.do" method="post">
      <input type="text" name="blogtitle" placeholder="请输入标题" required><br/>
      <textarea rows="10" cols="60" name="blogcontent" placeholder="请输入内容" required></textarea>
      <!-- 通过隐藏域告诉Servlet这里做的操作是增加 -->
      <input type="hidden" name="op" value="add" >
      <br/>
      <input type="submit" value="添加">
   </form>

(3) Perform different operations according to different op values.

	request.setCharacterEncoding("utf-8");
	String op = "";
	if (request.getParameter("op") != null) {
    
    
		op = request.getParameter("op");
	}

	if ("login".equals(op)) {
    
    
		doLogin(request, response);//自定义的方法
	} else {
    
    
		doQuery(request, response);//自定义的方法
	}

2. Life cycle


Servlet is a singleton mode. When a user requests access to a Servlet from a browser for the first time, the life cycle of the corresponding Servlet is:

1. Instantiation and loading (created by Tomcat)
2. Initialization (init method, executed only once)
3. Service service (doXxx method, executed multiple times)
4. Destroy (destory method)
5. Garbage collection (finalize method, virtual machine) Call, execute only once)

Specific process:

(1) Tomcat calls the Servlet construction method to create an object of this class.
(2) Tomcat calls the initialization method in the JavaEE API: first call the init method with parameters, and then call the init method without parameters to perform the initialization work. (The init method is executed only once)
(3) After the initialization is successful, call the service method, and call the corresponding doXxx methods, such as doGet, doPost, etc., by judging the request mode. (The service method is executed multiple times)
(4) After the doXxx method returns normally, the service is finished.
(5) Tomcat destroys the Servlet object at an appropriate time according to its usage, and calls the destroy method before it is destroyed.
(6) Garbage collection finalize method (called by the virtual machine, executed only once).

3. Servlet loading startup options


By default, the server will initialize the Servlet instance only when the Servlet is accessed for the first time. If you need to initialize the Servlet instance when Tomcat starts, you can configure it in web.xml or @WebServlet.

(1) Configure in WebContent->WEB-INF->web.xml so that Servlet can be instantiated when Tomcat is started. <load-on-startup>2</load-on-startup>The number 2 in does not indicate the number, but the order in which the servlet starts. Servlet will always be instantiated only one object.

<servlet>
    <description></description>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.etc.train.controller.TestServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>	

(2) LoadOnStartup can be configured in @WebServlet. The default value of loadOnStartup is -1. When the value is -1, the Servlet will not be instantiated when Tomcat starts.

	@WebServlet(urlPatterns = "/TestServlet",loadOnStartup=1)
public class TestServlet extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
    public TestServlet() {
    
    
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
		doGet(request, response);
	}
}

4. Servlet configuration access path


(1) @WebServlet annotation (placed in front of the Servlet class):

	@WebServlet("/ts.do")
	public class TestServlet extends HttpServlet {
    
    }

If the path of @WebServlet is /a/b/c/d/ts.do, and the path of forwarding or redirecting is index.jsp, when forwarding or redirecting is performed, the path of forwarding or redirecting will become 项目名/a/b/c/d/index.jsp. This problem can be solved by setting the forwarding or redirecting path to an absolute path.

  • Servlet:, request.getContextPath()+路径名for examplerequest.getContextPath()+"index.jsp"
  • In JSP:, ${pageContext.request.contextPath}+路径名for example${pageContext.request.contextPath}+"index.jsp"

(2) web.xml file:

	<servlet>
		<servlet-name>ts</servlet-name>
		<servlet-class>com.etc.bs.controller.TestServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>ts</servlet-name>
		<url-pattern>/ts.do</url-pattern>
	</servlet-mapping>

4. Configure the default home page


The default home page can be configured in web.xml. When no specific access path is specified, the default home page is accessed by default. It will be accessed in order, and a 404 error will be reported if none exists. When the web.xml modification is completed, Tomcat needs to be restarted.

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
</welcome-file-list>

5. Request and Response


The server implements the request and response interfaces, and the implementation classes are RequestFacade and ResponseFacade . Every time a Servlet is accessed, the server creates a request object and a response object to pass to the doXxx method of the Servlet class.

5.1, Request request


All data submitted to the server through the browser is called request data. In the Servlet API, a request interface is defined to encapsulate and manipulate request data.

The implementation class of Request is requestFacade, which implements the HttpServletRequest interface, which inherits from the ServletRequest interface.

HttpServletRequest interface: responsible for processing the request (Tomcat instantiates it), the javax.servlet.http.HttpServletRequest interface inherits from the javax.servlet. ServletRequest interface.

5.1.1, ServletRequest interface method


(1) public void setAttribute(java.lang.String name, java.lang.Object o): Save the data within the requested range. Pass data within the requested scope. name is a string that specifies the name of the variable, and o is the object to be stored. name is the key and o is the value. You can get o by name.

	request.setAttribute("list",list);

(2) public void removeAttribute(java.lang.String name): Delete an attribute from the request scope. name is a string that specifies the name of the variable to be deleted, and can also be regarded as a key.

	request.removeAttribute("list");

(3) public RequestDispatcher getRequestDispatcher(java.lang.String path): Return a RequestDispatcher object that is a wrapper for the resource at the given path. The RequestDispatcher object can be used to forward a request to a resource, or to include the resource in a response. The resource can be dynamic or static.

  • Method of RequestDispatcher:: public void forward(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOExceptionTransfer a request from one servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows a servlet to preprocess a request and another resource used to generate a response.
	//转发:从servlet跳转到jsp页面
	request.getRequestDispatcher("a.jsp").forward(request, response);

(4) public java.lang.Object getAttribute(java.lang.String name): Return the attribute corresponding to the name (key) in the requested range. When there is no attribute with the given name, it returns a null value.

	List<Blog> list = (List<Blog>) request.getAttribute("list");

(5) public java.lang.String getParameter(java.lang.String name): Returns the string value of a request parameter. If the parameter does not exist, a null value is returned.

(6) public java.lang.String[] getParameterValues(java.lang.String name): Return a vector of string objects containing the values ​​of all given request parameters. If the parameter does not exist, a null value is returned.

(7) public java.lang.String getRemoteAddr(): Return the IP address of the request sent by the client.

Note: The
setAttribute method and the getRequestDispatcher method are a pair of partners and need to be used in combination. Set the data through the setAttribute method, and obtain the data through getAttribute. The data obtained at this time is of Object type.

5.1.2, HttpServletRequest interface method


public java.lang.String getHeader(java.lang.String name): Return the value specified as a string request message header. If the request does not have a message header with the specified name, this method will return a null value.

public java.lang.String getRemoteAddr(): Get the IP address of the client.

public java.lang.String getLocalAddr(): Get the IP address of the server.

MIME: The full name of MIME is Multipurpose Internet Mail Extensions (Multipurpose Internet Mail Extensions). The MIME that browsers can accept was originally customized to extend the plain text format of e-mail to support multiple information formats. Later, it was applied to a variety of protocols, including our commonly used HTTP protocol. The common form of MIME is a main type plus a subtype, separated by a slash. For example, text/html, application/javascript, image/png, etc. When accessing a web page, the MIME type helps the browser identify what data is returned by an HTTP request, how to open it, and how to display the type.

5.2, Response


All data returned by the server to the client is called response data. In the Servlet API, a response interface is defined to encapsulate and manipulate response data.

HttpServletResponse interface: responsible for processing the response (Tomcat instantiates it), javax.servlet.http.HttpServletResponse interface inherits from javax.servlet. ServletResponse interface.

5.2.1, ServletResponse interface method


(1) public java.lang.String getCharacterEncoding(): Returns the name of the encoding used for the MIME body sent in this response message. If charset is not allocated, it is implicitly set to ISO-8859-1 (Latin-1).

(2) public void setCharacterEncoding(String env) throws UnsupportedEncodingException: Set the encoding used for the MIME body sent in this response message.

	request.setCharacterEncoding("utf-8");

(3) public java.io.PrintWriter getWriter() throws java.io.IOException: Return a PrintWriter object that can send characters to a client. If necessary, the MIME type of the response can be modified to reflect the character encoding used. Either this method or the method getOutputStream() can be called to write the body, but they cannot be called at the same time. Returns a PrintWriter object that can return characters to a client.

	PrintWriter out = response.getWriter();
	out.print("<p>Servlet</p>");

(4) public void setContentType(java.lang.String type): Set the content type of the response being sent to the client. The content type can include the character encoding type used, for example, text/html; charset=ISO-8859-4.

5.2.2, HttpServletResponse interface method


(1) public void sendRedirect(java.lang.String location) throws java.io.IOException: Use the specified relocation URL to send a temporary relocation response message to the client. This method can receive relative URLs.

	response.sendRedirect("b.jsp");

Two, JSP file

1. Introduction to JSP


JSP (Java Server Pages) is a Web component in the JavaEE specification, used to write dynamic pages. JSP runs on the server side and is essentially a Servlet. JSP files are suffixed with .jsp and exist in the WebContent directory in the Eclipse project directory. JSP files can be accessed directly in the browser. The content in the JSP file is HTML+Java code, the static part uses HTML and text, and the dynamic part uses Java code.

Servlet is more cumbersome to generate dynamic pages, and it is more convenient to use JSP to generate dynamic pages, because the static content can be generated using HTML. The execution process of JSP is: translation-compilation-instantiation-providing services. The essence of JSP is Servlet, but the server translates and compiles JSP; it can be said that JSP is also a Java class.

JSP is an html file containing Java code to display data. Although both servlet and jsp can display data, servlet is usually not used to display data, but jsp is used to display data.

Create a new JSP file: Right-click in the WebContent directory -> new -> JSP File -> Finish.

In total JSP file, the shortcut key ctrl+shift+ois invalid, and the shortcut key Alt+/is valid.

Syntax in JSP:

(1) Instructions: used to guide the package and do some document settings. grammar:<%@指令 %>

<%@page import="com.etc.bs.service.BlogService"%>
<%@page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>

(2) Small script: used to write Java code. grammar:<% Java代码 %>

<%
	System.out.println("小脚本");
	System.out.println("Java代码");
%>

(3) Expression: used for page output. Syntax: <%=expression%>

	<% String s = "this.is jsp"%>
	<%=s%>

(4) Annotation: Annotation elements can be used in JSP, there are three situations:

  1. The format is <%--JSP注释--%>that JSP comments are only visible in the source code and have been ignored during translation.

  2. In JSP, in addition to using JSP annotations, you can also use HTML annotations <!--HTML注释-->. The HTML annotations will be returned to the client but not displayed on the page.

  3. Java comments can be used in the Java code part of the JSP. The Java comments will be translated into the .java file, but will be ignored during compilation.

(5) Declaration: If you need to define the member variables or methods of the class in the JSP file, you can use the declaration element in the format<%! 声明语句%>

The execution process in JSP: the jsp file is translated into a java file (servlet) by Tomcat, and the java file is compiled into a class bytecode file by a virtual machine. In fact, the response to the browser is a bytecode file, so sometimes it may be slow when the webpage is loaded for the first time, and the speed is faster when the webpage is loaded later. The generated java files and bytecode files are in the Tomcat root directory In the work directory.

Jar package configuration: Jar is placed in WebContent/WEB-INF/lib, and it will automatically be added to the build path normally. You can check whether it is built in javaResources-> Libraries->Web App Libraries.

The DBUtil tool class of jdbc needs to load the driver class.forName("com.mysql.cj.jdbc.Driver");.

After the code of the web project is written, you need to restart the Tomcat Service and pay attention to the output information of the console.

2. Nine built-in objects of JSP


(1) Objects related to input/output: request, response, out

(2) Objects related to attribute scope: session, application, pageContext

(3) Objects related to Servlet: page, config

(4) Related to error handling: exception
Insert picture description here

3. Scope


(1) pagecontext (page context): the current page is valid (invalid after the page jumps).

(2) Request: The same request is valid (valid after the request is forwarded, and invalid after the redirect), and the data is passed to the next page.

(3) session (session): the same conversation is valid (the same browser is valid before exiting and closing)

(4) application (the entire page application): globally effective (the entire service is executed at the beginning of the server until the server is closed). In Servlet, it is ServletContext, through this.getServletContext(). It is application in jsp and can be used directly.

From smallest to largest order: pagecontext <request <session <application

The scope includes the setAttribute method (storing data) and the getAttribute method (obtaining data).

Guess you like

Origin blog.csdn.net/qq_42141141/article/details/111570937