web
过滤器
-
获取到session对象
HttpServletRequest request=(HttpServletRequest)arg0; HttpServletResponse response=(HttpServletResponse)arg1; HttpSession session=request.getSession();
-
过滤器的使用:
- 使用过滤器检测用户是否登录
- 针对所有post请求,统一解决乱码问题
-
步骤:
-
在web.xml中设置相关的配置(类似与servlet的设置)
-
创建相关的过滤器类
-
实现过滤器接口(Filter)
-
重写相关方法()
public class LoginFilter implements Filter { @Override public void destroy() { } /** * 核心过滤的方法 */ @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)throws IOException, ServletException { System.out.println("开始过滤"); //检测用户是否登录过(验证session) HttpServletRequest request=(HttpServletRequest)arg0; HttpServletResponse response=(HttpServletResponse)arg1; HttpSession session=request.getSession(); //从session中获取用户信息 User user=(User)session.getAttribute("user"); if(user!=null && user.getName()!=null) { System.out.println("开始放行"); //放行 arg2.doFilter(request, response); }else { System.out.println("拦截"); response.sendRedirect("/web10/login.jsp"); } } @Override public void init(FilterConfig arg0) throws ServletException {
}
-
}
标签:arg0,request,HttpServletResponse,过滤器,session,day50,public From: https://www.cnblogs.com/ayuuuuu/p/16901076.html