Javaweb Learning Servlet (iv)----SERVLETCONFIG get configuration information, ServletContext applications

Source: Internet
Author: User

Statement

Welcome reprint, but please keep the original source of the article →_→

Article Source: http://www.cnblogs.com/smyhvae/p/4140877.html

Body

ServletConfig: Represents the configuration information of the current servlet in Web. XML ( not many )

    • String Getservletname ()--Gets the name of the current servlet configured in Web. xml
    • String Getinitparameter (string name)--Gets the value of the initialization parameter for the current servlet-specified name
    • Enumeration Getinitparameternames ()--Gets an enumeration of the names of all the initialization parameters of the current servlet
    • ServletContext Getservletcontext ()--Gets the ServletContext object that represents the current web App

In the servlet configuration file, you can configure some initialization parameters for the servlet using one or more <init-param> tags.

When the servlet is configured with initialization parameters, the Web container automatically encapsulates these initialization parameters into the ServletConfig object when it creates the Servlet instance object, and when invoking the Servlet's Init method, Pass the ServletConfig object to the servlet. Furthermore, the programmer can get the initialization parameter information of the current servlet through the ServletConfig object.

The advantage of this is: if the database information, encoding method and other configuration information in Web. XML, if the database user name, password changes, it is directly convenient to modify the Web. XML, to avoid the trouble of directly modifying the source code .

code example:

Create a new servlet named Servletconfigtest, and then, under the <servlet> tab in Web. XML, configure two initialization parameters for this servlet through the <init-param> tag:

    <servlet>        <servlet-name>ServletConfigTest</servlet-name>        <servlet-class> com.vae.servlet.servletconfigtest</servlet-class>        <init-param>            <param-name>name1 </param-name>            <param-value>value1</param-value>        </init-param>        < init-param>            <param-name>encode</param-name>            <param-value>utf-8</param-value >        </init-param>    </servlet>

Then get the above two parameters in the code. The code is implemented as follows:

1 package com.vae.servlet; 2 3 Import java.io.IOException; 4 Import java.util.Enumeration; 5 6 Import Javax.servlet.ServletConfig; 7 Import javax.servlet.ServletException; 8 Import Javax.servlet.http.HttpServlet; 9 Import javax.servlet.http.httpservletrequest;10 Import javax.servlet.http.httpservletresponse;11 public class Servletconfigtest extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse respons E) throws Servletexception, IOException {16servletconfig config = this.getservletconfig ();Get the ServletConfig object in the Init method 18 19//--Get the name configured in Web. XML by the current servlet (not many) String SName = Config.getservlet Name (); System.out.println ("The current servlet is configured in Web. xml:" +sname); 22 23//--Gets the initialization parameters configured in the current servlet (         Only one) is often used with a//String value = Config.getinitparameter ("name2"); +//System.out.println (value); 26 27 --Gets the initialization parameters (get all) that are configured in the current servlet, often using enumeration enumration = Config.getinitparameternames (); WH Ile (Enumration.hasmoreelements ()) {String name = (string) enumration.nextelement (); string value = C Onfig.getinitparameter (name), System.out.println (name+ ":" +value),}34}35, public void DoP         OST (HttpServletRequest request, httpservletresponse response) Notoginseng throws Servletexception, IOException {38 Doget (request, response); 39}40}

The core code is line 17th, takes the This.getservletconfig () method to the ServletConfig object in the Init method, and obtains the configuration information.

To run the program, print the spool log as follows:

Second, ServletContext: Represents the current Web application ( very Important )

When the Web container starts, it creates a corresponding ServletContext object for each Web application that represents the current web App .

A reference to the ServletContext object is maintained in the ServletConfig object, and the developer can obtain the ServletContext object by Servletconfig.getservletcontext method when writing the servlet.

Because all servlets in a web app share the same ServletContext object, communication can be achieved between servlet objects through ServletContext objects. ServletContext objects are also commonly referred to as context domain objects .

Application of ServletContext:

1. As a domain object, you can share data across your Web application.

Some concepts are involved here:

    • Domain objects: Using objects to share data within a range that can be seen
    • Scope: Share data across Web applications
    • Life cycle: The domain is generated after the server launches the Web app after the ServletContext object is created. When the web app is removed from the container or the server shuts down, the destruction domain of the Web app is destroyed.

code example:

Servlettest01.java:

1 package com.vae.servlet; 2  3 import java.io.IOException; 4  5 import javax.servlet.ServletContext; 6 import Javax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 One public class ServletTest01 extends HttpServlet {All public     VO ID doget (httpservletrequest request, httpservletresponse response)             throws Servletexception, IOException {15         ServletContext context = This.getservletcontext ();         context.setattribute ("name", "Smyhvae");     }18 19 Public     void DoPost (HttpServletRequest request, httpservletresponse response)             throws Servletexception, IOException {         doget (request, response);     }23 24}

Servlettest02.java:

1 package com.vae.servlet; 2  3 import java.io.IOException; 4  5 import javax.servlet.ServletContext; 6 import Javax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10 One public class ServletTest02 extends HttpServlet {All public     VO ID doget (httpservletrequest request, httpservletresponse response)             throws Servletexception, IOException {15         ServletContext context = This.getservletcontext ();         String myName = (string) context.getattribute ("name"),         System.out.println (myName),     }19 public     void DoPost (HttpServletRequest request, httpservletresponse response)             throws Servletexception, IOException {22< C10/>doget (request, response);     }24 25}

We add a parameter name (16 rows) to the context in ServletTest01, and then we can get this parameter in ServletTest02 (16 rows).

Common methods in the context are:

    • void SetAttribute (String,object);
    • Object getattribute (String);
    • void RemoveAttribute (String);

2. Get initialization parameters for Web applications

In the first paragraph, we configure information for a single servlet via the <init-param> tag, which is inaccessible in other servlets. But if we configure properties for the entire web app using the <context-param> tag (in parallel with the servlet tag), then all the servlets will have access to the parameters inside. For example, you can put the configuration information for the database here.

Here are some concepts not to confuse:

    • Request Parameters parameter The parameter information in the request sent---the browser.
    • Initialization parameters Initparameter ---The basic parameters that are configured for Servlets or ServletContext in Web. xml
    • Domain Properties attribute ---Key-value pairs accessed in four major scopes

code example:

In Web. XML, add the initialization parameters for the entire application: User name, password. The code location is as follows:

Then we'll get these parameters in the code. The code is as follows:

Servlettest03.java:

 1 package com.vae.servlet; 2 3 Import java.io.IOException; 4 Import java.util.Enumeration; 5 6 Import Javax.servlet.ServletContext; 7 Import javax.servlet.ServletException; 8 Import Javax.servlet.http.HttpServlet; 9 Import javax.servlet.http.httpservletrequest;10 Import javax.servlet.http.httpservletresponse;11 public class              ServletTest03 extends HttpServlet {$ public void doget (HttpServletRequest request, httpservletresponse response) 15 Throws Servletexception, IOException {ServletContext context = This.getservletcontext ();//Get context to  Elephant 1718//Gets the initialization parameter of the single context inside of string value1 = Context.getinitparameter ("username"); Lue2 = Context.getinitparameter ("password"); System.out.println (value1 + ";" + value2); System.out.pri Ntln (); 23 24//One-time access to all initialization parameters in the context enumeration enumeration = Context.getinitparameternames (); 26 while (Enumeration.hasmoreelements ()) {String name = (string) enumeration.nextelement (); Tring value = Context.getinitparameter (name), SYSTEM.OUT.PRINTLN (name + ";" + value);}32}34 public void DoPost (HttpServletRequest request, httpservletresponse response) 36 Throws Servletexception, IOException {PNS doget (request, response); 38}39 40}

The above code can see that we can get the initialization parameters through the Context.getinitparameter () method.

The results are as follows:

3. Implement the servlet forwarding

Here are some concepts to differentiate:

    • Request redirection: 302+location (two requests two responses)
    • Request Forwarding: No resource flow within the server (one response at a time to achieve resource flow)

Note: The content in the brackets above is the difference between the two. For example, if you ask me to borrow money, if it is a request for redirection, then you go to others to borrow, if the request is forwarded, then I will find someone to borrow, and then lend you.

code example:

Servlettest04.java Implement Request Forwarding:

 1 package com.vae.servlet; 2 3 import java.io.IOException; 4 5 import javax.servlet.RequestDispatcher; 6 import ja Vax.servlet.ServletException; 7 Import Javax.servlet.http.HttpServlet; 8 Import Javax.servlet.http.HttpServletRequest; 9 Import javax.servlet.http.httpservletresponse;10/**12 * ServletContext Implement Request forwarding */14 public class ServletTest04 Ext Ends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) thro WS Servletexception, IOException {RequestDispatcher dispatcher = This.getservletcontext (). GE Trequestdispatcher ("/servlet/servlettest05");//Parameter Write virtual path Dispatcher.forward (request, response); After executing this line of code, you will be skipped to ServletTest05 to execute. }23 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Ser Vletexception, IOException {doget (request, response);}28} 

With 19 lines of code to the forwarder dispatcher, the forwarder points to ServletTest05 (the parameter writes the virtual path), and once the execution of 20 lines of code, it will jump to ServletTest05 to execute.

Then the Servlettest05.java code is as follows:

1 package com.vae.servlet; 2  3 import java.io.IOException; 4  5 import javax.servlet.ServletException; 6 import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse; 9/**11  * ServletContext Implementation Request Forwarding */13 public  class ServletTest05 extends HttpServlet {+ public     void DoG ET (httpservletrequest request, httpservletresponse response)             throws Servletexception, IOException {         Response.getwriter (). Write ("10000yuan"),     }19 public     void DoPost (HttpServletRequest request, HttpServletResponse response)             throws Servletexception, IOException {doget         (request, response); 23     }24 25}

Enter the URL in the browser, the effect is as follows:

4. Load the resource file:

Let's start with a new resource file in the root directory of Webroot Config.properties, here's a question to note:

4.1 When reading a resource file in a servlet:

If a relative or absolute path is written, this path refers to the path in the directory under which the current program starts . Therefore, in a Web environment, the directory that Tomcat launches is tomcat/bin, so resources cannot be found. The effect is as follows:

If the path to the hard drive is d:\\apache-tomcat-7.0.57\\webapps\\webtest\\config.properties, you can find the resource, but as soon as you change the release environment, the hard drive path is likely to be wrong.

To solve this problem, ServletContext provides a Getrealpath method, in which a path is passed to the bottom of the method, which will stitch the path of the current Web application's hard disk in front of the incoming path . In order to get the hard disk path of the current resource, this way, even if the release environment is changed, the bottom of the method can get the correct path of the Web application and always the path of the correct resource. The code is as follows:

This.getservletcontext (). Getrealpath ("Config.properties")

code example:

Create a new file for config.properties at the root of the Webroot, with the following parameters:

Config.properties:

username=smyhvaepassword=007

Next, create a new servlet with the following code:

Servlettest06.java:

1 package com.vae.servlet; 2 3 Import Java.io.FileReader; 4 Import java.io.IOException; 5 Import java.util.Properties; 6 7 Import Javax.servlet.ServletException; 8 Import Javax.servlet.http.HttpServlet; 9 Import javax.servlet.http.httpservletrequest;10 Import javax.servlet.http.httpservletresponse;11 public class              ServletTest06 extends HttpServlet {$ public void doget (HttpServletRequest request, httpservletresponse response) 15 Throws Servletexception, IOException {Properties prop = new Properties ();//Note the package is import Java.uti L.properties;17Prop.load (New FileReader (This.getservletcontext () Getrealpath ("Config.properties" ));System.out.println (Prop.getproperty ("username")), System.out.println (Prop.getproperty ("password")) ;}23 public void DoPost (HttpServletRequest request, httpservletresponse response) throws Se Rvletexception, IOException {doget (request, response); 27}28 29}

The core code is This.getservletcontext (). Getrealpath ("Config.properties")in line 17th.

The results are as follows:

4.2 In many cases, the servlet does not handle a lot of logic, but instead calls the other Java code directly, which involves the following problem:

If you are reading a resource file in a non-servlet environment , you can read the resource by loading the file with the ClassLoader: MyService.class.getClassLoader (). GetResource (". /.. /.. /config.properties "). GetPath ()

Now what about the path in the GetResource ()? Just remember the word: where the class loader loads the class, it loads the resources from there. This is a bit of an abstraction, let's look at it in code:

Create a new servlet class:

Servlettest07.java:

1 package com.vae.servlet; 2  3 import java.io.IOException; 4  5 import javax.servlet.ServletException; 6 import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse; 9 Import com.vae.service.myservice;11 public class ServletTest07 extends HttpServlet {All public     void Doget (Ht Tpservletrequest request, HttpServletResponse response)             throws Servletexception, IOException {myservice         Service = new MyService ();         Service.method ();}19 public     void DoPost (HttpServletRequest request, HttpServletResponse response)             throws Servletexception, IOException {doget         (request, response);     }24 25}

In 16, 17 lines of code, a method in the MyService class is called. The following defines the MyService class, in which the resource file is loaded.

Myservice.java:

1 package com.vae.service; 2  3 import java.io.FileNotFoundException; 4 import java.io.FileReader; 5 import java.io.IOException; 6 import Java.ut Il. Properties; 7  8 public class MyService {9     -public void Method () throws FileNotFoundException, ioexception{11         //In the absence of Serv Letcontext environment, if you want to read the resources, you can use the class loader to load the resources of the class, you         should note that the class loader from which directory load class, from which directory load resources,         So the path here must give a path relative to the class loading directory         prop = new properties ();          Prop.load (New FileReader (MyService.class.getClassLoader () getresource ("Config.properties"). GetPath ());         System.out.println (Prop.getproperty ("username")),         System.out.println (Prop.getproperty ("Password "));     }19     20}

After the browser enters the URL, the background output is as follows:

"Pay special attention" to the path in the 15th line of code in GetResource ().

The directory from which the class loader loads the class, the directory from which the resource is loaded, so the path here must give a path to the directory loaded relative to the class

Let's take a look at the directory that this project publishes into Tomcat:

Enter the Web-inf directory, which looks like this:

The classes directory and the SRC directory of the project file are equivalent.

(1) If the Config.properties file is placed in the SRC directory, the path is: GetResource ("Config.properties")

(2) If the location of the Config.properties file is as follows:

The path is the same as the code above: GetResource ("Com/vae/servlet/config.properties")

(3) If the Config.properties file and the Myservice.java file are parallel, the path is: GetResource ("Com/vae/service/config.properties")

(4) If the location of the Config.properties file is as follows:

At this point the Config.properties file and the classes file are tied:

The path is: GetResource (". /config.properties ") Note:". /"represents the previous level of the directory.

(5) If the Config.properties file is placed in the root directory of the entire project file, it is not valid because the file is not published to Tomcat at this time.

"Engineering Documents"

Link: http://pan.baidu.com/s/1ntBPHd3 Password: 5QR2

(turn) Javaweb learning Servlet (iv)----SERVLETCONFIG get configuration information, ServletContext applications

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.