Experience 5--servletcontext and some details

Source: Internet
Author: User
Tags tomcat server

1. Learning Java has object-oriented thinking, get an object do not deliberately to think about what the object of the method, what is the role. And to use the idea of object-oriented thinking, and then want to change the object of what method. For example: To get a student object, you will think of the object has a learning method; Get a Dog object, you will think of the object has bitten people, the bones of the method, get a Web object, you should think of a method of data sharing, ServletContext on behalf of a Web application.

2. There are four domains in Java, and domain is the meaning of scope. These four domains are: request, session, page, context. The scope of the context domain object is the scope of the entire application, as long as the application does not exit, anyone can access.

3.ServletContext

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

A reference to the ServletContext object is maintained in the ServletConfig object, and developers can write the servlet by Servletconfig.getservletcontex The T method obtains the ServletContext object.

You can also use the This.getservletcontext method

Example:

//Get ServletContext in two ways:

Method One: Obtain by ServletConfig

ServletContext SC1 = this. Getservletconfig (). Getservletcontext ();

Method Two: Get directly through the servlet class

ServletContext SC2 = this. Getservletcontext ();

• Because all the servlet in a Web application shares the same ServletContext object, the Servlet object can communicate through the ServletContext object. Multiple servlet implementations of data sharing through ServletContext objects.

ServletContext objects are also commonly referred to as context domain objects. (Request,session,page)

SetAttribute (), getattribute ();

Example:

/*

ServletContext Domain:

This is a container

Servetcontext field This statement describes the scope of the container, which is the scope of the application

Implementation of CONTEXTDEMO2 and CONTEXTDEMO3 data sharing through ServletContext

*/

Contextdemo2.java

Package com.context;

Import java.io.IOException;

Import javax.servlet.ServletException;

Import Javax.servlet.http.HttpServlet;

Import Javax.servlet.http.HttpServletRequest;

Importjavax.servlet.http.HttpServletResponse;

public class ContextDemo2 extends httpservlet{

Publicvoid doget (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

StringData = "AAAA";

This.getservletcontext (). setattribute ("Data", data);

}

Publicvoid DoPost (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Doget (Request,response);

}

}

Contextdemo3.java

Package com.context;

Import java.io.IOException;

Import javax.servlet.ServletException;

Import Javax.servlet.http.HttpServlet;

Import Javax.servlet.http.HttpServletRequest;

Importjavax.servlet.http.HttpServletResponse;

public class ContextDemo3 extends httpservlet{

Publicvoid doget (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

System.out.println (This.getservletcontext (). getattribute ("Data"));

}

Publicvoid DoPost (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Doget (Request,response);

}

}

4.ServletContext Application

Gets the initialization parameters for the Web application.

<context-param>

<param-name>data</param-name>

<param-value>xxxx</param-value>

</context-param>

Example:

configuration information in Web.xml:

<context-param>

<param-name>data1</param-name>

<param-value>zzzz</param-value>

</context-param>

<context-param>

<param-name>data2</param-name>

<param-value>xxxxx</param-value>

</context-param>

<context-param>

<param-name>data3</param-name>

<param-value>qqqqq</param-value>

</context-param>

Contextdemo4.java

Package com.context;

Import java.io.IOException;

Import java.util.Enumeration;

Import javax.servlet.ServletException;

Import Javax.servlet.http.HttpServlet;

Import Javax.servlet.http.HttpServletRequest;

Importjavax.servlet.http.HttpServletResponse;

Get initialization parameters for Web applications

public class ContextDemo4 extends httpservlet{

Publicvoid doget (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Output an initialization information

System.out.println (This.getservletcontext (). Getinitparameter ("data1"));

Output more than one initialization information

Enumerationen = This.getservletcontext (). Getinitparameternames ();

while (En.hasmoreelements ()) {

Stringname = (String) en.nextelement ();

StringValue = This.getservletconfig (). Getservletcontext (). Getinitparameter (name);

This is a bit different from the previous one, where you get the context object to get the Initparameter method.

System.out.println (name+ "---" +value);

}

}

Publicvoid DoPost (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Doget (Request,response);

}

}

implementation of the servlet forwarding .

Forwarding is you borrow money from me, I did not I borrow for you to others. REDIRECT You borrowed money from me I didn't, I let you borrow from others.

If you use an HTML settings file, but do not use forwarding, how can this happen: Response.getoutputstream (). Write (("<font color= ' Red ' >" +value+ "</font > "). getBytes ());

RequestDispatcher Rd =getservletcontext (). Getrequestdispatcher ("/1.jsp");

Rd.forward (Request,response);

JSP is an HTML that can write Java code.

How to upload data to 1.jsp. (You can pass the request field, you cannot use the context field)

Example:

code in LSP:

<font color= "Blue" >

<%

String data = (string) application.getattribute ("Data");

Out.write (data);

%>

</font>

Contextdemo5.java

Package com.context;

Import java.io.IOException;

Import Javax.servlet.RequestDispatcher;

Import javax.servlet.ServletException;

Import Javax.servlet.http.HttpServlet;

Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Forward by Sevletcondext implementation

public class ContextDemo5 extends httpservlet{

Publicvoid doget (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

StringData = "Dhflk";

This.getservletcontext (). setattribute ("Data", data);

Bring the data to index.jsp.

REQUESTDISPATCHERRD = This.getservletcontext (). Getrequestdispatcher ("/1.jsp");

Rd.forward (Request,response);

}

Publicvoid DoPost (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Doget (Request,response);

}

}

read resource files using the ServletContext object .

There are probably two types of configuration files used in software development : XML and properties. The difference between the two profiles is that the data in the XML file is related, and the latter does not.

– Get File path

– Three ways to read a resource file

. properties file (property file)

Example:

package Com.context;

import Java.io.FileInputStream;

import java.io.IOException;

import Java.io.InputStream;

import java.util.Properties;

import javax.servlet.ServletException;

import Javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

Publicclass ContextDemo6 extends httpservlet {

publicvoid doget (httpservletrequest request, Httpservletresponseresponse)

throws Servletexception, IOException {

Test5 ();

}

Under normal circumstances, that is, the db.properties under the SRC path

publicvoid test1 () throws IOException {

InputStream in = this. Getservletcontext (). getResourceAsStream ("/web-inf/classes/db.properties");

Properties Pro = New properties ();

Pro.load (in);

String Driver = pro.getproperty ("Driver");

String url = pro.getproperty ("url");

String username = pro.getproperty ("username");

String Password = pro.getproperty ("password");

SYSTEM.OUT.PRINTLN (driver);

System.out.println (URL);

SYSTEM.OUT.PRINTLN (username);

SYSTEM.OUT.PRINTLN (password);

}

The situation of db.properties under the package road

publicvoid test2 () throws IOException {

InputStream in = this. Getservletcontext (). getResourceAsStream ("/web-inf/classes/com/context/ Db.properties ");

Properties Pro = New properties ();

Pro.load (in);

String Driver = pro.getproperty ("Driver");

String url = pro.getproperty ("url");

String username = pro.getproperty ("username");

String Password = pro.getproperty ("password");

SYSTEM.OUT.PRINTLN (driver);

System.out.println (URL);

SYSTEM.OUT.PRINTLN (username);

SYSTEM.OUT.PRINTLN (password);

}

Db.properties in the directory, that is, webroot or above can be written in this case

publicvoid test3 () throws IOException {

InputStream in = this. Getservletcontext (). getResourceAsStream ("/db.properties");

Properties Pro = New properties ();

Pro.load (in);

String Driver = pro.getproperty ("Driver");

String url = pro.getproperty ("url");

String username = pro.getproperty ("username");

String Password = pro.getproperty ("password");

SYSTEM.OUT.PRINTLN (driver);

System.out.println (URL);

SYSTEM.OUT.PRINTLN (username);

SYSTEM.OUT.PRINTLN (password);

}

Two errors: The system could not find the specified path, server-side error, the specified file could not be found

publicvoid test4 () throws IOException {

FileInputStream in = new fileinputstream ("src/db.properties");

/* Change to this is not correct: fileinputstream in = Newfileinputstream ("classes/db.properties");

Although this directory is under the Web project. This line of code is invoked by the Tomcat server, the server is invoked by the JDK, and the relative path is relative to the Java Virtual Machine directory, and the Java Virtual machine is started when the Tomcat server is started.

So the relative path is the Tomcat server's

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.