Head-first servelts&jsp Reading Note 3

Source: Internet
Author: User

<servlet>    <Servlet-name>Beerparamtests</Servlet-name>    <Servlet-class>Testinitparams</Servlet-class>     <init-param>       <Param-name>AdminEmail</Param-name>      <Param-value>[Email protected]</Param-value>    </Init-param></servlet>

The fragment in Web. Xml.

This fragment is for Testinitparams, the servlet.

Getservletconfig () has access to this servlet-related information.

Getservletconfig (). Getinitparameter ("AdminEmail");

Able to obtain the corresponding Paramvalue--[email protected]

When a container initializes a servlet, a unique corresponding ServletConfig is created.

The container will read the corresponding information from the DD and bind to the ServletConfig object.

Then, call the Servlet class's Init method and reference the ServletConfig object to the Servlet object.

Methods for ServletConfig objects:

1 string Getinitparameter (string);

2 enumeration Getinitparameternames (); An implementation class for enumeration is StringTokenizer ...

3 ServletContext getservletcontext ();

4 String getservletname (); Nearly with no use

<servlet>    <Servlet-name>Beerparamtests</Servlet-name>    <Servlet-class>Testinitparams</Servlet-class></servlet> <context-param>     <Param-name>AdminEmail</Param-name>    <Param-value>[Email protected]</Param-value></Context-param>

The fragment in Web. Xml.

ServletContext, belonging to the entire Web-app, not a servlet.

This.getservletcontext (). Getinitparameter ("AdminEmail");

This.getservletconfig (). Getservletcontext (). Getinitparameter ("AdminEmail");

BOTH RIGHT!!! If the servlet extends HttpServlet or genericservlet.

Methods for ServletContext objects:

1 string getinitparameter (String)

2 enumeration Getinitparameternames ();

3 Object getattribute (String);

4 Getattributenames ();

5 SetAttribute (String, Object);

6 removeattribute (String);

7 Getrequestdispatcher (String);

Listener

Sometimes it is necessary to do some work before one or some of the events are executed, or to do some work afterwards.

This work can be done for each servlet, but it seems cumbersome, this time can be extracted from the work, to a Java class to complete, this Java class is a listener.

Servletcontextlistener

Listener that listens for ServletContext action

 Public classSomeservletcontextlistenerImplementsServletcontextlistener { Public voidcontextinitialized (Servletcontextevent event) { ServletContext sc =   event.getservletcontext;
String some = Sc.getinitparameter ("some");
Dog dog = new Dog (some);
    Sc.setattribute ("Dog", dog); } Public voidcontextdestoryed (Servletcontextevent event) {// nothing to do here~}}

Set the listener, in Web. XML, append

< Listener >    < Listener-class >xx.xx. Someservletcontextlistener</listener-class></  Listener>

In this way, container will go to the specified location to find the listener class, and then

In the Servlet class, by

Dog dog = (dog) Getservletcontext (). getattribute ("dog");

You can get the dog object, and pay attention to forcing the type conversion.

Other types of listeners:

Servletcontextattributelistener: Used to monitor attribute changes in the ServletContext.

    1. attributeadded
    2. Attributeremoved
    3. attributereplaced

Httpsessionlistener: Used to monitor session creation and destruction, that is, how many users are using the program.

    1. sessioncreated
    2. Sessiondestroyed

Servletrequestlistener: Used to listen to the program request, in order to encapsulate the request or log information printing.

    1. Requestinitialized
    2. Requestdestroyed

Wait a minute...

Servletrequestattributelistener

Httpsessionbindinglistener

Httpsessionattributelistener

Httpsessionactivationlistener

The so-called listener, is to listen to something, such as append, delete, change, Initialize and destroy.

Types of attribute: Servletcontext,httpsession,httpservletrequest

Types of Parameter: ServletContext init parameter,request parameter,servletconfig init Parameter

Attribute can be set, such as This.getservletcontext (). SetAttribute ("Some", New Some ());

However, the parameter cannot be modified.

You can get attribute and parameter, but the return type of attribute is object, and the parameter return type is string, such as:

Object o = Request.getattribute ("Some");

String str = request.getparameter ("Some");

String str = This.getservletconfig (). Getinitparameter ("Some");

Three regions of the existence of the attribute:

Context:servletcontext, visible to all users;

Session:httpsession, only visible to the current session;

Request:servletrequest, visible only to the current request.

Object getattribute (String name)
void SetAttribute (String name, Object value)
void RemoveAttribute (String name)
Enumeration Getattributenames ()

Context Scope is not thread-safe

Because any user of application can create a new ServletContext attribute, of course, there is the right to amend and delete it.

So the attribute in the ServletContext does not guarantee its safety.

Syncronized (This.getservletcontext) can guarantee its thread safety.

HttpSession Scope is not thread-safe

Synchronized (Request.getsession ());

HttpServletRequest Scope is Thread-safe.

RequestDispatcher is available in two ways, one through request and one through ServletContext

RequestDispatcher view = Request.getrequestdispatcher ("result.jsp");

RequestDispatcher view = Getservletcontext (). Getrequestdispatcher ("/result.jsp");

Note: They are quite different!!!

Request, if the argument starts with a "/", it goes back to the root of the project to look for the page, otherwise he will go down to the relative path of the request to find the page.

ServletContext, you can only use a string that begins with "/" as a parameter!

You can then use this view.forward (request, response);

You can ' t forward the request if you ' ve already committed a response!

 Public voidDoget (HttpServletRequest request, httpservletresponse response)throwsIOException, servletexception {response.setcontenttype ("Application/jar "); ServletContext CTX=Getservletcontext (); InputStream is=Ctx.getresourceasstream ("Bookcode.jar"); intRead = 0; byte[] bytes =New byte[1024]; OutputStream OS=Response.getoutputstream ();  while(read = Is.read (bytes))! =-1) {os.write (bytes,0, read);  } Os.flush (); Cause an illegalstateexception requestdispatcher view=request.getrequestdispatcher ("result.jsp");  View.forward (request, response); Os.close ();}

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.