Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Servlet

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the example analysis of Servlet, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

About Java Servlets

JavaTM servlets is a platform-independent Java Mini Program, which can be used to extend the functions of a Web server in a variety of ways. You can think of Servlet as applets on Server, which is compiled into bytecode so that it can be loaded dynamically and effectively expand the processing power of the host.

Servlet differs from applets in that it does not run on Web browsers or other graphical user interfaces. Servlet runs in the Web server through the servlet engine to execute requests and responses, a typical example of which is the HTTP protocol.

A client program, which can be a Web browser, or a non-other program that can connect to Internet, accesses the Web server and makes a request. The request is processed by the Servlet engine running on the Web server and the response is returned to Servlet. Servlet forwards this response to the client through HTTP.

Functionally, Servlet is somewhat similar to CGI and NSAPI, but unlike them, Servlet is platform independent.

Introduction to Java Servlet

Servlet and other common server extension mechanisms have the following improvements:

Because it uses a different process processing mode, it is faster than CGI.

It uses the standard API supported by many Web servers.

It inherits all the advantages of Java, including easy upgradeability and platform independence.

It can call a large number of API functional modules provided by Java.

This document describes the methods of Java Servlet API's classes and interfaces. For more information, see the API instructions below.

Life cycle of Servlet

A Java servlet has a life cycle that defines how a Servlet is loaded and initialized, how a request is received and responded to, and how it is cleared from the service. The life cycle of Servlet is defined by the interface javax.servlet.Servlet.

All Java Servlet executes the javax.servlet.Servlet interface directly or indirectly so that it can run in a Servlet engine. The Servlet engine is an extension customized by the Web server to the Java Servlet API. The Servlet engine provides network services, understands MIME requests, and provides a container that runs Servlet.

The javax.servlet.Servlet interface defines the methods that are called at a specific time and in a particular order during the life cycle of the Servlet.

Parsing and loading of Servlet

The Servlet engine parses and loads a Servlet, which can happen when the engine starts, when a Servlet is needed to respond to the request, and at any time in between.

The Servlet engine uses the Java class loading tool to load a Servlet,Servlet engine that loads Servlet from a local file system, a remote file system, and a network.

Initialization of Servlet

After the Servlet engine loads the Servlet, the Servlet engine must initialize the Servlet. In the process, you can read some fixed storage data, initialize the connection to the JDBC, and establish connections to other resources.

During initialization, the init () method of the javax.servlet.Servlet interface provides initialization information for Servlet. In this way, Servlet can configure itself.

The init () method gets a Servlet configuration object (ServletConfig). This object is executed in the Servlet engine and allows Servlet to get the relevant parameters through it. This object enables Servlet to access the ServletContext object.

Servlet handles requests

After Servlet is initialized, it can handle requests from the client, each request from the client is described as a ServletRequest object, and the response of the Servlet is described as a ServletResponse object.

When the client makes a request, the Servlet engine passes Servlet a ServletRequest object and a ServletResponse object, which are passed as parameters to the service () method.

Servlet can also execute ServletRequest interfaces and ServletResponse interfaces. The ServletRequest interface gives Servlet the right to use requests made by the client. Servlet can read the request information through the ServletInputStream object.

The ServletResponse interface allows Servlet to establish response headers and status codes. By executing this interface, Servlet has the right to use the ServletOutputStream class to return data to the client.

Multithreading and mapping

In a multithreaded environment, Servlet must be able to handle many simultaneous requests. The exception is that the Servlet executes the SingleThreadModel interface, in which case Servlet can only process one request at the same time.

Servlet responds to client requests according to the mapping of the Servlet engine. A mapping pair includes an instance of Servlet and a URL with data returned by Servlet, for example: HelloServlet with / hello/index.html.

However, a mapping may consist of a URL and many Servlet instances, for example, a distributed Servlet engine may run on more than one server, so that there may be an Servlet instance in each server to balance the load of the process. As a Servlet developer, you can't assume that there is only one instance of a Servlet.

Uninstall Servlet

The Servlet engine does not have to guarantee that a Servlet is loaded at any time or when the service is turned on. The Servlet engine is free to use or clear a Servlet at any time. Therefore, we cannot rely on a class or instance to store important information.

When the Servlet engine decides to uninstall a Servlet (for example, if the engine is turned off or needs to make way for resources), the engine must allow Servlet to release the resources in use and store the relevant data. To do this, the engine calls the destroy () method of Servlet.

Before uninstalling a Servlet, the Servlet engine must wait for all service () methods to complete or the timeout ends (the Servlet engine defines the timeout). When a Servlet is uninstalled, the engine will not be able to send any requests to the Servlet. The engine must release the Servlet and complete the collection of useless storage units

Servlet mapping technology

As a Servlet engine developer, you must have a lot of adaptability to how to map client requests to Servlet. This documentation does not specify how the mapping occurs. However, you must be free to use all of the following technologies:

Map a Servlet to a URL

For example, you can specify a special Servlet that is called only by requests from / feedback/index.html.

Map a Servlet to all URL starting with a specified directory name

For example, you can map a Servlet to / catalog so that requests from / catalog/, / catalog/garden, and / catalog/housewares/index.html are all mapped to the Servlet. But requests from / catalogtwo or / catalog.html are not mapped.

Map a Servlet to all URL that end in a specific field

For example, you can map a request from all the requests that end in in.thtml to a specific Servlet.

Map a Servlet to a special URL / servlet/servlet_name.

For example, if you create a Servlet called listattributes, you can access the Servlet by using / servlet/listattributes.

Call Servlet through the class name

For example, if the Servlet engine receives a request from / servlet/com.foo.servlet.MailServlet, the Servlet engine loads the com.foo.servlet.MailServlet class, creates an instance, and processes the request through the Servlet.

Servlet environment

The ServletContext interface defines a Servlet environment object that defines a view of Servlet on the Servlet engine. By using this object, Servlet can log events, get resources, and get classes from the Servlet engine (such as RequestDispatcher objects). A Servlet can only run in one Servlet environment, but different Servlet can have different views on the Servlet engine.

If the Servlet engine supports virtual hosts, each virtual host has a Servlet environment. A Servlet environment cannot be shared between virtual hosts.

The Servlet engine can allow a Servlet environment to have its own scope of activity.

For example, a Servlet environment belongs to a bank application and will be mapped to the / bank directory. In this case, a call to the getContext method returns the Servlet environment of / bank.

HTTP session

HTTP is a stateless protocol. To build an effective Web service application, you must be able to identify a continuous, unique request from a remote client. With the passage of time, a lot of session tracking techniques have been developed, but they are all troublesome to use.

Java Servlet API provides a simple interface through which the Servlet engine can effectively track users' sessions.

Establish Session

Because HTTP is a request-response protocol, a session is considered a new session before the client joins. To join means to return session tracking information to the server, indicating that the session has been established. We cannot determine that the next client request is part of the current session until the client joins.

In the following cases, Session will be considered the new Session.

The Session of the client didn't know before.

The client chooses not to join the Session, for example, if the client refuses to receive the cookie from the server

As a Servlet developer, you have to decide whether your Web application handles clients not joining or not joining Session. The server maintains a Session object for the time specified by the Web server or Servlet. When the Session terminates, the server releases the Session object and all objects bound to the Session.

Bind objects to Session

If it helps you deal with the data requirements of your application, you may need to bind objects to Session. You can bind any object to Session with a unique name. In this case, you need to use HttpSession objects. Any object bound to the Session can be handled by Servlet calls to the same session.

Some objects may need you to know when they will be placed in or removed from the Session. You can get this information by using the HttpSessionBindingListener interface. When your application stores data in Session or clears data from Session, Servlet checks what classes are bound or unbound through HttpSessionBindingListener. The methods of this interface notify objects that are bound or unbound.

Description of the API object

This section contains a detailed description of all the classes and interfaces of Java Servlet API. This description is similar to Javadoc API, but this document provides more information.

API contains two software packages, twelve interfaces and nine classes.

Software package: javax.servlet

Included interface: RequestDispatcher;Servlet;ServletConfig;ServletContext;ServletRequest;ServletResponse;SingleThreadModel.

Included class: GenericServlet;ServletInputStream;ServletOutputStream;ServletException;UnavailableException.

1. RequestDispatcher interface:

Definition:

Public interface RequestDispatcher

Define an object, receive a request from the client, and send it to the server's available resources (such as Servlet, CGI, HTML files, JSP files). The Servlet engine creates request dispatcher objects that encapsulate server resources defined by a particular URL.

This interface is designed to encapsulate Servlet, but a Servlet engine can create request dispatcher objects to encapsulate any type of resource.

Request dispatcher objects are created by the Servlet engine, not by Servlet developers.

Method

1 、 forward

Public void forward (ServletRequest request, ServletReponse response)

Throws ServletException, IOException

Is used to pass requests from this Servlet to other server resources. This method can be used when a Servlet has done preliminary processing of the response and requires other objects to respond to it.

When the request object is passed to the target object, the requested URL path and other path parameters are adjusted to reflect the target URL path of the target object.

This method cannot be used if a ServletOutputStream object or PrintWriter object has been returned through the response, otherwise it throws an IllegalStateException.

2 、 include

Public void include (ServletRequest request, ServletResponse response)

Throws ServletException, IOException

Content used to include responses sent to other server resources. In essence, this approach reflects the content on the server side.

When the request object is passed to the target object, it reflects the request URL path and path information of the call request. This response object can only call the ServletOutputStream object and PrintWriter object of this Servlet.

A Servlet calling include cannot set the header domain, and if the Servlet calls a method that must set the header domain (such as cookie), this method will not be guaranteed to work properly. As a Servlet developer, you must properly address methods that may store headers directly. For example, even if you use session tracking, in order for session to work properly, you must start your session outside of a Servlet that calls include

Second, Servlet interface.

Define

Public interface Servlet

This interface defines a Servlet: a Java class that inherits this functionality on the Web server.

Method

1 、 init

Public void init (ServletConfig config) throws ServletException

The Servlet engine invokes the init method precisely after the Servlet is instantiated and before placing the service. Before calling the service method, the init method must exit successfully.

If the init method throws a ServletException, you cannot put the Servlet into the service, and if the init method is not completed within the timeout, we can also assume that the Servlet is not functional and cannot be placed into the service.

2 、 service

Public void service (ServletRequest request, ServletResponse response)

Throws ServletException, IOException

The Servlet engine calls this method to allow Servlet to respond to requests. This method cannot be called until Servlet is successfully initialized. The Servlet engine can block pending requests before Servlet is initialized.

The Servlet engine cannot call this method after a Servlet object is unloaded until a new Servelt is initialized

3 、 destroy

Public void destroy ()

The Servlet engine calls this method when a Servlet is removed from the service. The destroy method cannot be called when all threads of the object's service method have not exited or are not considered by the engine to have timed out.

4 、 getServletConfig

Public ServletConfig getServletConfig ()

Return a ServletConfig object, and as a Servlet developer, you should store the ServletConfig object through the init method so that this method can return it. For your convenience, GenericServlet has already done so when executing this interface.

5 、 getServletInfo

Public String getServletInfo ()

Allows Servlet to provide information about itself to the host's Servlet operator. The returned string should be in plain text format without any flags (such as HTML,XML, etc.).

III. ServletConfig interface

Define

Public interface ServletConfig

This interface defines an object through which the Servlet engine configures a Servlet and allows Servlet to get a description of its ServletContext interface. Each ServletConfig object corresponds to a unique Servlet.

Method

1 、 getInitParameter

Public String getInitParameter (String name)

This method returns a String that contains the initialization parameters specified by Servlet. If this parameter does not exist, add a null value back.

2 、 getInitParameterNames

Public Enumeration getInitParameterNames ()

This method returns a list String object that includes all initialization parameter names of Servlet. If Servlet does not have initialization parameters, getInitParameterNames returns an empty list.

3 、 getServletContext

Public ServletContext getServletContext ()

Returns the ServletContext object of this Servlet.

IV. ServletContext interface

Define

Public interface ServletContext

Defines an environment object for Servlet, through which the Servlet engine provides environment information to Servlet.

An Servlet environment object must be at least one-to-one corresponding to the host it resides on. In a Servlet engine that handles multiple virtual hosts (for example, a host header domain that uses HTTP1.1), each virtual host must be treated as a separate environment. In addition, the Servlet engine can create environment objects that correspond to a set of Servlet.

Method

1 、 getAttribute

Public Object getAttribute (String name)

Returns the property object specified in the Servlet environment object. If the property object does not exist, a null value is returned. This method allows access to additional information about the Servlet engine that has not been provided in other methods of the interface.

2 、 getAttributeNames

Public Enumeration getAttributeNames ()

Returns a list of property names available in the Servlet environment object.

3 、 getContext

Public ServletContext getContext (String uripath)

Returns a Servlet environment object that contains the Servlets and resources for a specific URI path, or a null value if the path does not exist. The URI path format is / dir/dir/filename.ext.

For security purposes, if you access a restricted Servlet environment object through this method, a null value is returned.

4 、 getMajorVersion

Public int getMajorVersion ()

Returns the major version number of the Servlet API supported by the Servlet engine. For example, for version 2.1, this method returns an integer of 2.

5 、 getMinorVersion

Public int getMinorVersion ()

Returns the minor version number of the Servlet API supported by the Servlet engine. For example, for version 2.1, this method returns an integer of 2.

6 、 getMimeType

Public String getMimeType (String file)

Returns the MIME type of the specified file, or a null value if the MIME type is unknown. The MIME type is determined by the configuration of the Servlet engine.

7 、 getRealPath

Public String getRealPath (String path)

The format of a specified virtual path that conforms to the URL path format is: / dir/dir/filename.ext. With this method, you can return the String of a real path corresponding to a virtual path that conforms to the format. The format of this real path should be appropriate for the computer running the Servlet engine (including its corresponding path parser).

Whatever the reason, if this process of converting from a virtual path to a real path cannot be performed, the method will return a null value.

8 、 getResource

Public URL getResource (String uripath)

Returns a URL object that reflects resources known to the Servlet environment object at the given URL address (format: / dir/dir/filename.ext). Whether or not URLStreamHandlers is necessary to access a given environment, the Servlet engine must execute. If the Servlet environment of the given path has no known resources, the method returns a null value.

This method is not exactly the same as java.lang.Class 's getResource method. The getResource method of java.lang.Class looks for resources by loading classes. This approach allows the server to generate environment variables to any Servlet of any resource without having to rely on loading classes, specific regions, and so on.

9 、 getResourceAsStream

Public InputStream getResourceAsStream (String uripath)

Returns an InputStream object that references the contents of the Servlet environment object of the specified URL. If the Servlet environment variable is not found, a null value is returned, and the URL path should have this format: / dir/dir/filename.ext.

This method is a convenient way to get URL objects through the getResource method. Please note that when you use this method, meta-information (such as content length, content type) will be lost.

10 、 getRequestDispatcher

Public RequestDispatcher getRequestDispatcher (String uripath)

If the active resource can be found under this specified path (for example, a Servlet,JSP page, CGI, etc.), it returns a RequestDispatcher object for a specific URL, otherwise, it returns a null value, and the Servlet engine is responsible for encapsulating the target path with a request dispatcher object. This request dispatcher object can be used for the transmission of full requests.

11 、 getServerInfo

Public String getServerInfo ()

Returns a String object that includes at least the name and version number of the Servlet engine.

12 、 log

Public void log (String msg)

Public void log (String msg, Throwable t)

Public void log (Exception exception, String msg); / / this usage will be cancelled

Writes the specified information to a log file of a Servlet environment object. The log file to be written is specified by the Servlet engine, but this is usually an event log. When this method is called by an exception, the stack trace is included in the log.

13 、 setAttribute

Public void setAttribute (String name, Object o)

Give the object you specified in the Servlet environment object a name.

14 、 removeAttribute

Public void removeAttribute (String name)

Removes a property from the specified Servlet environment object.

Note: the following methods will be cancelled

15 、 getServlet

Public Servlet getServlet (String name) throws ServletException

Originally used to return a Servlet with a specified name, or a null value if it is not found. If the Servlet can be returned, it means that it has been initialized and is ready to accept service requests. This is a dangerous way. When you call this method, you may not know the state of the Servlet, which can lead to problems with the server state. This method of allowing one Servlet to access other Servlet is equally dangerous.

This method now returns a null value and has not been cancelled in order to maintain compatibility with previous versions. This method will be canceled in future versions of API.

16 、 getServletNames

Public Enumeration getServletNames ()

Originally used to return a list of String objects that represents all known Servlet object names in this Servlet environment. The list always contains the Servlet itself.

This is also a dangerous approach for the same reasons as the previous method.

Now this method returns an empty list. In order to maintain compatibility with previous versions, this method has not been cancelled. This method will be canceled in future versions of API.

17 、 getServlets

Public Enumeration getServlets ()

Originally used to return a list of all known Servlet objects in this Servelet environment. The list always contains the Servlet itself.

This is also a dangerous approach for the same reasons as the getServlet method.

Now this method returns an empty list. In order to maintain compatibility with previous versions, this method has not been cancelled. This method will be canceled in future versions of API.

5. ServletRequest interface

Define

Public interface ServletRequest

Define an object generated by the Servlet engine through which Servlet can obtain the data requested by the client. This object provides all data, including the name, value, and attribute of the parameter, as well as the input stream, by reading the data of the request body.

Method

1 、 getAttribute

Public Object getAttribute (String name)

Returns the value of the property specified in the request, or a null value if the property does not exist. This method allows access to request information that is not provided to other methods in this interface, as well as other data that Servlet places in the request object.

2 、 getAttributeNames

Public Enumeration getAttributeNames ()

Returns a list of all attribute names contained in this request.

3 、 getCharacterEncoding

Public String getCharacterEncoding ()

Returns the character encoding type of the input in the request, or a null value if no character encoding type is defined.

4 、 getContentLength

Public int getContentLength ()

The length of the request content, which returns-1 if the length is unknown.

5 、 getContentType

Public String getContentType ()

Returns the MIME type of the request data body, or null if the type is unknown.

6 、 getInputStream

Public ServletInputStream getInputStream () throws IOException

Returns an input stream for reading binary data from the request body. If you have previously obtained the result to be read through the getReader method, this method throws an IllegalStateException.

7 、 getParameter

Public String getParameter (String name)

Returns the value of the specified parameter as a String, or null if the parameter does not exist. For example, in a HTTP Servlet, this method returns the value of a parameter generated by a specified query statement or a parameter value in a submitted form. If a parameter name corresponds to several parameter values, this method can only return the first value in the array returned by the getParameterValues method. Therefore, if this parameter has (or may have) multiple values, you can only use the getParameterValues method.

8 、 getParameterNames

Public Enumeration getParameterNames ()

Returns a list of String objects for all parameter names, and if no parameters are entered, the method returns a null value.

9 、 getParameterValues

Public String [] getParameterValues (String name)

Returns the value of the specified parameter through an array of String objects, or a null value if the parameter does not exist.

10 、 getProtocol

Public String getProtocol ()

Returns the protocol used for this request in the form of protocol / major version number. Minor version number. For example, for a HTTP1.0 request, the method returns HTTP/1.0.

11 、 getReader

Public BufferedReader getReader () throws IOException

This method returns an entity that buffered reader uses to read the request body, which is encoded according to the encoding of the request data. If the input stream of the request has been obtained by the getInputStream call, the method throws an IllegalStateException.

12 、 getRemoteAddr

Public String getRemoteAddr ()

Returns the IP address of the sending requester.

13 、 getRemoteHost

Public String getRemoteHost ()

Returns the host name of the sending requestor. If the engine cannot or chooses not to resolve the hostname (to improve performance), this method returns the IP address directly.

14 、 getScheme

Public String getScheme ()

Returns the mode of the URL used by the request. For example, for a HTTP request, the pattern is http.

15 、 getServerName

Public String getServerName ()

Returns the hostname of the server that received the request.

16 、 getServerPort

Public int getServerPort ()

Returns the port number on which the request was received.

17 、 setAttribute

Public void setAttribute (String name, Object object)

This method adds a property to the request that can be used by other objects that can access the request object, such as a nested Servlet.

Note: the following methods will be cancelled

GetRealPath

Public String getRealPath (String path)

Returns the real path corresponding to the virtual path, and if for some reason this process cannot be done, the method returns a null value.

This method duplicates the getRealPath method in the ServletContext interface. In version 2.1, the ServletContext interface will clarify the mapping of all the paths that can be used by a Servlet. The result of the execution of this method will be exactly the same as that of the getRealPath method in ServletContext.

VI. ServletResponse interface

Define

Public interface ServletResponse

Define an object generated by the Servlet engine through which the Servlet responds to the client's request. The response should be an MIME entity, which could be a HTML page, image data, or other MIME format.

Method

1 、 getCharacterEncoding

Public String getCharacterEncoding ()

Returns the character encoding of the MIME entity. This character encoding can be the specified type or the type that best matches the character encoding that the client can accept as reflected in the request header domain. In the HTTP protocol, this information is transmitted to the Servlet engine via Accept-Charset.

For more information about character encoding and MIME, see RFC 2047.

2 、 getOutputStream

Public ServletOutputStream getOutputStream () throws IOException

Returns an output stream that records binary response data.

If the response object has already called getWriter, IllegalStateException will be thrown.

3 、 getWriter

Public PrintWriter getWriter throws IOException

This method returns a PringWriter object to record the formatted response entity. If you want to reflect the character encoding used, you must modify the MIME type of the response. Before calling this method, you must set the content type of the response.

If no such encoding type is provided, a UnsupportedEncodingException is thrown, and if the response object has already called getOutputStream, a getOutputStream is thrown.

4 、 setContentLength

Public void setContentLength (int length)

Set the length of the content of the response, this method overrides the previous setting of the content length.

To ensure that the content length of the response header is successfully set, this method must be called before the response is submitted to the output stream.

5 、 setContentType

Public void setContentType (String type)

This method is used to set the content type of the response. This type may later be implicitly modified in other cases, where the other case may be when the server finds it necessary to set the MIME characters.

To ensure that the content type of the response header is successfully set, this method must be called before the response is submitted to the output stream.

7. SingleThreadModel interface

Define

Public interface SingleThreadModel

This is an empty interface that specifies how the system handles calls to the same Servlet. If a Servlet is specified by this interface, no two threads will be executed at the same time in the service method in this Servlet.

Servlet can achieve this guarantee by maintaining a separate pool of Servlet instances, or by having only one thread in Servlet's service.

8. GenericServlet class

Public abstract class GenericServlet implements Servlet

ServletConfig, Serializable

The existence of this class makes it easier to write Servlet. It provides a simple scheme for executing methods about the Servlet life cycle and describing ServletConfig and ServletContext objects at initialization time.

Method

1 、 destroy

Public void destroy ()

The destroy method doesn't do any other work here.

2 、 getInitParameter

Public String getInitParameter (String name)

This is an easy way to call the method of the same name of the ServletConfig object.

3 、 getInitParameterNames

Public Enumeration getInitParameterNames ()

This is an easy way to call the method of the same name of the ServletConfig object.

4 、 getServletConfig

Public ServletConfig getServletConfig ()

Returns a description of the ServletConfig object generated through the init method of this class.

5 、 getServletContext

Public ServletContext getServletContext ()

This is an easy way to call the method of the same name of the ServletConfig object.

6 、 getServletInfo

Public String getServletInfo ()

Returns a String that reflects the Servlet version.

7 、 init

Public void init () throws ServletException

Public void init (ServletConfig config) throws ServletException

The init (ServletConfig config) method is an easy way to initialize the life cycle of this Servlet.

The init () method is used to allow you to extend the GenericServlet class. When using this method, you do not need to store the config object or call super.init (config).

The init (ServletConfig config) method stores the config object and then calls init (). If you overload this method, you must call super.init (config) for the other methods of the GenericServlet class to work properly.

8 、 log

Public void log (String msg)

Public void log (String msg, Throwable cause)

Writes the class name of Servlet and the given information to the log file through the Servlet content object.

9 、 service

Public abstract void service (ServletRequest request, ServletResponse

Response) throws ServletException, IOException

This is an abstract method, and when you extend this class, in order to execute a network request, you must execute it.

9. ServletInputStream class

Define

Public abstract class ServletInputStream extends InputStream

This class defines an input stream that reads the client's request information. This is an abstract class provided by the Servlet engine. A Servlet gets a description of a ServletInputStream object by using the ServletRequest interface.

A subclass of this class must provide a method to read relevant information from the InputStream interface.

Method

1 、 readLine

Public int readLine (byte [] b, int off, int len) throws IOException

Reads bytes of the specified length into the specified array starting at the specified offset of the input stream. If all the requested contents of the line have been read, the reading process ends. If a new line is encountered, the first character of the new line will also be read into the array.

10. ServletOutputStream class

Define

Public abstract class ServletOutputStream extends OutputStream

This is an abstract class used by the Servlet engine. Servlet gets a description of an object of this type by using the ServletResponse interface. Using this output stream, you can return the data to the client.

A subclass of this class must provide a method to write information to the OutputStream interface.

In this interface, when a refresh or closed method is called. The information for all data buffers will be sent to the client, that is, the response will be submitted. Note that it is not necessary to close the implied socket stream when closing this type of object.

Method

1 、 print

Public void print (String s) throws IOException

Public void print (boolean b) throws IOException

Public void print (char c) throws IOException

Public void print (int I) throws IOException

Public void print (long l) throws IOException

Public void print (float f) throws IOException

Public void print (double d) throws IOException

Output variables to the output stream

2 、 println

Public void println () throws IOException

Public void println (String s) throws IOException

Public void println (boolean b) throws IOException

Public void println (char c) throws IOException

Public void println (int I) throws IOException

Public void println (long l) throws IOException

Public void println (float f) throws IOException

Public void println (double d) throws IOException

Output variables to the output stream and add a carriage return newline character

Eleventh, ServletException class

Define

Public class ServletException extends Exception

An exception thrown when Servlet encounters a problem.

Constructor function

Public ServletException ()

Public ServletException (String message)

Public ServletException (String message, Throwable cause)

Public ServletException (Throwable cause)

Construct a new ServletException, and if the constructor includes a Throwable parameter, the Throwable object will be used as the possible reason for throwing the exception.

Method

1 、 getRootCause

Public Throwable getRootCause ()

If the reason for throwing the exception is configured, the method returns that reason, otherwise it returns a null value.

XII. Unsupported ableException class

Define

Public class UnavailableException extends ServletException

This exception is thrown regardless of whether a Servlet is permanently or temporarily invalid. Servlet records the exception and the corresponding action to be taken by the Servlet engine.

Temporary invalidation means that the Servlet is unable to process the request at some point due to a temporary problem. For example, services (possibly databases) at a different application layer cannot be used. The problem may be corrected by itself or other corrective actions may be required.

Permanent invalidation means that this Servlet will not be able to process client requests unless the administrator takes action. For example, the Servlet configuration information is missing or the state of the Servlet is corrupted.

The Servlet engine can safely handle both exceptions, including permanent invalidation, but normal handling of temporary invalidation can make the Servlet engine more robust. In particular, the request for Servlet is only blocked (or postponed) for a period of time, which is obviously more scientific than denying the request completely before service itself restarts.

Constructor function

Public UnavailableException (Servlet servlet, String message)

Public UnavailableException (int seconds, Servlet servlet

String message)

Constructs a new exception that contains the specified description. If this constructor has an argument about the number of seconds, this will give the estimated time that the request can be reprocessed after the temporary invalidation of the Servlet. If this parameter is not included, this means that the Servlet is permanently invalid.

Method

1 、 getServlet

Public Servlet getServlet ()

Return Servlet with invalid report. This is used by the Servlet engine to identify the affected Servlet.

2 、 getUnavailableSeconds

Public int getUnavailableSeconds ()

Returns the expected invalid time of the Servlet, or-1 if the Servlet is permanently invalid.

3 、 isPermanent

Public boolean isPermanent ()

If the Servlet is permanently invalid, a Boolean true is returned, indicating that some administrative action must be taken to make the Servlet available.

[@ more@]

Software package: javax.servlet.http

Included interface: HttpServletRequest;HttpServletResponse;HttpSession;HttpSessionBindingListener;HttpSessionContext.

Included class: Cookie;HttpServlet;HttpSessionBindingEvent;HttpUtils.

I. HttpServletRequest interface

Define

Public interface HttpServletRequest extends ServletRequest

It is used to process a request information in HTTP format for Servlet.

Method

1 、 getAuthType

Public String getAuthType ()

Returns the authentication mode for this request.

2 、 getCookies

Public Cookie [] getCookies ()

Returns an array containing all the current cookie in the request. If there is no cookie in this request, an empty array is returned.

3 、 getDateHeader

Public long getDateHeader (String name)

Returns the value of the specified request header field, which is converted to a long integer accurate to milliseconds since 1970-1-1 (GMT).

If the header field cannot be converted, throw an IllegalArgumentException. If the request header domain does not exist, this method returns-1.

4 、 getHeader

Public String getHeader (String name)

Returns the value of a request header field. (translator's note: unlike the previous method, this method returns a string)

If the request header domain does not exist, this method returns-1.

5 、 getHeaderNames

Public Enumeration getHeaderNames ()

This method returns a list of String objects that reflect all the header domain names of the request.

Some engines may not allow access to the header domain through this method, in which case this method returns an empty list.

6 、 getIntHeader

Public int getIntHeader (String name)

Returns the value of the specified request header field, which is converted to an integer.

If the header field cannot be converted, throw an IllegalArgumentException. If the request header domain does not exist, this method returns-1.

7 、 getMethod

Public String getMethod ()

Returns the HTTP method used for this request (for example: GET, POST, PUT)

8 、 getPathInfo

Public String getPathInfo ()

This method returns additional path information for the request URL after the Servlet path of the request URL. If the request URL includes a query string, the query string will not be included in the return value. This path must be decoded by URL before being returned. If there is no path information after the Servlet path of the requested URL. This method returns a null value.

9 、 getPathTranslated

Public String getPathTranslated ()

This method takes the additional path information after the Servlet path of the requested URL and converts it into a real path. The requested URL must be decoded by URL before the conversion can be performed. If there is no additional path information after the Servlet path of this URL. This method returns a null value.

10 、 getQueryString

Public String getQueryString ()

Returns the query string contained in the request URL. A query string in a URL consists of a "?" Lead out. If there is no query string, this method returns a null value.

11 、 getRemoteUser

Public String getRemoteUser

Returns the requested user name, which is used for HTTP user argument.

If there is no user name information in the request, this method returns a null value.

12 、 getRequestedSessionId

Public String getRequestedSessionId ()

Return the corresponding session id for this request. If for some reason the session id provided by the client is invalid, this session id will be different from the session id in the current session, and at the same time, a new session will be created.

If the request is not associated with a session, this method returns a null value.

13 、 getRequestURI

Public String getRequestURI ()

Returns the part of the requested URL that defines the requested resource from the first line of the HTTP request. If a query string exists, the query string will not be included in the return value. For example, if a request is accessed through a URL path such as / catalog/books?id=1, this method will return / catalog/books. The return value of this method includes the Servlet path and path information.

If part of the URL path is URL encoded, the return value of this method must be decoded before it can be returned.

14 、 getServletPath

Public String getServletPath ()

This method returns the part of the request URL that reflects the call to Servlet. For example, a Servlet is mapped to the URL path / catalog/summer, while a request uses a path such as / catalog/summer/casual. The so-called part of reflecting the call to Servlet is / catalog/summer.

If the Servlet is not called through path matching. This method will return a null value.

15 、 getSession

Public HttpSession getSession ()

Public HttpSession getSession (boolean create)

Returns the current valid session associated with this request. If this method is called without arguments, a new session will be created if no session is associated with the request. If you call this method with a Boolean parameter, the session will be established only if the parameter is true.

To ensure that session can be fully maintained. The Servlet developer must call this method before the response is submitted.

If the parameter brought in is false and there is no session associated with the request. This method returns a null value.

16 、 isRequestedSessionIdValid

Public boolean isRequestedSessionIdValid ()

This method checks whether the session associated with this request is currently valid. If the session used in the current request is invalid, it cannot be returned through the getSession method.

17 、 isRequestedSessionIdFromCookie

Public boolean isRequestedSessionIdFromCookie ()

If the session id of the request is provided through a cookie on the client, the method returns true, otherwise it returns false.

18 、 isRequestedSessionIdFromURL

Public boolean isRequestedSessionIdFromURL ()

If the session id of the request is provided through part of the client's URL, the method returns true, otherwise it returns false. Note that this method is different from isRequestedSessionIdFromUrl in the spelling of URL.

The following methods will be cancelled

19 、 isRequestedSessionIdFromUrl

Public boolean isRequestedSessionIdFromUrl ()

This method is replaced by isRequestedSessionIdFromURL.

II. HttpServletResponse interface

Define

Public interface HttpServletResponse extends ServletResponse

Describes a HTTP response returned to the client. This interface allows Servlet programmers to take advantage of header information specified in the HTTP protocol.

Member variable

Public static final int SC_CONTINUE = 100

Public static final int SC_SWITCHING_PROTOCOLS = 101

Public static final int SC_OK = 200

Public static final int SC_CREATED = 201

Public static final int SC_ACCEPTED = 202

Public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203

Public static final int SC_NO_CONTENT = 204

Public static final int SC_RESET_CONTENT = 205

Public static final int SC_PARTIAL_CONTENT = 206,

Public static final int SC_MULTIPLE_CHOICES = 300

Public static final int SC_MOVED_PERMANENTLY = 301

Public static final int SC_MOVED_TEMPORARILY = 302

Public static final int SC_SEE_OTHER = 303

Public static final int SC_NOT_MODIFIED = 304,

Public static final int SC_USE_PROXY = 305

Public static final int SC_BAD_REQUEST = 400

Public static final int SC_UNAUTHORIZED = 401

Public static final int SC_PAYMENT_REQUIRED = 402

Public static final int SC_FORBIDDEN = 403

Public static final int SC_NOT_FOUND = 404

Public static final int SC_METHOD_NOT_ALLOWED = 405

Public static final int SC_NOT_ACCEPTABLE = 406

Public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407

Public static final int SC_REQUEST_TIMEOUT = 408

Public static final int SC_CONFLICT = 409

Public static final int SC_GONE = 410

Public static final int SC_LENGTH_REQUIRED = 411

Public static final int SC_PRECONDITION_FAILED = 412

Public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413

Public static final int SC_REQUEST_URI_TOO_LONG = 414

Public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415

Public static final int SC_INTERNAL_SERVER_ERROR = 500,

Public static final int SC_NOT_IMPLEMENTED = 501

Public static final int SC_BAD_GATEWAY = 502

Public static final int SC_SERVICE_UNAVAILABLE = 503

Public static final int SC_GATEWAY_TIMEOUT = 504

Public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505

The above HTTP production status code is defined by HTTP/1.1.

Method

1 、 addCookie

Public void addCookie (Cookie cookie)

Adds a specified cookie to the response. This method can be called multiple times to define multiple cookie. In order to set the appropriate header domain, this method should be called before the response is submitted.

2 、 containsHeader

Public boolean containsHeader (String name)

Check whether the specified response header is set.

3 、 encodeRedirectURL

Public String encodeRedirectURL (String url)

Encodes the specified URL used by the sendRedirect method. If you don't need to encode, just return this URL. This additional encoding method is provided because in the case of redirect, the rules for determining whether or not to encode URL are different from the general situation. The given URL must be an absolute URL. Relative URL cannot be received, and an IllegalArgumentException is thrown.

All URL provided to the sendRedirect method should be run through this method to ensure that session tracking works properly in all browsers.

4 、 encodeURL

Public String encodeURL (String url)

Encode the URL that contains session ID. If you don't need to encode, just return this URL. The Servlet engine must provide the URL encoding method, because in some cases we will have to rewrite the URL, for example, including a valid session in the response to the corresponding request, but this session cannot be maintained by a non-URL (such as cookie) means.

All URL provided to Servlet should be run through this method to ensure that session tracking works properly in all browsers.

5 、 sendError

Public void sendError (int statusCode) throws IOException

Public void sendError (int statusCode, String message) throws

IOException

Send an error response to the client with the given status code. If a message parameter is provided, it will be issued as part of the response body, otherwise the server will return the standard information corresponding to the error code.

After this method is called, the response is submitted immediately. After calling this method, Servlet will not have any more output.

6 、 sendRedirect

Public void sendRedirect (String location) throws IOException

Send a temporary redirect response (SC_MOVED_TEMPORARILY) to the client using the given path. The given path must be an absolute URL. The relative URL will not be received and an IllegalArgumentException will be thrown.

This method must be called before the response is submitted. After this method is called, the response is submitted immediately. After calling this method, Servlet will not have any more output.

7 、 setDateHeader

Public void setDateHeader (String name, long date)

Set the response header with a given name and date value, where the date value should be a long integer accurate to milliseconds since 1970-1-1 (GMT). If the response header has been set, the new value will overwrite the current value.

8 、 setHeader

Public void setHeader (String name, String value)

Sets the response header with a given name and domain. If the response header has been set, the new value will overwrite the current value.

9 、 setIntHeader

Public void setIntHeader (String name, int value)

Sets the response header with a given name and shaping value. If the response header has been set, the new value will overwrite the current value.

10 、 setStatus

Public void setStatus (int statusCode)

This method sets the status code of the response, and if the status code has been set, the new value will overwrite the current value.

The following methods will be cancelled

11 、 encodeRedirectUrl

Public String encodeRedirectUrl (String url)

This method is replaced by encodeRedirectURL.

12 、 encodeUrl

Public String encodeUrl (String url)

This method is replaced by encodeURL.

13 、 setStatus

Public void setStatus (int statusCode, String message)

This method sets the status code of the response, and if the status code has been set, the new value will overwrite the current value. If a message is provided, it will also be sent as part of the response body.

III. HttpSession interface

Define

Public interface HttpSession

This interface is used by the Servlet engine to correlate between the HTTP client and the HTTP session. This association may last for a given period of time in multiple external connections and requests. Session is used to maintain state and identify users over multiple request pages under the stateless HTTP protocol.

A session can be maintained by cookie or by rewriting URL.

Method

1 、 getCreationTime

Public long getCreationTime ()

Returns the time when the session was established, expressed as milliseconds since 1970-1-1 (GMT).

2 、 getId

Public String getId ()

Returns the identifier assigned to this session. The identifier of a HTTP session is a unique string established and maintained by the server.

3 、 getLastAccessedTime

Public long getLastAccessedTime ()

Returns the last time the client issued a request related to this session, or-1 if the session was newly created. This time is expressed as milliseconds since 1970-1-1 (GMT).

4 、 getMaxInactiveInterval

Public int getMaxInactiveInterval ()

Add back the number of seconds, which represents the maximum amount of time that the session will be maintained by the Servlet engine when the client does not make a request. After this time, the Servlet engine may be terminated by the Servlet engine. If the session is not terminated, the method returns-1.

Calling this method when session is invalid throws an IllegalStateException.

5 、 getValue

Public Object getValue (String name)

Returns an object bound to the session with the given name. If no such binding exists, a null value is returned.

Calling this method when session is invalid throws an IllegalStateException.

6 、 getValueNames

Public String [] getValueNames ()

Returns the names of all data bound to the session as an array.

Calling this method when session is invalid throws an IllegalStateException.

7 、 invalidate

Public void invalidate ()

This method terminates the session. All data bound to this session will be erased. And send out the notification through the valueUnbound method of the HttpSessionBindingListener interface.

8 、 isNew

Public boolean isNew ()

Returns a Boolean value to determine whether the session is new. If a session has been established by the server but has not received a request from the corresponding client, the session will be considered new. This means that the client has not joined the session or is not recognized by the session. The appropriate session authentication information cannot be returned when he makes the next request.

Calling this method when session is invalid throws an IllegalStateException.

9 、 putValue

Public void putValue (String name, Object value)

Binds the given object to session with the given name. Existing bindings with the same name are reset. The valueBound method of the HttpSessionBindingListener interface is called.

Calling this method when session is invalid throws an IllegalStateException.

10 、 removeValue

Public void removeValue (String name)

Unbind an object with a given name from the session. If a bound object with a given name is not found, this method does nothing. The valueUnbound method of the HttpSessionBindingListener interface is called.

Calling this method when session is invalid throws an IllegalStateException.

11 、 setMaxInactiveInterval

Public int setMaxInactiveInterval (int interval)

Sets the number of seconds, which represents the maximum amount of time that the session will be maintained by the Servlet engine when the client does not make a request.

The following method will be cancelled

12 、 getSessionContext

Public HttpSessionContext getSessionContext ()

Returns the environment variable in which session is persisted. This method is cancelled like all other HttpSessionContext methods.

IV. HttpSessionBindingListener interface

Define

Public interface HttpSessionBindingListener

This object is added to the session of the HTTP, and executing this interface will inform you whether any objects have been bound to or unbound from the HTTP session.

Method

1 、 valueBound

Public void valueBound (HttpSessionBindingEvent event)

This method is called when an object is bound to session. The Servlet engine should call the HttpSession.putValue method when it is called.

2 、 valueUnbound

Public void valueUnbound (HttpSessionBindingEvent event)

This method is called when an object is unbound from the session. The Servlet engine should call the HttpSession.removeValue method when it is called.

5. HttpSessionContext interface

Define

This interface will be cancelled

Public interface HttpSessionContext

This object is a single entity associated with a set of HTTP session.

This interface has been removed for security reasons, and it appears in the current version only for compatibility reasons. The method of this interface returns the corresponding value that simulates the definition of the previous version.

Method

1 、 getSession

Public HttpSession getSession (String sessionId)

It was used to return the session associated with this session id. Now return a null value.

2 、 getIds

Public Enumeration getIds ()

It was used to return a list of all the session id in this environment. Now return to the empty list.

VI. Cookie class

Define

Public class Cookie implements Cloneable

This class describes a cookie. For the definition of cookie, you can refer to the description of Netscape Communications Corporation or RFC 2109.

Constructor function

Public Cookie (String name, String value)

Define a cookie with a name-value pair. This name must be accepted by HTTP/1.1.

Name that begins with the character $is reserved by RFC 2109.

If the given name is not accepted by the HTTP/1.1, the method throws an IllegalArgumentException.

Method

1 、 getComment

Public String getComment ()

Returns a description describing the purpose of the cookie, or a null value if the description is not defined.

2 、 getDomain

Public String getDomain ()

Returns the region where the cookie can appear, or null if no region is defined.

3 、 getMaxAge

Public int getMaxAge ()

This method returns the maximum survival period specified by the cookie. If the maximum survival period is not defined, the method returns-1.

4 、 getName

Public String getName ()

The method returns the cookie name.

5 、 getPath

Public String getPath ()

Returns the prefixes of all URL paths that are valid for this cookie, or null if not defined.

6 、 getSecure

Public boolean getSecure ()

If the cookie returns true only through secure channel transport, otherwise it returns false.

7 、 getValue

Public String getValue ()

This method returns the value of cookie.

8 、 getVersion

Public int getVersion ()

Returns the version of cookie. Version 1 is interpreted by RFC 2109. Version 0 is explained by the description of Netscape Communications Corporation. The newly constructed cookie defaults to version 0.

9 、 setComment

Public void setComment (String purpose)

If one user submits the cookie to another user, the purpose of the cookie must be described through this description. Version 0 does not support this attribute.

10 、 setDomain

Public void setDomain (String pattern)

This method sets the properties of the valid domain of the cookie. This property specifies the area where the cookie can appear. A valid domain begins with a dot (.foo.com), which means that the cookie can be seen by hosts in the zone of the specified domain name resolution system (which may be www.foo.com but not a.b.foo.com). By default, cookie can only return to the host where it was saved.

11 、 setMaxAge

Public void setMaxAge (int expiry)

This method sets the maximum survival time of the cookie. After this period of survival, cookie will be finally targeted. A negative number means that the cookie will not take effect, and 0 will remove the cookie from the client.

12 、 setPath

Public void setPath (String uri)

This method sets the path property of the cookie. The client can only return cookie to paths that begin with this given path, String.

13 、 setSecure

Public void setSecure (boolean flag)

Indicates that this cookie can only be sent through a secure channel (such as HTTPS). This can only be set if the server that generated the cookie uses the security protocol to send the cookie value.

14 、 setValue

Public void setValue (String newValue)

Set the value of this cookie, using BASE64 encoding for binary data.

Version 0 cannot use spaces, {}, (), =, ", /,?, @,: and;.

15 、 setVersion

Public void setVersion (int v)

Set the version number of cookie

7. HttpServlet class

Define

Public class HttpServlet extends GenericServlet implements

Serializable

This is an abstract class that simplifies the process of writing HTTP Servlet. It is an extension of the GenericServlet class and provides a framework for dealing with the HTTP protocol.

The service method in this class supports standard HTTP methods such as GET and POST. This support process is achieved by assigning them to the appropriate methods (such as doGet, doPost).

Method

1 、 doDelete

Protected void doDelete (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP DELETE operation. This operation allows the client to request that the URL be removed from the server. This operation may have a negative impact, and the user is responsible for it.

The default execution result of this method is to return a HTTP BAD_REQUEST error. You must overload this method when you want to process a DELETE request.

2 、 doGet

Protected void doGet (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP GET operation. This operation allows the client to simply "get" resources from a HTTP server. Overloading this method will automatically support the HEAD method.

GET operations should be safe and have no negative impact. This operation should also be safe to repeat.

The default execution result of this method is to return a HTTP BAD_REQUEST error.

3 、 doHead

Protected void doHead (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP HEAD operation. By default, this operation is performed according to an unconditional GET method, which returns no data to the client, just header information containing the length of the content.

Like the GET operation, this operation should be safe and have no negative impact. This operation should also be safe to repeat.

The default execution result of this method is to automatically handle the HTTP HEAD operation, which does not need to be executed by a subclass.

4 、 doOptions

Protected void doOptions (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP OPTION operation. This operation automatically determines which HTTP method is supported. For example, if a Servlet writes a subclass of HttpServlet and overloads the doGet method, doOption returns the following header:

Allow: GET,HEAD,TRACE,OPTIONS

You don't usually need to overload this method.

5 、 doPost

Protected void doPost (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP POST operation. This operation contains the data of the request body, and Servlet should act according to it.

This operation may have a negative impact. Such as updating stored data or shopping online.

The default execution result of this method is to return a HTTP BAD_REQUEST error. When you want to handle the POST operation, you must overload this method in a subclass of HttpServlet.

6 、 doPut

Protected void doPut (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP PUT operation. This is similar to sending a file through FTP.

This operation may have a negative impact. Such as updating stored data or shopping online.

The default execution result of this method is to return a HTTP BAD_REQUEST error. When you want to handle the PUT operation, you must overload this method in a subclass of HttpServlet.

7 、 doTrace

Protected void doTrace (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Called by the service method of this class to handle a HTTP TRACE operation. The default result of this operation is to produce a response that contains information that reflects all the header fields sent in the trace request.

When you develop Servlet, in most cases you need to overload this method.

8 、 getLastModified

Protected long getLastModified (HttpServletRequest request)

Returns the last modification time of this request entity. To support GET operations, you must override this method to accurately reflect the time of the last modification. This will help browsers and proxy servers reduce the load of server and network resources and thus work more efficiently. The value returned is the number of milliseconds since 1970-1-1 (GMT).

The default execution result is to return a negative number, which indicates that the last modification time is unknown and cannot be used by a conditional GET operation.

9 、 service

Protected void service (HttpServletRequest request

HttpServletResponse response) throws ServletException

IOException

Public void service (ServletRequest request, ServletResponse response)

Throws ServletException, IOException

This is a Servlet HTTP-specific scheme that assigns requests to other methods of the class that support the request.

When you develop Servlet, you don't have to overload this method in most cases.

8. HttpSessionBindingEventclass

Define

Public class HttpSessionBindingEvent extends EventObject

This event connects to HttpSession when it is heard that binding and unbinding occurs in HttpSessionBindingListener. This may be the result of a session being terminated or found to be invalid.

The event source is HttpSession.putValue or HttpSession.removeValue.

Constructor function

Public HttpSessionBindingEvent (HttpSession session, String name)

Construct a new HttpSessionBindingEvent from the Session that caused the event and the name of the object that was bound or unbound.

Method

1 、 getName

Public String getName ()

Returns the name of the object on which binding and unbinding occurred.

2 、 getSession

Public HttpSession getSession ()

Returns the name of the session where binding and unbinding occurred.

9. HttpUtils class

Define

Public class HttpUtils

Collect the static and effective methods used by HTTP Servlet.

Method

1 、 getRequestURL

Public static StringBuffer getRequestURL (HttpServletRequest

Request)

Recreate the URL that the client uses to establish the request on the server. This method reflects different protocols (such as http and https) and ports, but does not contain a query string.

This method returns a StringBuffer instead of a String so that the URL can be effectively modified by the Servlet developer.

2 、 parsePostData

Public static Hashtable parsePostData (int len

ServletInputstream in)

Parse a stream containing data of type MIME application/x-www-form-urlencoded and create a hash table with key value-data pairs. The key value here is a string, and the data is a list of values corresponding to that string. A key value can appear one or more times in POST data. Each time this key value appears, its corresponding value is added to the list of values corresponding to the string in the hash table.

Data read from POST data will be decoded by URL, and + data that will be converted to spaces and transmitted in hexadecimal (for example,% xx) will be converted into characters.

This method throws an IllegalArgumentException when the POST data is invalid.

3 、 parseQueryString

Public static Hashtable parseQueryString (String s)

Parse a query string and create a hash table with key value-data pairs. The data here is a list of values corresponding to the string. A key value can appear one or more times. Each time this key value appears, its corresponding value is added to the list of values corresponding to the string in the hash table.

Data read from the query string will be decoded by URL, and + data that will be converted to spaces and transmitted in hexadecimal (for example,% xx) will be converted to characters.

This method throws an IllegalArgumentException when the query string is invalid.

Glossary of terms

Bytecode

Bytecode: machine code generated by the Java compiler and the Java interpreter.

Cookie

The data created by the Web server, which is stored on the user's computer, provides a way for the Web site to track the user's parameters and store them on the user's own hard disk.

HTTP

Hypertext transfer protocol. A request response protocol is used to connect the WWW server to transmit HTML pages to the client browser.

Input stream object

An object, defined by the ServletInputStream class, is used by Servlet to read requests from the client.

Mapping

A pair of Servlet instances and URL that Servlet returns data, for example, HelloServlet and / hello/index.html.

Output stream object

An object, defined by the ServletOutputStream class class, is used by Servlet to return data to the client.

Request dispatcher object

An object defined by the RequestDispatcher interface that receives requests from the client and sends them to other resources (such as Servlet, CGI, HTML files, or JSP files) available on the Web server.

Sandboxed servlet

Servlet that runs under a security constraint.

Servlet

A small, platform-independent Java program with no graphical user interface. It can extend the functionality of Web services in many ways.

Servlet configuration object

An object defined by the ServletConfig interface to configure a Servlet.

Servlet context object

An object defined by the ServletContext interface. Give Servlet information about the Servlet engine.

Servlet engine

An environment created by a Web server provider that allows Servlet to run on a specific Web server.

Servlet request object

An object defined by the ServletRequest interface that allows Servlet to obtain the data requested by the client.

Servlet response object

An object defined by the ServletResponse interface that allows Servlet to respond.

Servlet runner

The sun.servlet.http.HttpServer process in Java Servlet Developer's Kit (JSDK), which enables Servlet to run.

Session tracking

In a Web application, the ability to identify a continuous and unique request from the same client.

SSL

Encrypt the socket protocol layer. A security protocol used to exchange keys and encrypted data between client browsers and servers on Iternet.

URI

Uniform resource identification. Define an Internet address, which is a superset of URL.

URL

Unified resource path. This address defines the route to a file on a WWW, usually consisting of a protocol prefix, domain name, directory name, and file name.

Thank you for reading this article carefully. I hope the article "sample Analysis of Servlet" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report