Java Web (ix)--Listener & Filter

Source: Internet
Author: User
Tags java web

Listener  & FilterListener Listener 1, what can I do? Monitor the occurrence of an event. Change of state. 2, the listener's internal mechanism is actually the interface callback.  Interface callback 1, requirements: A in the execution loop, when the loop to 5, notify B. First, pass an object to a, and when a executes to 5, the method in B is invoked by this object. Note, however, that instead of passing an instance of B directly, you pass an instance of an interface past.

A total of 8 web listeners are divided into three types 1, define a class, implement Interface 2, register |  Configure listeners to listen on three scopes Create and destroy request  ---httpservletrequest session  ---httpSession aapplication  ---ServletContext 1, Servletcontextlistener①servletcontext creation: ②servletcontext destroy when starting the server: Shut down the server.        Remove Project 2 from the server, Servletrequestlistener①request create: Access to any resource on the server will be requested. Access to HTML: The JSP will be accessed: The servlet will be accessed: it will be ②request destroyed: The server has responded to this request.
             Public classMyrequestlistenerImplementsServletrequestlistener {@Override Public voidrequestdestroyed (servletrequestevent SRE) {System.out.println ("ServletRequest destroyed."); } @Override Public voidrequestinitialized (servletrequestevent SRE) {System.out.println ("ServletRequest initialized."); }                }                            <listener> <listener-class>com.itheima.listener.myrequestlistener</listener-class> </listener>

3. Httpsessionlistenersession creation as long as call getsessionhtml: No JSP: Will GetSession (); servlet: Session destruction timeout 30 minutes abnormal shutdown destroy normal shutdown server ( Serialized) public class Mysessionlistener implements Httpsessionlistener {@Overridepublic void sessioncreated ( Httpsessionevent se) {System.out.println ("created session");} @Overridepublic void sessiondestroyed (httpsessionevent se) {System.out.println ("destroy Session");}} Role: Servletcontextlistener uses it to, at the time of creation of ServletContext, 1. Complete the initialization work you want 2. Perform a custom task schedule. Perform a task. Timer Httpsessionlistener Statistics Online number of people. Monitoring three scope property state changes can listen in scope value Added | Replace | The action to remove. * ServletContext---servletcontextattributelistener! [Icon] (img/img03.png) * Request---servletrequestattributelistener! [Icon] (img/img04.png) * Session---httpsessionattributelistener! [Icon] (img/img02.png) Monitor the status change of the httpsession stored in this type of listener is not registered. * Httpsessionbindinglistener> Listener object with session binding and Unbind action 1. Let JavaBean implement the interface to @overridepublic void Valuebound (Httpsessionbindingevent event) {System.out.println ("object is bound in");} @Overridepublic void Valueunbound (HttpsessionbinDingevent event) {System.out.println ("object is Unbound");} * Httpsessionactivationlistener> is used to monitor whether the value of the session now is passivated (serialized) or activated (deserialized) action * passivation (serialization) > Storing in-memory data on the hard disk * activation (deserialization) > Reads the data from the hard drive into memory. * The purpose of the session Passivation activation > Session value may be many, and we have a long period of time not to use this memory value, then you can consider the value of the session can be stored on the hard disk "passivation", and so on the next time in use, extracted from the hard disk. "Activation" * How to let the session in a certain period of time passivation. > configuration can be 1. Within Tomcat inside the Conf/context.xml is configured for all the projects that run on this server in effect 2.  The Conf/catalina/localhost/context.xml configuration is in effect for localhost. localhost:80803. The Meta-inf/context.xml in your own Web project is only valid for the current project. Maxidleswap:1 minutes do not have to passivation directory: the location of the directory where the file after passivation is stored. D:\tomcat\apache-tomcat-7.0.52\work\catalina\localhost\listenerdemo\itheima<context><manager ClassName = "Org.apache.catalina.session.PersistentManager" maxidleswap= "1" ><store classname= " Org.apache.catalina.session.FileStore "directory=" Itheima "/></manager></context># #Filter > Filters, In fact, it is the request from the client to filter.  The browser issues, and the server sends the servlet to handle it. In the middle can be filtered, in fact, the filter plays the role of interception. * Function 1. Filter some sensitive words by 2. Unified Setup Encoding 3. Automatic login ... # # #如何使用Filter1. AvailabilityA class that implements Filterpublic class Filterdemo implements Filter {public void Destroy () {}public void DoFilter (ServletRequest reque St, servletresponse Response, Filterchain chain) throws IOException, servletexception {System.out.println ("came to the filter ... "); Chain.dofilter (request, response);} public void init (Filterconfig fconfig) throws Servletexception {}}2.  Register filter > Register in Web. XML, the same technique as the servlet. <filter> <display-name>FilterDemo</display-name> <filter-name>filterdemo</filter-name > <filter-class>com.itheima.filter.FilterDemo</filter-class> </filter> <filter-mapping > <filter-name>FilterDemo</filter-name> <url-pattern>/*</url-pattern> </ filter-mapping>## #Filter的生命周期 * created > created when the server is started. * Destroy > When server is stopped. # # #Filter执行顺序1. The client makes a request, passes through the filter first, and if the filter is released, it can go to Servlet2. If there are multiple filters, they are queued in the order of registration mappings. As long as there is a filter, do not release, then the queue behind the filter and our servlet will not receive the request. # #Filter细节: 1. The Init method's parameter, Filterconfig, can be used to get the filter's name in the register and initialize the parameters. In fact, the design of the original intention and ServletConfig is the same. 2. If you want to release, then operate in the DoFilter method, using the parameter Chainchain.dofilter (request, response); Release to allow the request to reach the next target. 3. <url-pattern>/*</url-pattern> format is the same as a servlet. 1. Full path match to/start/loginservlet2. Match with directory to/start with * End/demo01/* 3. After the prefix match with * begins after the prefix name ends *.jsp *.html *.do 4. Set request for dispatcher: As long as requests come in, all intercept, the default is request FORWARD: As long as the forwarding is intercepted. Error: Page error occurs when jump include: contains the page when it is intercepted. # # #自动登录 * Demand Analysis! [Icon] (img/img05.png) # # # #1. Build the Environment 1. Build Database 2. Build Page # # #登录servlet代码protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {try {String userName = Request.getparameter ("UserName"); String Password = request.getparameter ("password"); String autologin = Request.getparameter ("Auto_login"); UserBean user = new UserBean (); User.setusername (userName); User.setpassword (password); Userdao dao = new Userdaoimpl (); UserBean UserBean = dao.login (user); if (UserBean! = null) {//succeeded, go to Home request.getsession (). SetAttribute ("UserBean", UserBean); response.Sendredirect ("index.jsp");} else{//unsuccessful ... request.getrequestdispatcher ("login.jsp"). Forward (request, response);}} catch (SQLException e) {e.printstacktrace ();}} # #过滤器代码 > The core of the filter is not to complete the interception or release display. Its core is to help the user to complete the login function before releasing. * Realization Idea 1. First to determine whether the session is valid, if effective, you do not have to take a cookie, direct release. 2. If the session fails, then take a cookie. 1. No cookie Release 2. There is a cookie 1. Take out the value of the cookie and complete login 2. Store the user's value in session 3. Release. /** * @see filter#dofilter (servletrequest, Servletresponse, filterchain) */public void DoFilter (ServletRequest req, Servletresponse response, Filterchain chain) throws IOException, Servletexception {try {httpservletrequest request = (Htt Pservletrequest) req;//First Judge, now the session there is no that userbean.userbean UserBean = (UserBean) request.getsession (). GetAttribute ("UserBean");//Also, effective. if (UserBean! = null) {Chain.dofilter (request, response);} The ELSE{//representative session failed. 2. Look at the cookie. 1. To request, first remove the cookie from the request, but the cookie has a lot of key-valuecookie[] cookies = request.getcookies ();//2. Find the Cookiecookie cookie we used to send to the browser from a bunch of cookies = Cookieutil.findcookie (COOKies, "Auto_login");//First time to if (cookie = = null) {Chain.dofilter (request, response);} else{//is not the first time. String value = Cookie.getvalue (); String username = value.split ("#itheima #") [0]; String Password = value.split ("#itheima #") [1];//complete login UserBean user = new UserBean (); User.setusername (username); User.setpassword (password); Userdao dao = new Userdaoimpl (); UserBean = dao.login (user);//Use the session to save this value to the domain, so that you can use it before the next time it expires. Request.getsession (). SetAttribute ("UserBean", UserBean); Chain.dofilter (request, Response);}} catch (Exception e) {e.printstacktrace (); Chain.dofilter (req, response);}} # # #BeanUtils的使用 > Beanutils.populate (bean, map);//Register your own date converter convertutils.register (new Mydateconverter (), Date.class);//conversion data Map map = Request.getparametermap ();  UserBean bean = new UserBean (); Convert the data in the map into the Bean object Beanutils.populate (bean, map); #总结 # #Listener8个 three types Create and destroy for three scopes change the value of the three scopes "add | Replace | Remove "passivation activation for values in session", "Bind Unbind" passivation (serialized) in-memory object storage to hard disk timeout invalidation. The session was destroyed. Non-normal shutdown server, passivation. Normal shutdown server destruction set the session, how long. Context.xml Live(deserialization) reads from the hard disk into memory Servletcontextlistner: When the application is deployed, the server loads the project, doing some initialization work, task scheduling. Httpsessionlistener: Statistics Online number httpsessionactivationlistener: passivation activation Processing # #Filter > use more frequently * if you want to write a filter. > 1. Define a class that implements interface Filter> 2. Registered. Xml. Similar to Servlets. * Filter release. > chain.dofilter (Request, response); * Filter life cycle creation: When the server loads this project, it creates an instance destruction: When the server is shut down or the project is removed from the server.

Java Web (ix)--Listener & Filter

Related Article

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.