编程知识 cdmana.com

Java Web foundation summary: servlet topic

Recently, there are some tasks to rectify the old interface , Most of them are related to Spring The interceptor of ,Tomcat Related to , Change to some underlying code discovery , On the basis of J2EE Some of my knowledge is forgotten , It needs to be looked up frequently , Just sort it out from scratch Servlet and Filter Knowledge of .

Servlet What is it

Servlet(Server Applet) yes Java Servlet Short for , It's using Java A program written in language that runs on the server side . Platform and protocol independent features , The main function is to browse and generate data interactively , Generate dynamic Web Content . Generally speaking ,Servlet It means that everything has been realized Servlet Interface class .Servlet The main workflow of the system is as follows :

 

Servlet Your request will first be HTTP Server ( Such as Apache) receive ,HTTP The server is only responsible for static HTML Page parsing , and Servlet The request will be forwarded to Servlet Containers ,Servlet The container will be based on web.xml The mapping in the Archives , Call the corresponding Servlet,Servlet The result of processing is returned to Servlet Containers , And through HTTP The server transmits the response to the client .

Servlet It is mainly used to process the data sent by the client HTTP Ask for , And return a response , The requests it can handle are doGet() and doPost() etc. .
Servlet from Servlet Containers provide ,Servlet Container means to provide Servlet The function of the server ( Such as Tomcat).
Servlet The container will Servlet Dynamically load to the server , And then through HTTP Request and HTTP Should interact with the client .

Servlet Related classes and interfaces of

Sun The company provides a series of interfaces and classes for Servlet Technology development , The most important interface is javax.servlet.Servlet. stay Servlet The interface defines 5 An abstract method , The details are as follows :

 Servlet Abstract methods of interfaces
Method declaration Function description
void init(ServletConfig config) The container is being built Servlet After the object , Will call this method . This method receives a ServletConfig Type arguments ,Servlet The container passes this argument to Servlet Pass initialization configuration information
ServletConfig getSendetConfig() Used to obtain Servlet Object configuration information , return Servlet Of ServletConfig thing
String getServletInfo() Returns a string , It contains information about Servlet Information about , As the author 、 Version and copyright information
voidservice (ServletRequest request,ServletResponse response) Responsible for responding to user requests , When the container receives client access Servlet Object request , Will call this method .
The container will construct a representation of the client's request information ServletRequest Object and a ServletResponse The object is passed as an argument to service() Method .
stay service() In the method , It can be done by ServletRequest Object to get information about the client and request information , After processing the request , call ServletResponse Object's method setting response information
void destroy() Responsible for releasing Servlet Resources occupied by objects . When the server is down or Servlet When an object is removed ,Servlet Objects will be destroyed , The container will call this method

Servlet Five methods in the interface , among init()、service() and destroy() Methods can express Servlet Life cycle of , They will be called at a certain time .
For Servlet The interface of ,Sun The company provides two default interface implementation classes :GenericServlet and HttpServlet. among ,GenericServlet Is an abstract class , This class is Servlet The interface provides a partial implementation of , It didn't come true HTTP Request processing .
HttpServlet yes GenericServlet Subclasses of , It inherited GenericServlet All the ways , And for HTTP In the request GET and POST Etc. provides specific operation methods . Usually , Written by Servlet Classes are inherited from HttpServlet, It's also used most in development HttpServlet thing .

HttpServlet Class
Method declaration Function description
protected void doGet (HttpServletRequest req, HttpServletResponse resp) To deal with GET Type HTTP The method of request
protected void doPost(HttpServletRequest req, HttpServletResponse resp) To deal with POST Type HTTP The method of request

 

Servlet Life cycle of

stay java In program , Every object has its life cycle ,Servlet No exception ;

Graph Described in Servlet Life cycle of .Servlet After the container is loaded , According to different functions , You can roughly put Servlet There are three stages in the life cycle of , The initialization phase 、 The execution and destruction phases .

Initialization phase

When the client to Servlet The container emits HTTP Request access to Servlet When ,Servlet The container first parses the request , Check to see if the memory already has the Servlet thing , If there is , Then directly use the Servlet thing , If not , Then establish Servlet Example object , And then by calling init() Method implementation Servlet Initialization work . It should be noted that , stay Servlet Throughout the life cycle of , its init() Method can only be called once .

Execution phase

This is Servlet The most important stage in the life cycle , In this stage ,Servlet The container will create a representative for this request HTTP Requested ServletRequest Objects and representatives HTTP Responsive ServletResponse thing , Then pass them as arguments to Servlet Of service() Method .
service() Methods from ServletRequest Object to obtain the client request information and process the request , Through ServletResponse Object generates response results .
stay Servlet Throughout the life cycle of , For Servlet Every visit request for ,Servlet The container calls once Servlet Of service() Method , And build new ServletRequest and ServletResponse thing , That is to say ,service() Method in Servlet Will be called many times throughout its life cycle .

Destruction phase

When the server is down or Web When the application is removed from the container ,Servlet With Web The destruction of the app . Destroying Servlet Before ,Servlet The container will call Servlet Of destroy() Method , So that Servlet Object releases the resources it occupies . stay Servlet Throughout the life cycle of ,destroy() Methods can only be called once .
Here ,Servlet Once an object is created, it will reside in memory waiting for access from the client , Until the server is shut down or Web When the application is removed from the container ,Servlet Objects are destroyed .

Servlet Function location and main work flow

 Servlet  Every request for ,Web The server is calling service() Before method , Will establish HttpServletRequest and HttpServletResponse thing . among ,HttpServletRequest Objects are used to encapsulate HTTP Request message , Abbreviation request thing .HttpServletResponse Objects are used to encapsulate HTTP Response message , Abbreviation response thing ( This section will be described in detail later ). The detailed process is shown in the figure below :

As can be seen in the figure , When a request event occurs in the browser ,

    1. I will Web The server sent a HTTP Ask for ;
    2. Web According to the request received by the server , We'll build a HttpServletRequest and HttpServletResponse thing , And then call the corresponding Servlet The program .
    3. stay Servlet While the program is running , It starts with HttpServletRequest Object to read data information , And then through service() Method to process the request message , And write the processed response data to HttpServletResponse In objects . Finally ,Web The server will start from HttpServletResponse Response data read from object , And send it to the browser .


notes : stay Web Server runtime , Every Servlet Only one instance object will be created , For every time HTTP Ask for ,Web The server will call the requested Servlet Example of service(HttpServletRequest request,HttpServletResponse response) Method , And build a new one request Object and a response thing .

 

HttpServletRequest Foundation

About Request thing

I have talked a lot about request Object information , Let's talk about it in detail request thing . In the Internet , Our data are all transmitted based on protocol , stay web In application , The most in circulation is http Agreement ,

A browser request web Server , In fact, the essence is to web The server sends a http Ask for , and web Server in order to better in web In this application http, It encapsulates a HttpServletRequest Class of , And a series of methods and programs are established to establish request thing ;

HttpServletRequest The interface is inherited from ServletRequest Interface , Its main function is to encapsulate HTTP Request message . Because of HTTP Request messages are divided into request lines 、 There are three parts: request header and request body . therefore , stay HttpServletRequest The interface defines the get request line 、 Related methods of request header and request message body .

When visiting Servlet When , All request messages will be encapsulated in the HttpServletRequest In objects , The request line of the request message contains the request method 、 Request resource name 、 Request path and other information , To get this information ,HttpServletRequest An interface defines a series of methods , As shown in the following table :


Common ways to get information about the request line
Method declaration Function description
String getMethod() This method is used to obtain HTTP The request mode in the request message ( Such as GET、POST etc. )
String getRequestURI() This method is used to get the resource name part of the request line, i.e. located at URL After the main engine and the terminal door 、 The part before the argument part
String getQueryString() This method is used to get the argument part of the request line , That is, the question mark after the resource path (?) Everything from now on
String getContextPath() This method is used to get the request URL It belongs to Web Application path , This path is based on / The beginning , Relative to the whole Web The root of the site , The end of the path does not contain /. If you ask for URL Of Web The root of the site , Then the return result is an empty string ("")
String getServletPath() This method is used to obtain Servlet The name of or Servlet The mapped path
String getRemoteAddr() This method is used to get the IP Address , Its format is similar to 192.168.0.3
String getRemoteHost() This method is used to get the full host name of the requesting client , Its format is similar to pcl.mengma.com. It should be noted that , If the full host name of the client cannot be resolved , Then the method will return the client's IP Address
int getRemotePort() This method is used to obtain the port number of the requesting client network connection
String getLocaIAddr() This method is used to obtain Web Receive the current network connection request on server IP Address
String getLocalName()
This method is used to obtain Web Receive current network connection on server IP The corresponding host name
int getLocalPort() This method is used to obtain Web The port number on the server to receive the current network connection
String getServerName() This method is used to get the host name that the current request points to , namely HTTP In the request message Host The part of the host name corresponding to the header field
int gctServcrPort() This method is used to obtain the port number of the server to which the current request is connected , namely HTTP In the request message Host The port number corresponding to the header field
StringBuffcr getRequestURL() This method is used to obtain the integrity of the request from the client URL, Including agreements 、 Server name 、 Port number 、 Resource path and other information , But it does not include the following query quotation part . Be careful ,getRequcstURL() The result of method regression is StringBuffer Type , instead of String Type , This makes it easier to modify the results

 


  Method to get the request header
Method declaration Function description
String getHeader(String name) The method used to get the value of the specified header field , If the request message does not contain the specified header field , Then getHeader() Method returns null; If the request message contains more than one header field of the specified name , Then getHeader() Method returns the value of the first header field
Enumeration getHeaders(String name)
This method returns a Enumeration Assemble objects , The collection object consists of all header field values of a specified name that appear in the request message . In most cases , A header field name appears only once in the request message , But sometimes it can happen many times
Enumeration getHeaderNames() This method is used to get a... Containing all the request header fields Enumeration thing
int getIntHeader(String name) This method is used to get the header field of the specified name , And change its value to int Type . It should be noted that , If the header field of the specified name does not exist , Then the return value is -1; If the value of the obtained header field cannot be converted to int Type , It will happen NumberFormatException Abnormal
long getDateHeader(String name) The method used to get the value of the specified field , And press it GMT The time format is converted to a representative date / Long integer of time , The long integer is from 1970 year 1 month 1 Japan 0 When 0 branch 0 The time value in milliseconds from the second
String getContentType() This method is used to obtain Content-Type The value of the header field , The result is String Type
int getContentLength() This method is used to obtain Content-Length The value of the header field , The result is int Type
String getCharacterEncoding() This method is used to return the character set encoding of the entity part of the request message , Usually from Content-Type In the header field , The result is String Type

 

Request forwarding

  When a Web After the resource receives a request from the client , If you want the server to notify another resource to process the request , It can be done by RequestDispatcher Objects to solve , ServletRequest A get is defined in the interface RequestDispatcher Method of object .

  • RequestDispatcher getRequestDispatcher (String path)

Returns the... That encapsulates the resource specified by a path RequestDispatcher thing . among , Arguments path Must use “/” The beginning , Used to indicate the current Web Root of application . It should be noted that ,WEB-INF The contents in the catalogue are correct for RequestDispatcher Objects are also visible . therefore , Pass to getRequestDispatcher(String path) The resource of a method can be WEB-INF Files in the catalog

RequestDispatcher The interface defines two related methods .

 RequestDispatcher Interface method
Method declaration Function description
forward(ServletRequest request,ServletResponse response) This method is used to transfer a request from a Servlet Pass it on to another Web Resources . stay Servlet in , You can do a preliminary processing of the request , And then by calling this method , Pass the request to other resources in response . It should be noted that , The method must be called before the response is submitted to the client , Otherwise, it will be thrown IllegalStateException Abnormal
include(ServletRequest request,ServletResponse response)
This method is used to include other resources as the current response content

 

HttpServletResponse Foundation

About Response thing

HttpServletnse The interface is inherited from ServletResponse Interface , It is mainly used for packaging HTTP Response message . Because of HTTP Response messages are divided into status lines 、 Response header 、 The message body consists of three parts . therefore , stay HttpServletResponse The interface defines to send the response status code to the client 、 Response header 、 Methods of responding to message bodies .

When Servlet When a response message is sent back to the client , You need to set the status code in the response message . therefore ,HttpServletResponse The interface defines two ways to transmit status codes .

1)setStatus(int status) Method

This method is used to set HTTP The status code of the response message , And generate a response status line . Since the state description information in the response status line is directly related to the status code , and HTTP The version is determined by the server , therefore , Just pass setStatus(int status) Method sets the status code , The status line can be transmitted . It should be noted that , Under normal circumstances ,Web The server will default to generate a status code of 200 The status line of .

2)sendError(int sc) Method

Servlet The response message sent to the client contains the response header field , Because of HTTP There are many types of response header fields for protocols , therefore ,HttpServletResponse An interface defines a set of settings HTTP The method of responding to the header field .

How to set the response header field
Method declaration Function description
void addHeader(String name,String value) Both methods are used to set HTTP Response header field of the protocol . among , Arguments name The name used to specify the response header field , Arguments value Used to specify the sound Should be the value of the header field . The difference is ,addHeader() Method can add a response header with the same name , and setHeader() Method will override the header field with the same name
void setHeader (String name,String value)
void addIntHeader(String name,int value) These two methods are specifically used to set response headers that contain integer values , Avoid using addHeader() And setHeader() Method requires that int The set value of the type is converted to String The trouble with type

void setIntHeader(String name, int value)
void setContentType(String type) This method is used to set Servlet Output content of MIME Type , For HTTP According to the agreement , It's about setting Content-Type The value of the response header field . for example , If the content delivered to the client is jpeg Format of the video data , You need to set the type of the response header field to image/jpeg. It should be noted that , If the content of the response is text ,setContentType() Method can also set character encoding , Such as text/html;charset = UTF-8
void setLocale (Locale loc) This method is used to set the localized information of the response message . Yes HTTP Say , It's about setting Content-Language Response header fields and Content-Type The character set encoding part of the header field . It should be noted that , If HTTP The message is not set Content-Type Header field , Then setLocale() The character set code set by the method will not appear in HTTP In the response header of the message , If you call setCharacterEncoding() or setContentType() Method specifies the inner part of the response The character set encoding of Rong , Then setLocale() Method will no longer have the ability to specify character set encoding
void setCharacterEncoding(String charset) This method is used to set the character encoding used in the output , Yes HTTP According to the agreement , It's about setting Content-Type The character set encoding part of the header field . If not set Content-Type Header field , Then setCharacterEncoding Method design The set character set encoding will not appear in HTTP In the response header of the message .setCharacterEncoding() Method ratio setContentType() and setLocale() Methods have high priority , Its settings will override setContentType() and setLocale() Method

  At HTTP In the response message , A lot of data is delivered through the response message body , therefore ,ServletResponse Follow the I/O The design concept of streaming a lot of data . When sending the response message body , Two output stream related methods are defined .

1)getOutputStream() Method

The byte output stream object obtained by this method is ServletOutputStream Type . Because of ServletOutputStream yes OutputStream Subclasses of , It can directly output binary data in byte array . therefore , To output the response text in binary format , You need to use getOutputStream() Method .

2)getWriter() Method

The character output stream object obtained by this method is PrintWriter Type . Because of PrintWriter Object of type can output character text directly , therefore , If you want to output a web page file whose content is all character text , You need to use getWriter() Method .

Be careful : Although response Of objects getOutputStream() and getWriter() Methods can send the response message body , however , They repel each other , Do not use at the same time , Otherwise IllegalStateException Abnormal .

Request redirection

In some cases , Requests for clients , One Servlet Class may not be able to do all the work . At this time , You can do this using request redirection .
Request redirection refers to Web After receiving the request from the server , It may be due to some conditions , Cannot access the current request URL The point is Web Resources , Instead, a new resource path is specified , Let the client resend the request .

In order to achieve request redirection ,HttpServletResponse An interface defines a sendRedirect() Method , This method is used to generate 302 Response code and Location Response head , To inform the client to re access Location Specified in the response header URL

sendRedirect() The working principle of the method is shown in the figure

When the client accesses Servlet1 When , As a result of Servlet1 Middle call sendRedirect() Method to redirect the request to Servlet2, therefore , The browser received Servlet1 After the response message of , Immediately Servlet2 Transfer request ,Servlet2 After processing the request , Then the response message is sent back to the client browser and displayed

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152743190d.html

Scroll to Top