Recently, there are some tasks to rectify the old interface , Most of them are related to Spring Interceptor ,Tomcat relevant , Change to some underlying code discovery , Base on J2EE Some of our knowledge is forgotten , It needs to be looked up frequently , Just sort it out from scratch Servlet and Filter Knowledge .
Servlet What is it?
Servlet（Server Applet） yes Java Servlet For short , It's using Java Language to run on the server side of the program . Platform - and protocol-independent , The main function is to interactively browse and generate data , Generate dynamic Web Content . Generally speaking ,Servlet It means that everything has been realized Servlet The class of the interface .Servlet The main work flow of is as follows ：
Servlet Your request will first be HTTP The server （ Such as Apache） receive ,HTTP The server is only responsible for static HTML Page parsing , and Servlet Your request will be forwarded to Servlet Containers ,Servlet The container will be based on web.xml Mapping relationships in files , Call the corresponding Servlet,Servlet The result of processing is returned to Servlet Containers , And pass HTTP The server transmits the response to the client .
Servlet It is mainly used to process the client sent HTTP request , 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 Function of the server （ Such as Tomcat）.
Servlet The container will Servlet Dynamic loading 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 Interface defined 5 Abstract methods , The details are as follows ：
|Method statement||Function description|
|void init(ServletConfig config)||The container is creating Servlet After the object , This method will be called . The method receives one ServletConfig Parameters of type ,Servlet By using this parameter, the container is directed to Servlet Pass initialization configuration information|
|ServletConfig getSendetConfig()||Used to get Servlet Object configuration information , return Servlet Of ServletConfig object|
|String getServletInfo()||Returns a string , It contains information about Servlet Information about , As the author 、 Version and copyright|
|voidservice (ServletRequest request,ServletResponse response)||
Responsible for responding to user requests , When the container receives client access Servlet When the object is requested , This method will be called .
The container will construct a representation of the client request information ServletRequest Object and a ServletResponse Object is passed as a parameter to service() Method .
stay service() In the method , Can pass ServletRequest Object to get the relevant information and request information of the client , After processing the request , call ServletResponse Object to set the response information
|void destroy()||To release Servlet Resources occupied by objects . When the server is down or Servlet When an object is removed ,Servlet The object 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 particular time .
in the light of Servlet The interface of ,Sun The company provides two default interface implementation classes ：GenericServlet and HttpServlet. among ,GenericServlet Is an abstract class , The class for Servlet Interface provides partial implementation , It doesn't work HTTP Request processing .
HttpServlet yes GenericServlet Subclasses of , It inherited GenericServlet All the ways , And for HTTP In the request GET and POST And other types provide specific operation methods . Usually , Compiling Servlet Classes are inherited from HttpServlet, It's also used most in development HttpServlet object .
|Method statement||Function description|
|protected void doGet (HttpServletRequest req, HttpServletResponse resp)||Used for processing GET Type of HTTP Requested method|
|protected void doPost(HttpServletRequest req, HttpServletResponse resp)||Used for processing POST Type of HTTP Requested method|
Servlet Life cycle of
stay java In the program , Any object has its life cycle ,Servlet No exception ;
chart Described in Servlet Life cycle of .Servlet After the container is loaded , According to different functions , You can roughly put Servlet The life cycle of is divided into three stages , The initialization phase 、 The operation phase and the destruction phase .
When the client Servlet The container emits HTTP Request access to Servlet when ,Servlet The container first parses the request , Check if the memory already has the Servlet object , If there is , Use the Servlet object , without , Create Servlet Instance object , And then by calling init() Method realization Servlet Initialization work . It should be noted that , stay Servlet Over the life cycle of , its init() Method can only be called once .
This is a Servlet The most important stage in the life cycle , At this stage ,Servlet The container creates a delegate for this request HTTP Requested ServletRequest Objects and representatives HTTP Responsive ServletResponse object , Then pass them as parameters to Servlet Of service() Method .
service() Methods from ServletRequest Object to obtain customer request information and process the request , adopt ServletResponse Object to generate response results .
stay Servlet Over the life cycle of , about Servlet Every visit request for ,Servlet The container will call once Servlet Of service() Method , And create new ServletRequest and ServletResponse object , in other words ,service() Method in Servlet Will be called many times throughout its life cycle .
When the server is down or Web When the application is removed from the container ,Servlet With Web The application is closed and destroyed . In the process of destruction Servlet Before ,Servlet The container will call Servlet Of destroy() Method , In order to make Servlet Object releases the resources it occupies . stay Servlet For the entire life cycle of ,destroy() Methods can only be called once .
ad locum ,Servlet Once created, the object will reside in memory waiting for the client to access , 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 Server is calling service() Before method , Will create HttpServletRequest and HttpServletResponse object . among ,HttpServletRequest Objects are used to encapsulate HTTP The request message , abbreviation request object .HttpServletResponse Objects are used to encapsulate HTTP The response message , abbreviation response object （ This part will be described in detail later ）. The detailed process is shown in the figure below ：
According to the picture , When a request event occurs in the browser ,
- Will send to Web The server sent a HTTP request ;
- Web The server receives the request , Will create a HttpServletRequest and HttpServletResponse object , Then call the corresponding Servlet Program .
- stay Servlet Program runtime , It starts with HttpServletRequest Object , And then through service() Method to process the request message , And write the processed response data to HttpServletResponse In the object . Last ,Web The server will be from HttpServletResponse The response data is read from the object , And send it to the browser .
notes ： stay Web Server running phase , Every Servlet Only one instance object will be created , For each time HTTP request ,Web The server will call the requested Servlet Example of service（HttpServletRequest request,HttpServletResponse response） Method , And recreate a request Object and a response object .
About Request object
I talked a lot about request Object information , Let's talk about it in detail request object . In the network , Our data is all protocol based , stay web Application , The most in circulation is http agreement ,
A browser request web The server , In fact, the essence is to web Server sends a http request , and web The server in order to better in web The app uses this http, It encapsulates one HttpServletRequest Class , And set up a series of methods and schemes to create request object ;
HttpServletRequest Interface inherited from ServletRequest Interface , Its main function is to encapsulate HTTP The request message . because HTTP Request messages are divided into request lines 、 Request header and request message body are three parts . therefore , stay HttpServletRequest Interface defines the get request line 、 Methods related to request header and request message body .
When accessing Servlet when , All request messages will be encapsulated in HttpServletRequest In the object , The request line of the request message contains the request method 、 Request resource name 、 Request path and other information , To get this information ,HttpServletRequest Interfaces define a series of methods , As shown in the following table ：
|Method statement||Function description|
|String getMethod()||This method is used to obtain HTTP Request mode in request message （ Such as GET、POST etc. ）|
|String getRequestURI()||This method is used to get the resource name part in the request line, which is located in URL After the host and the end door 、 The part before the parameter part|
|String getQueryString()||This method is used to get the parameter 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 Of Web The path to the application , This path takes / start , Relative to the whole Web The root directory of the site , The end of the path does not contain /. If you ask for URL Belong to Web The root directory of the site , Then the return result is an empty string （""）|
|String getServletPath()||This method is used to obtain Servlet Or Servlet 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 this 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 The server receives the current request for network connection IP Address|
This method is used to obtain Web The server receives the current network connection 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 host name part 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 part corresponding to the header field|
|StringBuffcr getRequestURL()||This method is used to obtain the complete information when the client makes a request URL, Including the agreement 、 Server name 、 Port number 、 Resource path and other information , But it does not include the following query parameters . Be careful ,getRequcstURL() The result of the method is StringBuffer type , instead of String type , This makes it easier to modify the results|
|Method statement||Function description|
|String getHeader(String name)||This method is used to get the value of a specified header field , If the request message does not contain the specified header field , be getHeader() Method returns null; If the request message contains more than one header field with the specified name , be getHeader() Method returns the value of the first header field|
|Enumeration getHeaders(String name)||
This method returns a Enumeration A collection of 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 Enumeration object|
|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 , 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)||This method is used to get the value of the specified header 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 value of time in milliseconds from seconds|
|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|
When one Web After the resource receives the request from the client , If you want the server to notify another resource to process the request , Can pass RequestDispatcher Object to solve , ServletRequest Interface defines a get RequestDispatcher Object method .
- RequestDispatcher getRequestDispatcher (String path)
Returns the... That encapsulates the resource specified by a path RequestDispatcher object . among , Parameters path Must be “/” start , Used to indicate the present 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 directory
RequestDispatcher Interface defines two related methods .
|Method statement||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 , A preliminary request can be processed , And then by calling this method , Pass the request to other resources in response . It should be noted that , This method must be called before the response is submitted to the client , Otherwise, it will throw IllegalStateException abnormal|
|include(ServletRequest request,ServletResponse response)||
This method is used to include other resources as the current response content
About Response object
HttpServletnse Interface inherited from ServletResponse Interface , It is mainly used for packaging HTTP The response message . because HTTP The response message is divided into status lines 、 Response header 、 The message body consists of three parts . therefore , stay HttpServletResponse Interface defines sending response status code to client 、 Response header 、 Methods for responding to message bodies .
When Servlet When a response message is sent back to the client , Need to be in the response message Set status code . therefore ,HttpServletResponse The interface defines two methods for sending 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 . The state description information in the response state line is directly related to the state code , and HTTP The version is determined by the server , therefore , As long as through the setStatus（int status） Method sets the status code , You can send the status line . It should be noted that , Under normal circumstances ,Web The server will default to a status code of 200 The status line of .
2）sendError（int sc） Method
Servlet The response message sent to the client contains Response header fields , because HTTP There are many kinds of response header fields in the protocol , therefore ,HttpServletResponse Interface defines a set of settings HTTP Response header field method .
|Method statement||Function description|
|void addHeader(String name,String value)||Both methods are used to set HTTP Response header field of the protocol . among , Parameters name Used to specify the name of the response header field , Parameters value Used to specify that Should be the value of the header field . The difference is ,addHeader() Method can add a response header field 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, you need to put int The set value of type is converted to String Type of trouble|
void setIntHeader(String name, int value)
|void setContentType(String type)||This method is used to set Servlet The output content of MIME type , about HTTP Agreement for , Is set Content-Type The value of the response header field . for example , If the content sent to the client is jpeg Format image 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 localization information of the response message . Yes HTTP Come on , Is set Content-Language Response header fields and Content-Type The character set encoding part of the header field . It should be noted that , If HTTP Message is not set Content-Type Header fields , be setLocale() The character set encoding set by the method does not appear in HTTP In the response header of the message , If the setCharacterEncoding() or setContentType() Method specifies the response inside The character set encoding of Rong , be 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 Agreement for , Is set Content-Type The character set encoding part of the header field . If not set Content-Type Header fields , be setCharacterEncoding Method set The 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 to set the character code table|
In HTTP In the response message , A lot of data is passed through Response message body Delivered , therefore ,ServletResponse Follow the I/O The design concept of streaming large amounts of data . When sending the body of the response message , Two output stream related methods are defined .
The object of byte output stream obtained by this method is ServletOutputStream type . because ServletOutputStream yes OutputStream Subclasses of , It can output binary data in byte array directly . therefore , To output the response body in binary format , You need to use getOutputStream() Method .
The character output stream object obtained by this method is PrintWriter type . because PrintWriter Type object can output character text content directly , therefore , If you want to output a web document whose content is all character text , You need to use getWriter() Method .
Be careful ： although response Object's getOutputStream() and getWriter() Method can send the response message body , however , They repel each other , Do not use at the same time , Otherwise it will happen IllegalStateException abnormal .
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 the server receives the request from the client , Maybe because of some conditions , Cannot access the current request URL The point is Web resources , Instead, it specifies a new resource path , Let the client resend the request .
In order to achieve request redirection ,HttpServletResponse The 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 The... Specified in the response header URL
sendRedirect() The working principle of the method is shown in the figure
When the client accesses Servlet1 when , Because in Servlet1 Called in sendRedirect() Method to redirect the request to Servlet2, therefore , Browser received Servlet1 After the response message , Immediately Servlet2 Send a request ,Servlet2 After processing the request , The response message is sent back to the client browser and displayed .