• Java 对全局用户是否登录验证


    在web.xml配置filter

    <!-- 登录认证过滤器 -->
    <filter>
    <filter-name>UserFilter</filter-name>
    <filter-class>com.filter.UserFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>UserFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
    <filter-mapping>
    <filter-name>UserFilter</filter-name>
    <url-pattern>*.action</url-pattern>
    </filter-mapping>

    后台class

    public class UserFilter implements Filter{
    
        @Override
        public void destroy() {
            
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            HttpServletResponse resp = (HttpServletResponse)response;
            HttpServletRequest req = (HttpServletRequest)request;
            HttpSession session = req.getSession();
            User user = (User)session.getAttribute("user");
            String uri = req.getRequestURI();
            //简单判断缓存中是否有用户
            if(user==null){//没有用户
                //判断用户是否是选择跳到登录界面
                if(uri.endsWith("login.jsp")||uri.endsWith("login.do")){
                    chain.doFilter(request, response);
                }else{
                    resp.sendRedirect(req.getContextPath()+"/login.jsp");
                }    
            }else{//有用户
                chain.doFilter(request, response);
            }
            chain.doFilter(request, response);
        }
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            
        }
    
    }

    首先要在登录时把user存到session中

  • 相关阅读:
    访问控制与封装
    构造函数
    定义抽象数据类型
    函数基础
    参数传递
    路径中 斜杠/和反斜杠 的区别
    【git】Github上面的开源代码怎么在本地编译运行
    IDEA及IDEA汉化包
    Java设计模式——工厂设计模式
    "/"程序中的服务器错误
  • 原文地址:https://www.cnblogs.com/ll0405/p/8109134.html
Copyright © 2020-2023  润新知