后端过滤器的实现,

javaEE过滤器的实现分为两步走

1.(1).在相应的类中也就是你的过滤器类中拱写相应的代码,

注意:,这个类要继承Filter这个接口,

主要的代码是在dofilter这个方法中实现的,,大致思路是这样的,从session中取出用户的登录对象

然后进行判断如果这个对象不为空,就让他继续进行访问这个项目,如果为空就强制让他转到登录界面,提示他登录失效等等, 



@Override
public void init(FilterConfig filterConfig) throws ServletException {
config=filterConfig;
}


@Override  
public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
  // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpSession session = servletRequest.getSession();
TbUser admin=(TbUser)session.getAttribute("admin");
        if(admin != null) {
            chain.doFilter(request, response);
        }else {
        // 当用户为登录或登录超时时提醒并跳转到登录界面
        String returnUrl = servletRequest.getContextPath() + "/login";
response.getWriter().println("<script language=\"javascript\">" + "alert(\"登录失效!请重新登录\");"
+ "if(window.opener==null){window.top.location.href=\"" + returnUrl
+ "\";}else{window.opener.top.location.href=\"" + returnUrl + "\";window.close();}</script>");
return;
        }

}


@Override
public void destroy() {
this.config = null;
}

2.在你的web.xml中配置你的过滤路径,注意这时的过滤的就是你要访问的网址的路径,

<!-- 配置管理员登陆过滤器 -->
<filter>
        <filter-name>AdminFilter</filter-name>
        <filter-class>com.torrow.school.filter.AdminFilter</filter-class>
    </filter>


    <filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/link/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/category/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/general/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/message/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/others/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/news/*</url-pattern>
</filter-mapping>

<filter-mapping>
        <filter-name>AdminFilter</filter-name>
        <url-pattern>/user/*</url-pattern>
</filter-mapping>

上一篇:break 和 continue 和 return在if语句和for循环中的区别


下一篇:个人对于冒泡排序和选择排序的理解