<!--配置监听器-->
<listener>
<listener-class>util.SessionListener</listener-class>
</listener>
<listener>
<listener-class>util.AttributeListener</listener-class>
</listener>
Filter
package util;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化LoginFilter");
}
@Override //请求和响应时都会执行这个方法
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//处理乱码
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
request.setCharacterEncoding("utf-8");
//防止用户在未登录的情况下访问资源
String requestURI = request.getRequestURI();//获得请求地址
Object username = request.getSession().getAttribute("username");
if(requestURI.endsWith("success.jsp") && username == null){
response.sendRedirect("index.jsp");
}
//调取下一个过滤器,或者调取servlet
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("销毁filter");
}
}
SessionListener
package util;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class SessionListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("session存值, "+httpSessionBindingEvent.getName()+","
+httpSessionBindingEvent.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("session删除, "+httpSessionBindingEvent.getName()+","
+httpSessionBindingEvent.getValue());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
}
}
AttributeListener
package util;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class AttributeListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("session创建");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("session销毁");
}
}