事件监听器
一;监听同一个用户重复登陆
下面以一个用户登陆列;来讲解sessiong监听器的原理和用法
1, 创建一个容器来封装登陆用户的信息,代码如下:
package org.luojs.lister; import java.util.ArrayList; import java.util.List; import com.luojs.struts.form.UserForm; public class ListLister { private static List list = new ArrayList(); public ListLister(){ super(); } public List getList(){ return list; } public void addList(UserForm user){ this.list.add(user); } public void remove(int n){ list.remove(n); } /** * 判断新来的用户是否也存在,如果存在,返回ture * @param user * @return true; */ public boolean isExec(UserForm user){ boolean flag = false; for (int i = 0; i < list.size(); i++) { UserForm userForm = (UserForm)list.get(i); if(userForm.getUsername().equals(user.getUsername())){ flag = true; break; } } return flag; } }
|
2, 监听器需要实现一个接口(implements HttpSessionAttributeListener),
package org.luojs.lister;
import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent;
import com.luojs.struts.form.UserForm;
public class SessionLister implements HttpSessionAttributeListener{
/* 创建一个 ListLister 来封装登陆的用户对象 */ private static ListLister list = new ListLister(); /** * 实现attributeAdded 方法,当用户向session 中添加用户对象时,触法次方法 * 这个方法将把该用户的信息保存到 ListLister 中 */ public void attributeAdded(HttpSessionBindingEvent arg0) { System.out.println("wcome you ! add "); if(arg0.getName().equals("username")){ System.out.println("wcome you ! add sssssssssssssss"); UserForm answer = (UserForm)arg0.getValue(); list.addList(answer); } } /** * 当有用户登陆来时,判断他是否已存在,如果存在,让他出去 */ public void attributeRemoved(HttpSessionBindingEvent arg0) { System.out.println("wcome come your removed "); int n=0; UserForm p1 = (UserForm)arg0.getValue(); for(int i=0;i<list.getList().size();i++){ UserForm p2 = (UserForm)list.getList().get(i); if(p1.getUsername().equals(p2.getUsername())){ n=i; break; } } list.getList().remove(n); } public void attributeReplaced(HttpSessionBindingEvent arg0) { } } |
3, 处理用户提交时的代码:(这是在Struts 中的验证)
public ActionForward longin(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { UserForm userForm = (UserForm) form;// TODO Auto-generated method stub boolean flag = false; ListLister listuser = new ListLister(); HttpSession session = request.getSession(); String user = userForm.getUsername(); String pass = userForm.getPassword(); flag = userbiz.selectByName(user, pass); if (flag) { if (!listuser.isExec(userForm)) { session.setAttribute("username", userForm); return mapping.findForward("indexto");// 如果登陆成功,把权限转交给JobsAction } else { error = "<h3><li>Sorry! 此用户也存在,不能重复登陆 !</h3>"; } } else { error = "<h3><li> sorry ! this is your userName or passwrod error !</h3>"; } request.setAttribute("error", error); return mapping.findForward("backToIndex");// 回到登陆页 } |
3, 在web.xml中注册监听器;
<listener> <listener-class>org.luojs.lister.SessionLister</listener-class> </listener> |