servlet struts2中的拦截器 servlet的两大特性:过滤器Filter 监听器Listener

一个web.xml里面通常要配置servlet、过滤器、监听器和<context-param>等等

一个完整的Servlet包括 继承httpServlet类,web.xml中配置<Servlet>  <Servlet-mapping>,后续的过滤器、监听器也是这样遵循这样的体系设置

只用于对requset response进行修改或者对context、session、request事件进行监听

一是继承于Filter接口,二 在web.xml文件中配置<filter> <filter-mapping>,过滤器常用于日志记录、权限验证、字符编码、数据加密等

他俩与servlet没有业务耦合,不加监听过滤器,原模块也能正常工作,只是少了一些功能而已。

Listener使用实现HttpSessionListener  ServletContextListener  ServletRequestListener接口 监听 session、context、request的创建和销毁,还可以实现XXXAttributeListener  接口监听属性的变化


 下面是转载别人博客中的内容:

1、拦截器是基于java的反射机制的,而过滤器是基于函数回调 。
2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 。
3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求 起作用 。
4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能 。
5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容 器初始化时被调用一次 。

为了学习决定把两种实现方式都试一下,然后再决定使用哪个。

权限验证的Filter实现:

web.xml代码片段

  <!-- authority filter 最好加在Struts2的Filter前面-->
  <filter>
    <filter-name>SessionInvalidate</filter-name>
    <filter-class>filter.SessionCheckFilter</filter-class>
    <init-param>
      <param-name>checkSessionKey</param-name>
      <param-value>loginName</param-value>
    </init-param>
    <init-param>
      <param-name>redirectURL</param-name>
      <param-value>/entpLogin.jsp</param-value>
    </init-param>
    <init-param>
      <param-name>notCheckURLList</param-name>
      <param-value>/entpLogin.jsp,/rois/loginEntp.action,/entpRegister.jsp,/test.jsp,/rois/registerEntp.action</param-value>
    </init-param>
  </filter>
  <!--过滤/rois命名空间下所有action  -->
  <filter-mapping>
    <filter-name>SessionInvalidate</filter-name>
    <url-pattern>/rois/*</url-pattern>
  </filter-mapping>
  <!--过滤/jsp文件夹下所有jsp  -->
  <filter-mapping>
    <filter-name>SessionInvalidate</filter-name>
    <url-pattern>/jsp/*</url-pattern>
  </filter-mapping>

SessionCheckFilter.java代码

package filter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面 配置参数 checkSessionKey 需检查的在 Session 中保存的关键字
 * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath notCheckURLList
 * 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath
 */
public class SessionCheckFilter implements Filter {
  protected FilterConfig filterConfig = null;
  private String redirectURL = null;
  private Set<String> notCheckURLList = new HashSet<String>();
  private String sessionKey = null;
  @Override
  public void destroy() {
    notCheckURLList.clear();
  }
  @Override
  public void doFilter(ServletRequest servletRequest,
      ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpSession session = request.getSession();
    if (sessionKey == null) {
      filterChain.doFilter(request, response);
      return;
    }
    if ((!checkRequestURIIntNotFilterList(request))
        && session.getAttribute(sessionKey) == null) {
      response.sendRedirect(request.getContextPath() + redirectURL);
      return;
    }
    filterChain.doFilter(servletRequest, servletResponse);
  }
  private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
    String uri = request.getServletPath()
        + (request.getPathInfo() == null ? "" : request.getPathInfo());
    String temp = request.getRequestURI();
    temp = temp.substring(request.getContextPath().length() + 1);
    // System.out.println("是否包括:"+uri+";"+notCheckURLList+"=="+notCheckURLList.contains(uri));
    return notCheckURLList.contains(uri);
  }
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    redirectURL = filterConfig.getInitParameter("redirectURL");
    sessionKey = filterConfig.getInitParameter("checkSessionKey");
    String notCheckURLListStr = filterConfig
        .getInitParameter("notCheckURLList");
    if (notCheckURLListStr != null) {
      System.out.println(notCheckURLListStr);
      String[] params = notCheckURLListStr.split(",");
      for (int i = 0; i < params.length; i++) {
        notCheckURLList.add(params[i].trim());
      }
    }
  }
}

权限验证的Interceptor实现:

使用Interceptor不需要更改web.xml,只需要对struts.xml进行配置

struts.xml片段

<!-- 用户拦截器定义在该元素下 -->
    <interceptors>
      <!-- 定义了一个名为authority的拦截器 -->
      <interceptor name="authenticationInterceptor" class="interceptor.AuthInterceptor" />
      <interceptor-stack name="defualtSecurityStackWithAuthentication">
        <interceptor-ref name="defaultStack" />
        <interceptor-ref name="authenticationInterceptor" />
      </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="defualtSecurityStackWithAuthentication" />
    <!-- 全局Result -->
    <global-results>
      <result name="error">/error.jsp</result>
      <result name="login">/Login.jsp</result>
    </global-results>
    <action name="login" class="action.LoginAction">
      <param name="withoutAuthentication">true</param>
      <result name="success">/WEB-INF/jsp/welcome.jsp</result>
      <result name="input">/Login.jsp</result>
    </action>
    <action name="viewBook" class="action.ViewBookAction">
        <result name="sucess">/WEB-INF/viewBook.jsp</result>
    </action>

AuthInterceptor.java代码

package interceptor;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class AuthInterceptor extends AbstractInterceptor {
  private static final long serialVersionUID = -5114658085937727056L;
  private String sessionKey="loginName";
  private String parmKey="withoutAuthentication";
  private boolean excluded;
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    
    ActionContext ac=invocation.getInvocationContext();
    Map<?, ?> session =ac.getSession();
    String parm=(String) ac.getParameters().get(parmKey);
    
    if(parm!=null){
      excluded=parm.toUpperCase().equals("TRUE");
    }
    
    String user=(String)session.get(sessionKey);
    if(excluded || user!=null){
      return invocation.invoke();
    }
    ac.put("tip", "您还没有登录!");
    //直接返回 login 的逻辑视图  
        return Action.LOGIN; 
  }
}

使用自定义的default-interceptor的话有需要注意几点:

1.一定要引用一下Sturts2自带defaultStack。否则会用不了Struts2自带的拦截器。

2.一旦在某个包下定义了上面的默认拦截器栈,在该包下的所有 Action 都会自动增加权限检查功能。所以有可能会出现永远登录不了的情况。

解决方案:

1.像上面的代码一样,在action里面增加一个参数表明不需要验证,然后在interceptor实现类里面检查是否不需要验证

2.将那些不需要使用权限控制的 Action 定义在另一个包中,这个新的包中依然使用 Struts 2 原有的默认拦截器栈,将不会有权限控制功能。

3.Interceptor是针对action的拦截,如果知道jsp地址的话在URL栏直接输入JSP的地址,那么权限验证是没有效果滴!

解决方案:把所有page代码(jsp)放到WEB-INF下面,这个目录下的东西是“看不见”的


你可能感兴趣的:(servlet struts2中的拦截器 servlet的两大特性:过滤器Filter 监听器Listener)