Servlet of JavaWeb: ServletConfig and ServletContext, servletcontext

Source: Internet
Author: User

Servlet of JavaWeb: ServletConfig and ServletContext, servletcontext
Html path read

In this case, myeclipse has a work area where we write our own web application. After writing, we need to deploy this application on the server, then access the application on the server through a browser.

Assume that the web application has read an html file, which is directly created in the myeclipse file list and created a directory.

 

The html file is located in the WebRoot directory. Then let's take a look at the absolute path in its attributes:

  

As you can see, this path is located in our myeclipse work area. Then the problem arises. When our web application is deployed to the server, the html file will also be deployed. How should we write the path when reading this html file?

It is unrealistic to write absolute paths, which will become unusable as the environment changes. We can use the context path of the web application to solve the problem. The request object has the following method:

Java. lang. String getContextPath () -- Obtain the context path of the web application.

The web Application Path is the name of the web application in the tomcat server, rather than the project name in ecplise.

So we can write the html path like this:

public class testpath extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { File file = new File(request.getContextPath()+"/WebRoot/getmypath.html");            System.out.println(file.getName());}

 

ServletConfig object

 

What is a ServletConfig object?

The ServletConfig object is called the Servlet configuration object. It is mainly used to load the initialization parameters of the configuration file.

 

Creation Time

The ServletConfig object is created after the servlet object is created and before the init method is called. The Config object is passed into the servlet along with the init method.

 

Common Methods

Java. lang. String getInitParameter (java. lang. String name)

Java. util. Enumeration getInitParameterNames () Get all parameters

ServletContext getServletContext () Get the servlet context object

Ava. lang. String getServletName () to get the servlet name

 

Problem: initialization parameters in SevletConfig cannot be shared by other servlets !!

 

The following describes how to use these methods:

We first configure the servlet initialization parameters in the servlet configuration file web. xml, and then use the above method to get the data!

Configuration file:

<Servlet> <servlet-name> testpath </servlet-name> <servlet-class> com. vmaxtam. dotest. testpath </servlet-class> <init-param> -- this label is written in the servlet to be set. <param-name> color </param-name>-attribute name <param-value> red </param-value>-attribute value </init-param> </servlet>

Now let's get the configured data in the corresponding servlet!

ServletConfig servletConfig = getServletConfig();String color = servletConfig.getInitParameter("color");

In this way, we can get the configured data! There are also simpler methods:

First, let's explain: HttpServlet inherits from the GenericServlet class, while the GenericServlet class inherits from the Servlet interface. The Servlet interface has the getServletConfig () method. Therefore, HttpServlet must have the getServletConfig () method (). The GenericServlet class implements the ServletConfig interface, that is, it must implement all the methods in the ServletConfig interface. Therefore, we can write the above Code as follows:

String color = getInitParameter("color");

The other methods are similar. We will not demonstrate them here ~~~

 

What is a ServletContext object?

We know that a Web application can contain multiple servlets. If you need to transmit a copy of data to all Servlets, you can use the ServletContext object.

The ServletContext object is a servlet context object. This object creates only one object in a web application, representing the current web application environment. In the current web application, all servlets share a ServletContext object.

The time when the ServletContext object is created

From the characteristics of the ServletContext object, we can infer the time when it was created: every time a web application is loaded, A ServletContext object is created, then the servlet in the web application can be used together!

So how can we get the created object in servlet?

Obtain the ServletContext object.

The developer cleverly puts the ServletContext object in each servlet in the web application!

When a servlet is created, its constructor will be called, and the init () method will be called to initialize it. During the initialization process, put the ServletContext object into the ServletConfig object! This servlet is very convenient to get the ServletContext object. You only need to use a code!

ServletContext servletContext = this.getServletContext();

 

Common Methods of ServletContext objects

After obtaining the ServletContext object, we need to think: what is the purpose of this object !? The following describes common methods.

There are five main usage methods:

1) obtain the context path of the web application:

Java. lang. String getContextPath ()

 

2) obtain the global parameters of the web application:

Java. lang. String getInitParameter (java. lang. String name)

Java. util. Enumeration getInitParameterNames ()

 

3) methods related to domain objects:

Java. lang. Object getAttribute (java. lang. String name)

Void setAttribute (java. lang. String name, java. lang. Object object)

Void removeAttribute (java. lang. String name)

 

4) for forwarding:

RequestDispatcher getRequestDispatcher (java. lang. String path)

 

5) how to load resource files for web applications:

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

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

 

The following shows how to use these methods:

 

1) obtain the context path of the web Application

Call this method through request

String path = request.getContextPath();System.out.println(path);

Output result:

/TestArea

The web Application Path is the name of the web application in the tomcat server, rather than the project name in ecplise.

Request. getContextPath (); for the convenience of obtaining the context path. This method is recommended.

 

 

2) obtain global parameters of web Applications

 

First, set the global parameter in the web. xml corresponding to the web application: the label of the global parameter is written in the <web-app> label.

<Web-app version = "3.0" 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"> <! -- Global parameter --> <context-param> <param-name> AAA </param-name> <param-value> AAA's value </param-value> </context -param> <context-param> <param-name> BBB </param-name> <param-value> BBB's value </param-value> </context-param>

Then obtain this parameter in the servlet:

// 1. the ServletContext object ServletContext context = this is obtained. getServletContext (); // 2. obtain the global parameter System. out. println (context. getInitParameter ("AAA"); Enumeration <String> enums = context. getInitParameterNames (); while (enums. hasMoreElements () {String paramName = enums. nextElement (); String paramValue = context. getInitParameter (paramName); System. out. println (paramName + "=" + paramValue );}

Note: Global parameters can be obtained for all servlets !!!

 

 

3) methods related to domain objects

What is a domain object?

Domain object: stores and obtains data, which is used to share data between different resources.

Now let's try to upload the data of the first servlet to another servlet!

 

Method 1: Use the jump function to write data in the jump uri when the jump from servlet1 to servlet2

response.sendRedirect("/servlet2?id=867");

 

Method 2: Use the domain object Method

SetAttribute (name, Object): Method for saving data. name, object Data

GetAttribute (name) to obtain data. Name is the name of the stored data.

RemoveAtrribute (name): clears data.

Servlet1:

 

ServletContext context = this.getServletContext();context.setAttribute("id", 123);

 

Then retrieve it from servlet2!

ServletContext context = this.getServletContext();String id = context.getAttribute("id");

   

4) used for forwarding

RequestDispatcher getRequestDispatcher (java. lang. String path)

 

Jump to resources in servlet: Redirection/forwarding

 

Redirection:

1) the address bar will change to the redirected address.

2) redirection can jump to the web, other web applications, or even out-of-site applications.

3) The caller and the called are in two different requests. Data cannot be shared through request domain objects.

 

Forwarding:

1) the address bar will not be changed.

2) forwarding cannot be forwarded to resources outside the application, nor to resources outside the site. It can only be forwarded to resources under the current web application.

3) The caller and the called are in the same request, and data can be shared through the request domain object.

 

Resource:

1) internal resources: Resources in web Applications

2) resources outside the application: resources under other web Applications

3) resources of other sites

 

 

How to load resource files for web Applications

First, let's take a look at the directory for running web applications:

 

The relative path refers to the running directory of the java command.

 

Java project: The ecplise tool sets the directory for running java commands to the root directory of the web application.

 

Web project: the directory for running java commands is in the tomcat/bin directory.

Sometimes we need a web application to load images, music, videos, etc. We need to obtain their paths and use them. You can use the following methods to obtain them:

 

Java. lang. String getRealPath (java. lang. String path) -- Obtain the absolute path of the resource.

 

Java. io. InputStream getResourceAsStream (java. lang. String path) -- get an input stream of the Resource

 

 

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.