Servlet & JSP (3)

Source: Internet
Author: User

We discussed servlet in servlet parsing (2 ).
The servlet interface in the UML class diagram. In this article, we will continue to discuss servletrequest, servletresponse, and servletconfig. In addition, there are servlet exceptions and servlet context.

Servletrequest and servletresponse

The servletrequest and servletresponse interfaces are defined in the javax. servlet package. Common methods in the servletrequest interface are as follows:

Public java. Lang. Object getattribute (Java. Lang. string name) // return the value of the attribute named by name. If this property does not exist, this method returns NULL. Public java. util. Enumeration getattributenames () // return the names of all available attributes in the request. If no attribute exists in the request, this method returns an empty enumeration set. Public void removeattribute (Java. Lang. string name) // remove the attribute named name in the request. Public void setattribute (Java. Lang. string name, java. Lang. Object O) // Save the attribute named name in the request. If the second parameter o is null, removeattribute (name) is called ). Public java. Lang. String getcharacterencoding () // returns the name of the character encoding used by the request body. If no character encoding is specified for the request, this method returns NULL. Public int getcontentlength () // returns the length of the Request body in bytes. If the length is unknown, this method returns-1. Public java. Lang. String getcontenttype () // returns the MIME type of the Request body. If the type is unknown, this method returns NULL. Public servletinputstream getinputstream () // returns an input stream that reads the content of the request body in binary mode. Javax. servlet. servletinputstream is an abstract class inherited from Java. Io. inputstream. Public java. Lang. String getlocaladdr () // returns the IP address of the network interface that receives the request. This method is added in the servlet 2.4 specification. Public java. Lang. String getlocalname () // return the Host Name of the IP interface that receives the request. This method is added in the servlet 2.4 specification. Public int getlocalport () // return the IP Port Number of the network interface that receives the request. This method is added in the servlet 2.4 specification. Public java. Lang. String getparameter (Java. Lang. string name) // return the value of the name parameter in the request. If the name parameter has multiple values, this method returns the first value in the list. If this parameter is not found in the request, this method returns NULL. Public java. util. Enumeration getparameternames () // return the names of all parameters contained in the request. If the request does not contain any parameters, this method returns an empty enumeration set. Public java. Lang. String [] getparametervalues (Java. Lang. string name) // return all values of the name parameter in the request. If this parameter does not exist in the request, this method returns NULL. Public java. Lang. String getprotocol () // return the name and version of the protocol used in the request, for example, HTTP/1.1. Public java. Io. bufferedreader getreader () throws java. Io. ioexception // returns the bufferedreader object and reads the Request body in character data mode. Public java. Lang. String getremoteaddr () // return the IP address of the client sending the request or the last proxy server. Public java. Lang. String getremotehost () // returns the full qualified name of the client sending the request or the last proxy server. Public int getremoteport () // returns the public requestdispatcher getrequestdispatcher (Java. lang. string path) // returns the requestdispatcher object, which is used as the encapsulation of the resource located by the path. Public java. Lang. String getservername () // return the Host Name of the server to which the request is sent. Public int getserverport () // return the port number of the server to which the request is sent. Public void setcharacterencoding (Java. Lang. String env) throws java. Io. Unsupported encodingexception // overwrite the name of the character encoding used in the Request body.

Common methods in the servletresponse interface are as follows:

Public void flushbuffer () throws java. Io. ioexception // force any content in the cache to be sent to the client. Public int getbuffersize () // returns the actual cache size used for the response. If no cache is used, this method returns 0. Public java. Lang. String getcharacterencoding () // returns the character encoding (MIME Character Set) used by the body sent in the response ). Public java. Lang. String getcontenttype () // return the MIME type used by the body sent in the response. Public servletoutputstream getoutputstream () throws java. Io. ioexception // returns the servletoutputstream object, which is used to write binary data in the response. Javax. servlet. servletoutputstream is an abstract class inherited from Java. Io. outputstream. Public java. Io. printwriter getwriter () throws java. Io. ioexception // returns the printwriter object, which is used to send character text to the client. The printwriter object uses the character encoding returned by the getcharacterencoding () method. If no encoding method is specified for the response, the ISO-8859-1 is used by default. Public Boolean iscommitted () // returns a Boolean value indicating whether a response has been submitted. Public void reset () // clear any data in the cache, including the status code and the message header. If the response has been submitted, this method throws an illegalstateexception. Public void resetbuffer () // clears the response content in the cache and retains the status code and the message header. If the response has been submitted, this method throws an illegalstateexception. Public void setbuffersize (INT size) // set the cache size of the response body. The servlet container uses a cache, which must be at least the requested size. This method must be called before the response body is written. If the content has been written or the response object has been submitted, this method will throw an illegalstateexception. Public void setcharacterencoding (Java. Lang. String charset) // sets the character encoding of the response sent to the client, for example, the UTF-8. Public void setcontentlength (INT Len) // for HTTP servlet, set the length of the content body in the response. This method sets the HTTP Content-Length object header. Public void setcontenttype (Java. Lang. string type) // set the content type of the response to be sent to the client. At this time, the response should not be submitted. The given content type can include character encoding instructions, such as text/html; charset = UTF-8. If this method is called before the getwriter () method is called, the character encoding of the response will only be set from the given content type. If this method is called after the getwriter () method is called or after the response is submitted, the character encoding of the response is not set. When HTTP is used, this method sets the Content-Type object header.

You do not need to write down all the methods listed above. You only need to get a general understanding of them. The key is to understand the methods that the request and response objects can provide. As long as we understand the interaction process and the role of the request object and response object, when we need a method, you can search in the API documentation.

Servletconfig

In the javax. servlet package, the servletconfig interface is defined. The servlet container uses the servletconfig object to pass configuration information to the servlet during its initialization. A servlet has only one servletconfig object. In this interface, the following four methods are defined:

Public java. Lang. String getinitparameter (Java. Lang. string name) // return the value of the initialization parameter whose name is name. The initialization parameter is configured in the web. xml configuration file. If the parameter does not exist, this method returns NULL. Public java. util. Enumeration getinitparameternames () // return the enumerated set of the names of all servlet initialization parameters. If the servlet does not have initialization parameters, this method returns an empty enumeration set. Public servletcontext getservletcontext () // return the reference of the servlet context object, about the use of servletcontext. Public java. Lang. String getservletname () // return the servlet Instance name. This name is specified in the deployment descriptor of the Web application. If it is an unregistered servlet instance, this method returns the servlet class name.

Servlet Exception

The javax. servlet package defines two exception classes: servletexception and unavailableexception.

1) servletexception class

The servletexception class defines a common exception that can be thrown by the init (), service (), and doxxx () methods. This class provides the following four constructor methods and one instance method:

Public servletexception () // This method constructs a new servlet exception. Public servletexception (Java. Lang. String message) // This method constructs a new servlet exception with the specified message. This message can be written to server logs or displayed to users. Public servletexception (Java. lang. string message, Java. lang. throwable rootcause) // if an exception hinders the normal operation of the servlet during servlet execution, this exception is the root cause (root cause) exception. If you need to include the root cause exception in a servlet exception, you can call this constructor and contain a description message. For example, you can embed a java. SQL. sqlexception exception in the servletexception exception. Public servletexception (Java. Lang. throwable rootcause) // The method is the same as above, but the parameter describing the message is not specified. Public java. Lang. throwable getrootcause () // This method returns the exception that causes this servlet exception, that is, the exception that returns the root cause.

2) unavailableexception class

The unavailableexception class is a subclass of the servletexception class. This exception is thrown by the servlet and is used to instruct the servlet container that the servlet is permanently or temporarily unavailable. This class provides the following two constructor methods and two instance methods:

Public unavailableexception (Java. Lang. String MSG) // This method constructs a new exception with a given message, indicating that the servlet is permanently unavailable. Public unavailableexception (Java. Lang. String MSG, int seconds) // This method constructs a new exception with a given message, indicating that the servlet is temporarily unavailable. The parameter seconds indicates that the servlet is unavailable in seconds. If the servlet cannot estimate how long it will recover, it can pass a negative number or zero to the seconds parameter. Public int getunavailableseconds () // This method returns the expected number of seconds of temporary unavailability of the servlet. If a negative number is returned, it indicates that the servlet is permanently unavailable or the length of the Servlet's unavailability cannot be estimated. Public Boolean ispermanent () // returns a Boolean value to indicate whether the servlet is permanently unavailable. Returns true, indicating that the servlet is permanently unavailable; returns false, indicating that the servlet is available or temporarily unavailable.

Servletcontext Interface

A servletcontext object represents the context of a Web application. During servlet initialization, the servlet container passes the servletconfig object to it. You can use the getservletcontext () method of the servletconfig object to obtain the servletcontext object. You can also use the getservletcontext () method of the genericservlet class to obtain the servletcontext object. However, the getservletcontext () method of the genericservlet class also calls the getservletcontext () method of the servletconfig object to obtain this object.

The servletcontext interface defines the following methods. The servlet container provides the implementation of this interface.

public java.lang.Object getAttribute(java.lang.String name)public java.util.Enumeration getAttributeNames()public void removeAttribute(java.lang.String name)public void setAttribute(java.lang.String name, java.lang.Object object)

The above four methods are used to read, remove, and set shared attributes. Any servlet can set a certain attribute, and another servlet of the same web application can read this attribute, whether or not these servlets serve the same customer.

public ServletContext getContext(java.lang.String uripath)

This method returns the servletcontext object corresponding to the specified URL on the server. The given uripath parameter must start with a slash (/) and be interpreted as the path relative to the root of the server document. For security reasons, if you call this method to access a restricted servletcontext object, the method returns NULL.

public String getContextPath()

This method is used to return the context path of the Web application. The context path always starts with a slash (/), but ends with no slash (/). In the default (Root) context, this method returns an empty string "".

public java.lang.String getInitParameter(java.lang.String name)public java.util.Enumeration getInitParameterNames()

You can define initialization parameters for the servlet context, which are used by the entire web application. You can use the <context-param> element in the deployment descriptor (Web. XML) to define context initialization parameters. The preceding two methods are used to access these parameters.

public int getMajorVersion()public int getMinorVersion()

The preceding two methods are used to return the main version and minor version of the Java Servlet API supported by the servlet container. For example, for containers that follow servlet 2.4, the getmajorversion () method returns 2, and the getminorversion () method returns 4.

public java.lang.String getMimeType(java.lang.String file)

This method returns the MIME type of the specified object. If the object type is unknown, this method returns NULL. Mime-type detection is based on the servlet container configuration, or can be specified in the deployment descriptor of the Web application.

public RequestDispatcher getRequestDispatcher(java.lang.String path)

This method returns a requestdispatcher object to encapsulate resources in a specified path. You can use the requestdispatcher object to forward a request to another resource for processing, or include resources in the response. Note that the input parameter path must start with a slash (/) and be interpreted as the path relative to the current context root.

public RequestDispatcher getNamedDispatcher(java.lang.String name)

This method is similar to the getrequestdispatcher () method. The difference is that this method accepts a servlet (or JSP page) name given by the <servlet-Name> element in the deployment descriptor as a parameter.

public java.lang.String getRealPath(java.lang.String path)

In a web application, the resource is referenced by the path relative to the context path. This method returns the actual path of the resource on the Server File System (the absolute path of the file ). The format of the returned real path should be suitable for the computer and operating system running the servlet container (including the correct path separator ). If the servlet container cannot convert a virtual path to a real path, this method returns NULL.

public java.net.URL getResource(java.lang.String path) throws java.net.Malformed URLException

This method returns the URL of the resource mapped to the specified path. The input parameter path must start with a slash (/) and be interpreted as a path relative to the current context root. This method allows the servlet container to generate an available resource for the servlet from any source. The resource can be in a local or remote file system, in a database, or in a war file. If no resource is mapped to the specified path, this method returns NULL.

public java.io.InputStream getResourceAsStream(java.lang.String path)

This method is similar to the getresource () method. The difference is that this method returns the input stream object of the resource. In addition, using the getresourceasstream () method, metadata (such as content length and content type) is lost, while using the getresource () method, metadata is available.

public java.util.Set getResourcePaths(java.lang.String path)

This method returns the resource path list. The path parameter must start with a slash (/) and specify some paths used to match the resource. For example, a Web application contains the following resources:

/Welcome.html
/CATALOG/index.html
/CATALOG/products.html
/CATALOG/offers/books.html
/CATALOG/offers/music.html
/Customer/login. jsp
/WEB-INF/Web. xml
/WEB-INF/classes/COM. Acme. orderservlet. Class
If getresourcepaths ("/") is called, [/welcome.html,/CATALOG/,/customer/,/WEB-INF/] is returned. If getresourcepaths ("/CATALOG/") is called, [/CATALOG/index.html,/CATALOG/products.html,/CATALOG/offers/] is returned.

public java.lang.String getServerInfo()

This method returns the name and version of the container that runs the servlet.

public java.lang.String getServletContextName()

This method returns the name of the Web application corresponding to the current servletcontext specified by the <display-Name> element in the deployment descriptor.

public void log(java.lang.String msg)public void log(java.lang.String message, java.lang.Throwable throwable)

The servletcontext interface provides the above two log recording methods. The first method is used to record general logs, and the second method is used to record stack tracing information for specified exceptions.

A simple example: count the number of visits

Many websites have the function of counting the number of visits. We can use the servletcontext object to save the number of visits. We know that a Web application has only one servletcontext object, and this object can be accessed by all servlets in the Web application, therefore, it is more appropriate to use the servletcontext object to save information that needs to be shared in Web applications.

To save shared information in the servletcontext object, call the setattribute () method of the object. To obtain shared information, call the getattribute () method of the object. In this example, we can call the setattribute () method to save the access count to the context object. When a new access is added, call the getattribute () method to retrieve the access count from the context object and Add 1, then call the setattribute () method to save it back to the context object.

We will continue to use mydemo as the web project, in the com. shan. create a counterservlet class under the Web package, that is, create a counterservlet under the mydemo \ SRC \ com \ Shan \ WEB directory. java, the Code is as follows.

Package COM. shan. web; import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *;/***** a count servlet ** @ author Shan **/public class counterservlet extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws ioexception, servletexception {servletcontext context = getservletcontext (); integer COUNT = NULL; synchronized (context) {COUNT = (integer) context. getattribute ("counter"); If (null = count) {COUNT = new INTEGER (1);} else {COUNT = new INTEGER (count. intvalue () + 1);} context. setattribute ("counter", count);} response. setcontenttype ("text/html; charset = gb2312"); printwriter out = response. getwriter (); out. println ("<HTML> 

The program calls the getservletcontext () method (indirectly inherited from the genericservlet class) to obtain the context object of the Web application. To avoid thread security issues, the synchronized keyword is used to synchronize context objects. Obtain the counter attribute value by calling the getattribute () method of the context object. Determine whether count is null. If it is null, set its initial value to 1. When this servlet is accessed for the first time, the counter attribute is not saved in the context object, so the value of this attribute will return null. If count is not null, add count to 1. Saves count as the value of the counter attribute to the servletcontext object.

After writing the above Code, you need to compile the code and execute the following statement:

javac -classpath D:\apache-tomcat-7.0.33\lib\servlet-api.jar -d classes src\com\shan\web\CounterServlet.java

Copy the compiled classes folder to the D: \ apache-Tomcat-7.0.33 \ webapps \ mydemo folder. Next, you need to modify the Web. xml file. The modified file is as follows:

<?xml version='1.0' encoding='utf-8'?><web-app xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0"  metadata-complete="true">    <description>      My Demo.    </description><servlet><servlet-name>selectServlet</servlet-name><servlet-class>com.shan.web.MyDemoServlet</servlet-class></servlet><servlet><servlet-name>countServlet</servlet-name><servlet-class>com.shan.web.CounterServlet</servlet-class></servlet><servlet-mapping><servlet-name>selectServlet</servlet-name><url-pattern>/SelectColor.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>countServlet</servlet-name><url-pattern>/count.do</url-pattern></servlet-mapping></web-app>

Copy the Web. xml file to the D: \ apache-Tomcat-7.0.33 \ webapps \ mydemo \ WEB-INF folder. Start Tomcat and enter http: localhost: 8080/mydemo/count. Do in the browser to view the result.

Refresh the pages in two browsers alternately, and you can see that the number of visits is also growing alternately. This means that attributes can be shared among multiple clients by using servletcontext to save attributes. Note that different Web applications have different servlet contexts, so servletcontext cannot be used to share attributes between different web applications. In addition, the number of visits starts from 1 after the Tomcat server is restarted. to permanently Save the number of visits, you can save this value to a file or database.

Reprinted please indicate the source: http://blog.csdn.net/iAm333

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.