Servlet-introduction to basic APIs and interfaces-Linux general technology-Linux programming and kernel information. The following is a detailed description. Basic classes and interfaces
1. javax. servlet. Servlet Interface
The servlet abstraction set is the javax. servlet. Servlet interface, which specifies the set of methods that must be recognized and managed by the Servlet engine by the servlet class.
The basic goal of the Servlet interface is to provide the lifetime Methods init (), service (), and destroy.
Methods In the servlet Interface
Void init (ServletConfit config) throws ServletException is performed by the servlet engine after the servlet is loaded and before the service is implemented? Secondary call. If init () causes an overflow of UnavailableException, servle will exit the service.
ServletConfig getServletConfig () returns the ServletConfig object passed to the servlet init () method.
Void service (ServletRequest request, ServletResponse response) throws ServletException. IOException processes the request described in the request object and returns the request result using the response object.
String getServletInfo () returns a String describing the servlet
Void destory () is called by the servlet engine when the servlet is to be detached.
Ii. javax. servlet. GenericServlet class (protocol-independent Version)
GenericServlet is a protocol-independent servlet. It is a servlet that does not provide services with requests. Instead, it simply starts the background thread from the init () method and (). It can be used to simulate the port monitoring process of the operating system.
The servlet API provides a direct implementation of the Servlet interface, called GenericServlet. This class provides the default implementation of methods in all interfaces except the service () method. This means that a basic servlet can be compiled by simply extending GenericServlte.
In addition to the Servlet interface, GenericServlet also implements the ServletConfig interface to process initialization parameters and servlet context, and provides methods for passing authorization to the ServletConfig object in the init () method.
Methods In the GenericServlet class
Void destory () is a registration entry for "destory ".
String getInitParameter (String name) returns the value of the initialization parameter with the specified name. Use config. getInitParameter (name) in progress.
Enumeration getInitParameterNames () returns this serv] for all et encoded initialization parameters? Enumerated value. Call config. getInitParameterNames () to obtain the list. If no initialization parameter is provided? Null enumerated value (but not null)
ServletConfig getServletConfig () returns the ServletConfig object passed to the init () method.
ServletContext getServletContext () returns the ServletContext referenced in the config object
String getServletInfo () returns an empty String
Void init (ServletConfig config) throws ServletException saves the config object in an instance variable. Compile the registration entry that makes up the word "init", and then call the method init ()
Void init () throws ServletException can be skipped to process servlet initialization. after the config object is saved, the end of init (ServletConfig config) is automatically called. servlet authors often forget to call super. init (config)
Void log (String msg) is used to compile the servlet registration entry. Therefore, the log () method of the servlet context is called. The servlet name is added to the beginning of the message text.
Void log (String msg, Throwable t) is used to compile a stack track for entry and servlet registration. This method is also a copy of the corresponding method in ServletContext.
Abstract void service (Request request, Response response) throws ServletException. IOException is called by the servlet engine to provide services for the Request described by the request object. This is the only abstract method in GenericServlet. Therefore, it is the only method that must be covered by the quilt class.
String getServletName () returns the servlet name specified in the Web application release Descriptor (web. xml.
Iii. javax. servlet. http. HttpServlet class (HTTP Version)
Although servlet APIs allow extension to other protocols, all servlets are implemented in the Web environment. Only a few servlets directly expand GenericServlet. More common for servlets is to extend their HTTP subclass HttpServlet.
HttpServlet class implements service () by calling the method specified to the HTTP request method, that is, for DELETE, HEAD, GET, OPTIONS, POST, PUT, and TRACE, doDelete () is called respectively (), doHead (), doGet (), doOptions (), doPost (), doPut (), and doTrace () methods, put the request and response objects into their HTTP specified subclass.
Methods In the HttpServlet class
Void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException is called by the servlet engine to process an http get request. The input parameters, HTTP header, and input stream can be obtained from the output stream of the request object, response header, and response object.
Void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException is called by the servlet engine to process an http post request. The input parameters, HTTP header, and input stream can be obtained from the output stream of the request object, response header, and response object.
Void doPut (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException is called by the servlet engine to process an http put request. In this method, the request URI specifies the location of the file to be loaded.
Void doDelete (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException is called by the servlet engine to process an http delete request. The request URI indicates that the resource is deleted.
Void doOptions (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException is called by the servlet engine to process an http options request. Returns an Allow response header indicating the HTTP method supported by the servlet. A servlet does not need to override this method, because the HttpServlet method has implemented the functions required by the specifications.
Void doTrace (HttpServletRequest request, HttpServletResponse response) throws ServletException. IOException is called by the servlet engine to process an http trace request. The request header is fed back to the response mark. A servlet does not need to override this method, because the HttpServlet method has implemented the functions required by the HTTP specification.
Void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException Service (Request request, Response response) calls an immediate method with the specified HTTP request and response. This method actually directs the request to doGet (), doPost (), and so on. This method should not be overwritten.
Void service (Request request, Response response) throws ServletException, IOException puts the Request and Response object into its specified HTTP subclass, and calls the specified HTTP service () method.
4. javax. servlet. ServletRequest class (protocol-independent Version)
The ServletRequest interface encapsulates the details of client requests. It has nothing to do with the Protocol and has a sub-interface that specifies HTTP.
ServletRequest mainly deals:
1. Find the Host Name and IP address of the client.
2. Retrieve Request Parameters
3. Get and set attributes
4. Get input and output streams
Methods In the ServletRequest class
Object getAttribute (String name) returns the request attribute with the specified name. If it does not exist, null is returned. Attributes can be set by the servlet engine or explicitly added using setAttribute.
Enumeration getAttributeName () returns the Enumeration of all attribute names in the request. If no attribute exists, an empty enumeration is returned.
String getCharacteEncoding () returns the character encoding used by the request.
Int getContentLength () specifies the length of the input stream. If it is unknown,-1 is returned.
ServletInputStream getInputStream () throws IOException returns the request-related (Binary) input stream. You can call one of the getInputStream () or getReader () methods.
String getParameter (String name) returns the specified input parameter. If no parameter exists, null is returned.
Enumeration getParameterName () returns an Enumeration that may be null for all parameter names in the request.
String [] getParameterValues (String name) returns an array of values for the specified input parameter name. If the value does not exist, null is returned. It is useful when parameters have multiple values.
String get Protocol () returns the name and version of the Protocol used in the request.
String getScheme () returns the substring of the request URI, but does not contain the content before the first colon.
String getServerName () returns the Host Name of the server that processes the request.
String getServerPort () returns the port number that the receiving host is listening on.
BufferedReader getReader () throws IOException returns a character interpreter for request-related input data. This method and getInputStream () can only be called separately and cannot be used at the same time.
String getRemoteAddr () returns the numeric IP address of the client host.
String getRemoteHost () returns the client host name if it is known.
Void setAttribute (String name, Object obj) saves the reference of the specified Object in the request with the specified name.
Void removeAttribute (String name): deletes a specified attribute from the request.
If Locale getLocale () is known, return the first scene of the client or null.
If Enumeration getLocales () is known, an Enumeration of the first field of the client is returned; otherwise, the first field of the server is returned.
Boolean isSecure () returns true if the request uses an HTTPS-secured tunnel.
RequestDispatcher getRequestDispatcher (String name) returns the RequsetDispatcher object of the specified source name.
V. javax. servlet. http. HttpServletRequest interface (HTTP Version)
HttpServletRequest class mainly deals:
1. Read and Write HTTP header labels
2. Obtain and set cookies
3. Obtain path information
4. Identify the HTTP session.
Methods In the HttpServletRequest Interface
String getAuthType () if the servlet is protected by an authentication scheme, for example, HTTP basic authentication, the scheme name is returned.
String getContextPath () returns the prefix of the URL of the specified servlet context (web application.
Cookie [] getCookies () returns an array of request-related cookies.
Long getDateHeader (String name) converts the output to a simplified version of getHeader () suitable for building the long value of the Date object.
String getHeader (String name) returns the specified HTTP header identifier. If the name is provided by the request, the name is case-insensitive.
Enumeration getHeaderNames () returns the weights of all HTTP header names given in the request.
Enumeration getHeaders (String name) returns the enumerated values of all HTTP header names of the specified type in the request. It is very useful for header labels with multiple values.
Int getIntHeader (String name) converts the output to a simplified version of getHeader () of the int value.
String getMethod () returns the HTTP request method (such as GET and POST)
String getPathInfo () returns any additional path information specified in the URL.
String getPathTranslated () returns any additional path information specified in the URL. the quilt is converted into an actual path.
String getQueryString () returns the query String, that is, in the URL? The following section.
String getRemoteUser () if the user passes the authentication, the remote user name is returned; otherwise, the value is null.
String getRequestedSessionId () returns the client session ID
String getRequestURI () returns a part of the URL, starting with "/", including the context, but not any query String.
String getServletPath () returns the substring after the request URI Context
HttpSession getSession () calls the simplified version of getSession (true.
HttpSession getSession (boolean create) returns the current HTTP session. If it does not exist, a new session is created. The create parameter is true.
Principal getPrincipal () if the user passes the authentication, the java. security. Principal object representing the current user is returned; otherwise, the value is null.
Boolean isRequestedSessionIdFromCookie () If the requested session ID is provided by a Cookie object, true is returned; otherwise, false is returned.
Boolean isRequestedSessionIdFromURL () If the requested session ID is decoded in the request URL, true is returned; otherwise, false is returned.
Boolean isRequestedSessionIdValid () returns true if the session ID returned by the client is still valid.
Boolean isUserInRole (String role) returns true if the user has been authenticated to be related to the specified role. If the user is not authenticated or fails to pass the authentication, false is returned.
The ServletResponse object uploads the result generated by a servlet to the client sending the request. The ServletResponse operation is mainly used as a package container for the output stream, its content type and length. It is created by the servlet engine.
Methods In the ServletResponse Interface
Void flushBuffer () throws IOException sends the output content cached to the client. Because HTTP requires header labels to be sent before the content, call this method to send status lines and Response Header labels to confirm the request.
Int getBufferSize () returns the cache size used by the response. If the cache is invalid, 0 is returned.
String getCharacterEncoding () returns the name decoded by a character in the response. ISO-8859-1 unless explicitly set
Locale getLocale () returns the field used for response. Unless modified using setLocale (), the default server field is used.
OutputStream getOutputStream () throws IOException returns the stream used to write the returned binary output to the client. Either method or getWrite () method can only call one of them.
Writer getWriter () throws IOException returns a character Writer that writes the returned text output to the client. This method and getOutputStream () can only call one of them.
Boolean isCommitted () returns true if the status and response header are sent back to the client. It does not work if the response is confirmed.
Void reset () clears the output cache and any response header. If the response is confirmed, the event IllegalStateException is thrown.
Void setBufferSize (int nBytes) sets the minimum cache size of the response. The actual cache size can be larger, which can be obtained by calling getBufferSize. If the output has been written, IllegalStateException is generated.
Void setContentLength (int length) sets the length of the content body.
Void setContentType (String type) sets the content type. Set the Content-Type header in HTTP servlet.
Void setLocale (Locale locale) is used to set the response site. In HTTP servlet, the Content-Type header value will be affected.
VII. javax. servlet. http. HttpServletResponse interface (HTTP Version)
HttpServletResponse adds a method to indicate the status code, status information, and response header. It is also responsible for decoding the HTTP session ID written to a web page in the URL.
Methods In the HttpServletResponse Interface
Void addCookie adds a Set-Cookie header to the response.
Void addDateHeader (String name, long date) uses the specified date value to add a method with the specified name (or replace all the Response Header labels.
Void setHeader (String name, String value) sets a response header with the specified name and value.
Void addIntHeader (String name, int value) uses the specified integer value to add the response header with the specified name (or replace all header labels with this name ).
Boolean containsHeader (String name) returns true if the response contains the header mark of this name.
String encodeRedirectURL (String url) if the client does not know to accept cookid, the session ID is added to the URL. The first method only calls the URLs used in sendRedirect. Other encoded URLs should be passed to encodeURL ()
String encodeURL (String url)
Void sendError (int status) sets the response status code to a specified value (optional status information ). HttpServleetResponse defines a complete set of Integer constants to indicate valid State values.
Void sendError (int status, String msg)
Void setStatus (int status) specifies the response status code. Only applicable to the response that does not generate an error, while the error response uses sendError ().
8. javax. servlet. ServletContext Interface
A servlet context is an interface provided by the servlet engine to serve Web applications. The Servlet context has a unique directory mapped to the file system by name (which belongs to the Web application name.
A servlet can reference the servlet context through the getServletContext () method of the ServletConfig object. If the servlet directly or indirectly calls the subclass GenericServlet, The getServletContext () method can be used.
In a Web application, servlet can be obtained using the servlet context:
1. Save and retrieve attributes during the call, and share these attributes with other servlets.
2. Read the file content and other static Resources in the Web application.
3. Sending Requests to each other.
4. Record errors and information messages.
Methods In the ServletContext Interface
Object getAttribute (String name) returns the Object with the specified name in the servlet context, or binds an Object with the specified name. From the standard perspective of Web applications, such objects are global objects because they can be accessed by the same servlet at another time. Or any other servlet access in the context.
Void setAttribute (String name, Object obj) sets the Object with the specified name in the servlet context.
Enumeration getAttributeNames () returns an Enumeration of all attribute names stored in the servlet context.
ServletContext getContext (String uripath) returns the servlet context mapped to another URL. In the same server, the URL must start.
String getInitParameter (String name) returns the initialization parameter value of the specified context range. This method is different from the name of the ServletConfig method. The latter is only applicable to the encoded specified servlet. This method is applied to all parameters in the context.
Enumeration getInitParameterNames () returns (may be blank) the enumerated value of the name of the initialization parameter value for the specified context range.
Int getMajorVersion () returns the maximum and minimum versions supported by servlet APIs in this context.
Int getMinorVersion ()
String getMimeType (String fileName) returns the MIME type of the specified file name. Typically, it is based on the file extension rather than the content of the file itself (it does not have to exist ). If the MIME type is unknown, null is returned.
RequestDispatcher getNameDispatcher (String name) returns the RequestDispatcher of the servlet or JSP with the specified name or path. If RequestDispatch cannot be created, null is returned. If a path is specified, it must start with "/" and be relative to the top of the servlet context.
RequestDispatcher getNameDispatcher (String path)
String getRealPath (String path) specifies a URI and returns the absolute path of the URI in the file system. If the ing is not allowed, null is returned.
URL getResource (String path) returns the URL corresponding to the specified absolute path of the servlet context or the input stream that reads the URL. If the resource does not exist, null is returned.
InputStream getResourceAsStream (String path)
String getServerInfo () returns the name and version number of the servlet engine.
Void log (String message)
Void log (String message, Throwable t) writes a message to the servlet registration. If the Throwable parameter is provided, the stack track is included.
Void removeAttribute (String name) deletes the specified attribute from the servlet context.
9. javax. servlet. http. HttpSession Interface
HttpSession is similar to the hash table interface. It provides the setAttribute () and getAttribute () Methods to store and retrieve objects. HttpSession provides a session ID keyword. A client that participates in session behavior stores and returns it in the same session request. The servlet engine searches for appropriate session objects and makes them available to the current request.
Methods In the HttpSession Interface
Object getAttribute (String name) saves an Object in a session as the specified name, and returns or deletes the previously saved name Object.
Void setAttribute (String name, Object value)
Void removeAttribute (String name)
Enumeration getAttributeName () returns the enumerated values of all attribute names bound to the current session.
Long getCreationTime () returns a long integer that represents the session creation and last access Date and time. This integer is used in the java. util. Date () constructor.
Long getLastAccessedTime ()
String getId () returns the session ID, a unique keyword set by the servlet engine.
If ing getMaxInactiveInterval () does not interact with the client, set and return the maximum number of seconds for session survival.
Void setMasInactiveInterval (int seconds)
Void invalidate () causes the session to be terminated and any objects are released.
Boolean isNew () returns true if the client is not added to the session. When a session is created for the first time and the session ID is passed into the client, but the client does not perform the second request containing the session ID, true is returned.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.