Listener (22 web basic learning notes) and listener learning notes

Source: Internet
Author: User

Listener (22 web basic learning notes) and listener learning notes
1. Listener

A listener is an object that is used to listen for and process events or state changes on other objects. When the Monitored Objects occur, they take corresponding actions immediately. The listener is actually a common java program that implements a specific interface. This program is used to listen for method calls or attribute changes of another java object. After the above events occur on the Monitored object, the listener immediately executes a method.

2. collect statistics on the number of online listeners-HttpSessionListener implementation
package com.pb.news.listenter;public class OnlineCounter {    public static long ONLINE_USER_COUNT=0;    public static long getonline(){        return ONLINE_USER_COUNT;    }    public static void raise() {        ONLINE_USER_COUNT++;    }    public static void reduce() {        ONLINE_USER_COUNT--;    }}
Package com. pb. news. listenter; import javax. servlet. http. httpSessionEvent; import javax. servlet. http. httpSessionListener;/*** Application Lifecycle Listener implementation class OnlineCounterListener **/public class OnlineCounterListener implements HttpSessionListener {/*** @ see HttpSessionListener # sessionCreated (HttpSessionEvent) */public void sessionCreated (HttpSessionEvent arg0) {// TODO Auto-generated method stub // The user adds 1 OnlineCounter to the session creation. raise ();}/*** @ see HttpSessionListener # sessionDestroyed (HttpSessionEvent) */public void sessionDestroyed (HttpSessionEvent arg0) {// Delete the OnlineCounter in the session. reduce ();}}

You only need to write

Online users: <% = OnlineCounter. getonline () %>
3. collect statistics on the number of online users-HttpSessionBindingListener

Create static variable class

Package com. pb. news. constants; public class Constants {// The static constant used to count the number of online users. public static int ONLINE_USER_COUNT = 0 ;}

Create a user class to implement-interface-HttpSessionBindingListener

Package com. pb. news. listenter; import javax. servlet. http. httpSessionBindingEvent; import javax. servlet. http. httpSessionBindingListener; import com. pb. news. constants. constants;/*** Application Lifecycle Listener implementation class UserLoginCount **/public class UserLoginCount implements HttpSessionBindingListener {private int id; // user id; private String username; // user name private String password; // User password private String email; // user email private int usertype; // user type // getter and setter Methods public int getId () {return id;} public void setId (int id) {this. id = id;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} public int getUsertype () {return usertype;} public void setUsertype (int usertype) {this. usertype = usertype;}/*** Default constructor. */public UserLoginCount () {// TODO Auto-generated constructor stub}/*** @ see role # valueBound (HttpSessionBindingEvent) */public void valueBound (HttpSessionBindingEvent arg0) {Constants. ONLINE_USER_COUNT ++;}/*** @ see HttpSessionBindingListener # valueUnbound (HttpSessionBindingEvent) */public void valueUnbound (HttpSessionBindingEvent arg0) {Constants. ONLINE_USER_COUNT --;}}

Create a login servlet class

Package com. pb. news. web. servlet; 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; import javax. servlet. http. httpSession; import com. pb. news. dao. impl. usersDaoImpl; import com. pb. news. entity. users; import com. pb. news. listenter. userLoginCount; import com. pb. news. service. impl. usersServiceImpl;/*** Servlet implementation class UserLoginServlet */public class UserLoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @ see HttpServlet # HttpServlet () */public UserLoginServlet () {super (); // TODO Auto-generated constructor stub}/*** @ see HttpServlet # doGet (HttpServletRequest request, HttpServletResponse response) */protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}/*** @ see HttpServlet # doPost (HttpServletRequest request, httpServletResponse response) */protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// request. setCharacterEncoding ("UTF-8"); String username = request. getParameter ("username"); String password = request. getParameter ("password"); UsersServiceImpl usersService = new UsersServiceImpl (); UsersDaoImpl usersDao = new UsersDaoImpl (); usersService. setUsersDao (usersDao); boolean flag = usersService. login (username, password); if (flag = true) {// request. getSession (). setAttribute ("user", username); // create an HttpSessio object/* Users users = new Users (); users. setUsername (username); users. setPassword (password); */UserLoginCount users = new UserLoginCount (); users. setUsername (username); users. setPassword (password); HttpSession s = request. getSession (); s. setAttribute ("user", users); // s. setAttribute ("pwd", password); // request. getRequestDispatcher ("jsp/index. jsp "). forward (request, response); response. sendRedirect ("jsp/index. jsp ");} else {request. setAttribute ("msg", "incorrect user name or password"); RequestDispatcher rd = request. getRequestDispatcher ("jsp/userLogin. jsp "); rd. forward (request, response); // request. getRequestDispatcher ("jsp/userLogin. jsp "). forward (request, response); // response. sendRedirect ("jsp/userLogin. jsp ");}}}

Display on the page to display

Logged-on user: <% = com. pb. news. constants. Constants. ONLINE_USER_COUNT %>

In comparison, the first one is more concise. Here there may be some simple output, which is not found yet.

4. collect statistics on the number of online listeners-HttpSessionListener implementation
Package com. pb. news. web. servlet; import javax. servlet. http. httpSessionEvent; import javax. servlet. http. httpSessionListener; public class UserCountListener implements HttpSessionListener {private int count = 0; public void sessionCreated (HttpSessionEvent se) {// TODO Auto-generated method stub // Add 1 count ++; setContext (se);} public void sessionDestroyed (HttpSessionEvent se) {// TODO Auto-generated method stub // The number of stub minus 1 count --; setContext (se );} private void setContext (HttpSessionEvent se) {se. getSession (). getServletContext (). setAttribute ("userCount", new Integer (count ));}}
Create a UserCountListener listener. Pay attention to the web. <listener> <listener-class> com. pb. news. web. servlet. userCountListener </listener-class> </listener> after creating a listener, you can add the following statement to the page for displaying the number of people: Object userCount = session. getServletContext (). getAttribute ("userCount"); out. print (userCount. toString ());
5. No need to log on to count online users
Package com. pb. listenter; import javax. servlet. servletContext; import javax. servlet. annotation. webListener; import javax. servlet. http. httpSessionEvent; import javax. servlet. http. httpSessionListener;/*** Application Lifecycle Listener implementation class CountListenter **/@ WebListenerpublic class CountListenter implements HttpSessionListener {// private int count = 0;/*** Default constructor. */public CountListenter () {// TODO Auto-generated constructor stub}/*** create seesion + 1 */public void sessionCreated (HttpSessionEvent se) {// TODO Auto-generated method stub ServletContext context = se. getSession (). getServletContext (); Integer count = (Integer) context. getAttribute ("count"); if (count = null) {// count = new Integer (1); context. setAttribute ("count", 1);} else {count ++; context. setAttribute ("count", count) ;}/ *** times of session destruction-1 */public void sessionDestroyed (HttpSessionEvent se) {// TODO Auto-generated method stub ServletContext context = se. getSession (). getServletContext (); Integer count = (Integer) context. getAttribute ("count"); count --; context. setAttribute ("count", count );}}

Enter the following code on the page to display:

<%ServletContext context=session.getServletContext();Integer count=(Integer)context.getAttribute("count");%>  <%=count%>

 

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.