0

我有 ABC.action 调用过滤器类的 doFilter 方法,该方法在 web.xml 中正确配置

我需要从请求对象中找到动作名称。我怎样才能做到这一点?

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
     throws IOException, ServletException {
  long t1 = System.nanoTime();
  filterChain.doFilter(request, response);
  long t2 = System.nanoTime();
  long time = t2 - t1;

  // Just writing statistics to servlet's log
  System.out.println("## " +
        "ArriveTime ns " + t1 + " Departtime ns " + t2 + " ServiceTime : " + time);
//      System.out.println("Time taken to process request to "
   //                                          + ((HttpServletRequest)         request).getRequestURI()
 //                                          + ": " + totalTime + " ms.");
   }
4

1 回答 1

0

试试下面的代码(在 JBOSS 中工作)。

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain fc) throws IOException, ServletException {
        System.out.println("Request");
        System.out.println(req);
        // req instance of HttpServletRequest
        if (req instanceof HttpServletRequest) {

            HttpServletRequest httpReq = (HttpServletRequest) req;
            System.out.println(httpReq.getRequestURI());
        } else {
            // req is not instance of HTTPServletRequest then try reflection
            try {
                Class clazz = Class
                        .forName("org.apache.catalina.connector.RequestFacade");
                Method method = clazz.getMethod("getContextPath", new Class[0]);
                String actionName = (String) method.invoke(req, new Object[0]);
                System.out.println(actionName);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
于 2013-01-31T12:31:50.163 回答