August 18, 2016 Javaweb review 12th listener

Source: Internet
Author: User

In the Web application, sometimes you want to do some tasks when the Web application starts or shuts down, or if you want to see him create and close the session, you can do it through the listener. Then the servlet to 8 monitor interface, the following one by one to explain.

1:servletcontextlistener and Servletcontextattributelistener

1.1:servletcontextlistener is mainly used for monitoring when the container is started and closed. There are 2 methods for monitoring container startup and shutdown, respectively. It's a metaphor for initializing a database connection when the container is started. Container closure can be notified to never start another container to ensure stable operation of the application

The code is as follows

 Public class Implements servletcontextlistener{    publicvoid  contextinitialized (servletcontextevent SCE {        System.out.println ("The servlet context object begins to initialize");            }      Public void contextdestroyed (Servletcontextevent sce) {        System.out.println ("The servlet context object starts destroying");}    }

Web. XML Configuration (hereinafter)

<listener>        <listener-class>com.lp.listensrs.myservletcontextlistener</listener- class> </listener>

1.2:servletcontextattributelistener mainly used to listen to the context object property changes in the main there are 3 methods to listen to add properties, delete attributes, and the property is worth replacing.

 Public classMyservletcontextattributelistenerImplementsservletcontextattributelistener{ Public voidattributeadded (servletcontextattributeevent scab) {System.out.println ("The added ServletContext property is" +scab.getname ()); }     Public voidattributeremoved (servletcontextattributeevent scab) {System.out.println ("The deleted ServletContext attribute is" +scab.getname ()); }     Public voidattributereplaced (servletcontextattributeevent scab) {System.out.println ("Attribute values are substituted"); }}

Then we add the JSP file

       Application.setattribute ("Sqlname", "admin");        Application.setattribute ("Sqlname", "Replaceadmin");        Application.removeattribute ("Sqlname");

Run can see the result as

2:servletrequestlistener and Servletrequestattributelistener

2.1:servletrequestlistener is primarily used to listen for HttpRequest object requests and responses. This listener allows you to listen to the number of each HTTP request in the application. The code is as follows

 Public class Implements servletrequestlistener{    publicvoid  requestdestroyed (servletrequestevent SRE) {        System.out.println ("Response to request");    }      Public void requestinitialized (servletrequestevent SRE) {        httpservletrequest request=(httpservletrequest ) sre.getservletrequest ();        String URL=request.getrequesturl (). toString ();        System.out.println ("Receive request" +URL);}    }

And then we can see the results.

2.1:servletrequestattributelistener This is the listener request property changes and servletcontent are basically the same. The code is as follows

 Public classMyservletrequestattributelistenerImplementsservletrequestattributelistener{ Public voidattributeadded (servletrequestattributeevent srae) {System.out.println ("Added properties:" +srae.getname ()); }     Public voidattributeremoved (servletrequestattributeevent srae) {System.out.println ("Deleted properties:" +srae.getname ()); }     Public voidattributereplaced (servletrequestattributeevent srae) {String str=Messageformat.format ("The attribute was replaced in the ServletRequest domain object: value of {0}", Srae.getname ());    System.out.println (str); }}
3:httpsessionlistener, Httpsessionattributelistener, Httpsessionbindinglistener

The main purpose of 3.1:httpsessionlistener is to monitor session creation and consumption. Here's just a simple example.

 public  class  Myhttpsessionlistener implements   httpsessionlistener{ public  void   sessioncreated (httpsessionevent se) {System.out.println ( "session created, S                    The ID of the ession is "+se.getsession (). GetId ());  public  void   sessiondestroyed (httpsessionevent se) {System.out.println ( "session destroyed" 

3.2:httpsessionattributelistener, Httpsessionbindinglistener These two I focus on, the former is mainly to listen to the entire application session property changes, and the latter is mainly its own properties to achieve, So that the property knows when he was added to a session, or the attribute was deleted from the session, (Httpsessionbindinglistener does not need to be configured in XML) now to demonstrate this httpsessionbindinglistener.

Now let's do a simple online demographic.

First do a userlist to store the number of people on the line, using a singleton mode, while using vectors to avoid thread safety issues. The code is as follows

 Public classuserlist {Private Static FinalUserList userlist=Newuserlist (); PrivateVector<string>Vector;  Publicuserlist () {vector=NewVector<string>(); }     Public Staticuserlist getinstance () {returnuserlist; }     Public voidAddUser (String name) {if(name!=NULL&&name!= "") {vector.addelement (name); }    }     Public voidRemoveuser (String name) {if(name!=NULL&name!= "") {vector.remove (name); }    }     PublicEnumeration<string>getuserlist () {returnvector.elements (); }     Public intGetusercount () {returnvector.size (); }}

The Userbean method is then called when a userbean is defined to implement Httpsessionbindinglistener to invoke the Valuebound method to delete the Valueunbound object when the Userbean object joins the session. 。

 Public classUserBeanImplementshttpsessionbindinglistener{PrivateString UserName; PrivateUserList ul=userlist.getinstance ();  PublicUserBean () {};  PublicUserBean (String name) { This. username=name; }     Public voidValuebound (Httpsessionbindingevent event) {Ul.adduser (userName); System.out.println ("called"); }     Public voidValueunbound (Httpsessionbindingevent event) {Ul.removeuser (userName); System.out.println ("Remove is called"); }     PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }}

Then we're going to define a servlet for the user to log in and add the Userbean object to the session as follows

 Public classOnlineuserservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L;  PublicOnlineuserservlet () {Super(); }    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {request.setcharacterencoding ("Utf-8"); String UserName=request.getparameter ("UserName"); String pwd=request.getparameter ("Password"); if(username==NULL|| username== "" | | pwd==NULL|| pwd== "") {Response.sendredirect ("Login.html"); return; } HttpSession Session=request.getsession (); UserBean UserBean= (UserBean) session.getattribute ("User"); UserList ul=userlist.getinstance (); if(userbean==NULL||!username.equals (Userbean.getusername ())) {UserBean=NewUserBean (userName); Session.setattribute ("User", UserBean);} response.setcontenttype ("text/html;charset=gb2312"); PrintWriter out=Response.getwriter (); Out.println ("Welcome user <b>" +username+ "</b> Login"); Out.println ("<br> Current Online user list </br>"); Enumeration<String> enums=ul.getuserlist (); intI=0;  while(Enums.hasmoreelements ()) {out.println (enums.nextelement ()); Out.println ("&nbsp;&nbsp;&nbsp;"); if(i++==10) {out.println ("<br>"); }} out.println ("<br> Current number of people online:" +i); Out.println ("<p><a href= ' logout ' > Exit login </>");    Out.close (); }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }

Then write a servlet exit and remove the Userbean from the session

 Public classLogoutservletextendshttpservlet{Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("text/html;charset=gb2312"); HttpSession Session=request.getsession (); UserBean UserBean= (UserBean) session.getattribute ("User"); Session.removeattribute ("User");PrintWriter out=Response.getwriter (); Out.println ("); Out.println (Userbean.getusername ()+ "You have logged out"); Out.println ("<a href= ' index.html ' > re-login </a>"); Out.println ("</body>);    Out.close (); }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

Finally write a index.html login page

<form action= "Online" method= "post" >        <table>            <tr>                <td> user name: <input type= " Text "Name=" UserName "/></td>                <td> Password: <input type=" password "name=" password "/></td>                <td><input type= "Submit" value= "Submission"/></td>            </tr>        </table></form >

Sign up for a wedding with Firefox first

Then I'm using Google Chrome to sign in

August 18, 2016 Javaweb review 12th listener

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.