我写了个过滤器,想在doFilter里处理一些东西,然后根据判断用response跳到另一个页面,可是调用sendRedirect的时候,发生异常,怎么在doFilter里面跳到另一个页面?public class ActionFilter implements Filter { public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
chain.doFilter(request, response);
String path = req.getRequestURI();
if(isActionPage(path)) {
path = getActionPath(path);
((HttpServletResponse)response).sendRedirect(path);//跳到对应的action
}
} public void init(FilterConfig filterConfig) throws ServletException { }

/**
 * 判断该jsp页面是否是某个action的对应页
 * @param page
 * @return
 */
private boolean isActionPage(String page) {
return page.indexOf("_act") != -1;
}

/**
 * 根据规律截掉字符串变成一个action的访问地址
 * @param path
 * @return
 */
private String getActionPath(String path) {
path = path.substring(0, path.lastIndexOf("."));//去掉JSP后缀名

/*
 * 去掉jsp页面的所在目录,如该jsp页在/scss/Admin/Major/xxx.jsp
 * 则去掉/Major变成/scss/Admin/xxx
 */
String tmp = path.substring(0, path.lastIndexOf("/"));
tmp = tmp.substring(tmp.lastIndexOf("/"), tmp.length());
path = path.replace(tmp, "");
return path;
}
}

解决方案 »

  1.   

    感觉要解决这个问题就必须弄清楚FilterChain  类
      

  2.   

    过滤链的好处是,执行过程中任何时候都可以打断,只要不执行chain.doFilter()就不会再执行后面的过滤器和请求的内容。而在实际使用时,就要特别注意过滤链的执行顺序问题,
      

  3.   

    我把过滤链去掉就没有异常了,而且突然发现,我按照jsp的路经来访问action竟然也能成功,虽然不知道怎么回事,但这样反让我轻松了- -! <package name="Admin" namespace="/Admin" extends="struts-default">
         <action name="*_*_act" class="com.freedom.scss.action.{1}Action" method="{2}">
         <result name="success">/Admin/{1}/{1}_{2}_act.jsp</result>
         <result name="input">/Admin/{1}/{1}_{2}_act.jsp</result>
         </action>
        </package>public class ActionFilter implements Filter {

    public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request; String path = req.getRequestURI();

    /*
     * 判断该jsp页是否有对应的action
     */
    if(path.indexOf("_act") != -1) {
    path = path.substring(0, path.lastIndexOf("."));//去掉JSP后缀名
    ((HttpServletResponse)response).sendRedirect(path);//跳到对应的action
    }
    } public void init(FilterConfig filterConfig) throws ServletException {}
    }