2011-09-19 109 views
0

是否有更简洁的方法来编写此方法?也许用正则表达式?需要帮助重构此方法

/** 
* Find a parameter in the request.pathInfo. In a certain cases we 
    * will send the variables via the path. 
* 
* For example: 
* normal request parameters - /ps/cmap?t=i&n=25&xid=1 
* mapping via path would be - /ps/cmap/ti/n25?xid=1 
*/ 
private static String findParamInPath(String paramName, HttpServletRequest request){ 
     String pathInfo = request.getPathInfo(); 
     int startIndex = pathInfo.indexOf("/" + paramName); 
     if(startIndex >= 0){ 
     startIndex += (paramName.length()+1); 

     int endIndex = pathInfo.indexOf("/", startIndex); 
     if(endIndex < 0){ 
      endIndex = pathInfo.indexOf("?", startIndex); 
     } 
     if(endIndex < 0){ 
      endIndex = pathInfo.length(); 
     } 
     String value = pathInfo.substring(startIndex, endIndex); 
     if (value != null) { 
      return value; 
     } 
     } 

     return null; 
    } 
+1

首先,去掉参数HttpServletRequest,只是通过另一个字符串,你只使用了'getPathInfo'从那个对象。 –

+1

添加评论:你想要做什么? –

+0

这将有助于举几个“单元测试”数据的例子;即样本输入和预期输出。 – Bohemian

回答

1

我可以通过读取要提取参数的值,当它可以编码为一个URL PARAM或路径代码见。

下面是你如何使用正则表达式。请注意,我更改了接受String的方法(而不是HttpServletRequest),因为它更易于编码和测试。

private static String getParamValue(String paramName, String pathInfo) { 
    return pathInfo.replaceAll("^.*\\b" + paramName + "=?(.*?)(&|\\?).*$", "$1"); 
} 

下面是一些测试代码:

public static void main(String... args) throws InterruptedException { 
    System.out.println(getParamValue("n", "/ps/cmap?t=i&n=25&xid=1")); 
    System.out.println(getParamValue("n", "/ps/cmap/ti/n25?xid=1")); 
} 

,其输出:

25 
25 
+0

是的,谢谢,那就是我需要的 – Areone

0

@Bohemian,

IMO重构是不是使代码更短,但明确。也许下面的更加清晰,为读者不需要是一个正则表达式专家理解它:

private static String getParamValue(String paramName, String pathInfo) { 
this.paramName = paramName; 
this.pathInfo = pathInfo; 

    if(paramInRequest()) 
     return valueInRequestParam(); 
    if(paramInPath()) 
     return valueInPathParam(); 
} 

private boolean paramInRequest() {...} 

private boolean paramInPath() {...} 

private Strign valueInRequestParam() {...} 

private Strign valueInPathParam() {...}