zoukankan      html  css  js  c++  java
  • 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中

  • 相关阅读:
    运算符优先级
    Tips—查询某结构体
    在线词典--(一、流程分析)
    数据库—SQLite3
    回调函数(转载)
    UNIX域套接字
    进程间通信小结
    HDU_oj_2027 统计元音
    HDU_oj_2026 首字母变大写
    HDU_oj_2025 查找最大字母
  • 原文地址:https://www.cnblogs.com/ll0405/p/8109134.html
Copyright © 2011-2022 走看看