从Servlet请求中获取操作名称

时间:2013-01-31 07:12:29

标签: servlets servlet-filters web.xml

我有ABC.action,它调用在web.xml中正确配置的Filter类的doFilter方法

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

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.");
   }

1 个答案:

答案 0 :(得分: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();
            }

        }

    }