HttpSessionAttributeListener的用法和實(shí)例
HttpSessionAttributeListener:
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
HttpSessionAttributeListener能監(jiān)測(cè)到有人正在往HttpSession里添加屬性。你可以采取相應(yīng)的措施。
例 2.2.4.1
package com;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {
public void attributeAdded(HttpSessionBindingEvent arg0) {
System.out.println("增加了" + arg0.getName() + " " +
arg0.getValue() );
}
public void attributeRemoved(HttpSessionBindingEvent arg0) {
System.out.println("去除了" + arg0.getName() + " " +
arg0.getValue() );
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {
System.out.println("取代了" + arg0.getName() + " " +
arg0.getValue()+"現(xiàn)在的新值是"+arg0.getSession().getAttribute(arg0.getName()) );
}
}
web.xml加入下面這段話:
<listener>
<listener-class>com.MyHttpSessionAttributeListener</listener-class>
</listener>
用下面這個(gè)servlet測(cè)試:
package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("add attribute");
request.getSession().setAttribute("name", "馬克-to-win");
System.out.println("replace attribute");
request.getSession().setAttribute("name", "mark-to-win");
System.out.println("remove attribute");
request.getSession().removeAttribute("name");
}
}
運(yùn)行這個(gè)servlet以后,console里的輸出結(jié)果是:
add attribute
增加了name 馬克-to-win
replace attribute
取代了name 馬克-to-win現(xiàn)在的新值是mark-to-win
remove attribute
去除了name mark-to-win