Java EE--------Statistics website online number, secure login, etc. (Observer design mode)

Source: Internet
Author: User
Tags trim

The general introduction:

Listener: Listener-is a common Java program that implements the pending interface, which is specifically used to listen for method calls from another class. is to use the observer design pattern.

Little brother just contact this, did some simple introduction, the Great God please bypass, technology is only a little, convenient later encounter problems can see these can solve some problems. And I want to share with you the little examples that we've written.

Event sources in the servlet:

Event Source: HttpSession
Httpsessionlistener-
Httpsessionattributelistener
Httpsessionevent
Event Source: ServletRequest
Servletrequestlistenr
Servletrequestattributelistener
Servletrequestevent
Event Source: ServletContext
Servletcontextlistener
Servletcontextattributelistener
Servletcontextevent

use the knowledge points in our project:

Httpsessionlistener, monitor the creation and destruction of httpsession.
sessioncreated
Sessiondestroyed

The default valid time for a session is 30 points. You can modify its value in a configured way.
You can call the Session.invalidate method to destroy the current session.

The main role is to record all current online numbers, whether users or tourists. ·


The above is the knowledge that we use to do this example, the following detailed introduction:

Instance requirements:

1, use Httpsessionlistener record online number.
2. Use Httpsessionattributelistener to record the number of logins.
3, the user kicked out of the system.


One: Record the number of people online, we need to use the Httpsessionlistener observer design pattern

Each user visiting the website will have a seesion creation, so we can create the session statistics

Write a class that implements the Httpsessionlistener interface

sessioncreated functions and sessiondestroyed, we use only the Create sessioncreated

The created session is all placed in a map collection, the current platform needs to be obtained, directly from the context of the acquisition, for other operations. In fact, sessioncreated used to set lock, the API itself, to solve multithreading problems.

The public class Mysessionlistener implements Httpsessionlistener {@Override the public
	void sessioncreated ( Httpsessionevent se) {
		//We encapsulate the created session in a map
		map<string, httpsession> map = (map<string, httpsession>) se.getsession (). Getservletcontext (). getattribute ("Onlines");
		if (map==null) {//Description This is the first visit is, need to own new one object
			map=collections.synchronizedmap (new hashmap<string, HttpSession > ())//Use set lock, using Java self-locking function
			se.getsession (). Getservletcontext (). setattribute ("Onlines", map);		System.out.println ("listener added One");
		Map.put (Se.getsession (). GetId (), Se.getsession ()),//With the ID of the session as the Key,session object for value exists in the map

	@Override Public
	void sessiondestroyed (httpsessionevent se) {
	}}


Two, the foreground display page we use before and after the login, are displayed in a page, using JSTL expression to make the difference can be.

Among them, we use when the login successfully, we will use the set session directly, so that the difference can be, when we adopt a secure login is also used in this session is the existence of values.

  <body> <!--requirements: To be able to allow visitors to visit, allow login, can view current users (including visitors), information-----name,ip,createtime,lasttime,
  
	Need a permission is can kick people (make session invalidation) is to talk about the creation of the time, save a list, and then the relevant information from the session back to-->  

third, after login processing

In whether to log in, we simply simulate under the

After the success, we will set a session value to the foreground processing

<span style= "FONT-SIZE:18PX;" > Public	void DoPost (HttpServletRequest request, httpservletresponse response)
			throws Servletexception, IOException {
		///Receive parameter encoding problem has been set up by the filter
		String name=request.getparameter ("name");
		String pwd =request.getparameter ("pwd");
		
		After obtaining the parameters, start encapsulating the data
		user User =new User ();
		User.setname (name);
		User.setpwd (PWD);
		User.setadmin (true);
		After encapsulating the data, call the service layer, access the database, and simply simulate the login success if name and PWD are equal (
		name!=null &&!name.trim (). Equals ("") & & pwd!= null && pwd.trim (). Length () >0) {
			if (Name.endswith (pwd)) {//impersonation, equality is login success
				Request.getsession (). setattribute ("user", user);
			}
		Response.sendredirect (Request.getcontextpath () + "/index.jsp")//Redirect to Home page
	}</span>

Four, view online users
<span style= "FONT-SIZE:14PX;" > <body>  

To view the current number of users online, we directly collect parameters:

public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/ /Here, we need to put the information that the front desk is packaged here//from the Onlines "Sessionid,session object" to get the whole session collection, extract the information//and then encapsulate this information to the foreground display List<map<s Tring, object>> list=new arraylist<map<string,object>> ()//Using list data map<string, HttpSession
> onlines= (map<string, httpsession>) request.getsession (). Getservletcontext (). getattribute ("OnLines");
		System.out.println (Onlines);
		Iterator<map.entry<string, httpsession>> it= onlines.entryset (). iterator ();
			while (It.hasnext ()) {entry<string, httpsession> entry=it.next (); HttpSession Sess=entry.getvalue ()//Get a single Session object map<string, object> mm =new hashmap<string, object> () //The map encapsulates a row of data, and then it is placed in the list, which is the data mm.put ("id", Sess.getid ()) of a table, or the ID mm.put of the session ("Createtime", New Date (Sess.get CreationTime ())//time created. It's the date type. Our front desk is parsed and displayed Mm.put ("Lastaccessedtime", New DaTe (Sess.getlastaccessedtime ())),//Last accessed time Mm.put ("User", Sess.getattribute ("user"));
			Mm.put ("IP", sess.getattribute ("IP"));			
		The front desk needs the information to complete, the backstage uses List.add (mm);
		} request.setattribute ("list", list); Request.getrequestdispatcher ("/jsps/show.jsp"). Forward (request, response); Show page for list object Jump}

Effect Chart:

Five, the manager kicks people

This is all set to admin and can be modified inside the value object

Mainly in the click of the kick, the object ID passed over, kicking people is the user's session.invalidate, set the same user name, can not play.

When kicking, we're not just changing the session. You also need to remove the session inside the map object.

public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {P
		Rintwriter PW =response.getwriter ();
		String id=request.getparameter ("id"); String username=request.getparameter ("user");//The user map<string of the current page, httpsession> map= (map<string,
		httpsession>) Request.getservletcontext (). getattribute ("Onlines"); HttpSession se=map.get (ID);//Get Session Object User user= (user) Se.getattribute by ID ("user");
		The user object can be System.out.println by the Session object ("username www" +username);
		System.out.println ("Locally directly obtained www" +user.getname ());
				if (!user.getname (). Equals (username)) {///cannot delete the user if (Map.containskey (ID)) {System.out.println ("deleted") that has the same name as himself;
				HttpSession ss= map.get (ID);
			Map.Remove (ID);//Remove Ss.invalidate () from the context ()//Let session fail Pw.write ("successfully delete user");
			}else{pw.write ("The user has been removed");
		} request.getrequestdispatcher ("/jsps/show.jsp");
		}else{pw.write ("Users can not kick themselves"); } pw.write ("<a href="/onlineweb/iNdex.jsp ' > Return </a> '); }

six, active exit

Remove your session directly, and remove your own from the map

public void DoPost (HttpServletRequest request, httpservletresponse response)
			throws Servletexception, IOException {
		map<string, httpsession> Map = (map<string, httpsession>) Request.getservletcontext (). GetAttribute ("Onlines");
		String id=request.getsession (). GetId ();
		Map.Remove (ID);//deleted by ID, Session object Request.getsession () in the context large container
		. Invalidate ();
		Response.sendredirect (Request.getcontextpath () + "/index.jsp");
	}


Seven , secure login

We have previously written examples, as long as the correct input of the path and access to the project, we can directly access, there is no security, but now we can use

Filter to achieve this function.

We are based on the success of our login, we will set the value of the session, and then we can filter according to this, we know that the previous total station compression and filter sensitive words, etc., are required to configure the filter path, so we are in the configuration path is to need attention, The login interface and the processing of the login interface result cannot be filtered. So generally these two are directly placed in the root directory.

public class Safeloginrfilter implements Filter {
	@Override public
	void init (Filterconfig filterconfig) throws servletexception {
	}

	@Override public
	void Dofilter (ServletRequest request, servletresponse response,
			Filterchain chain) throws IOException, servletexception {httpservletrequest
		req= (httpservletrequest) request;
		HttpServletResponse resp= (httpservletresponse) response;
		if (Req.getsession (). getattribute ("user") ==null) {//This is filtered by illegal users, only logged-in users can enter the user rights
			Resp.sendredirect ( Req.getcontextpath () + "/index.jsp");
		else{
			chain.dofilter (req, resp);
		}

	@Override public
	Void Destroy () {
	}

According to this above, we can set up a number of directories to allow visitors to visit, is not through the filter page, write a separate folder can be.

The Intercept path is configured in Web.xml:

<filter-mapping>
	  	<filter-name>safeLogin</filter-name>
  		<url-pattern>/servlet/* </url-pattern>
  		<url-pattern>/jsps/*</url-pattern>
  </filter-mapping>


Summary: In the example, we just need to know, with Httpsessionlistener, we can use it to achieve how many session objects created, put him in a map container, need to take out the line, of course, there are many valuable sessions, such as ID , access time, last access time, and so on. The rest are the usual knowledge.

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.