java - 需要帮助重构这个方法

标签 java refactoring

有没有更简洁的方法来写这个方法?也许用正则表达式?

   /**
 * 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;
    }

最佳答案

通过阅读您的代码,我可以看到您想要提取参数的值(当它可以编码为 url 参数或路径时)。

以下是使用正则表达式的方法。请注意,我已更改了接受 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

关于java - 需要帮助重构这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478256/

相关文章:

java - 如何正确使用switch语句?

java - 如何发送数组作为参数来制作向服务器请求的主体?

php - 重构 JavaScript 和 PHP 代码 [求职面试]

visual-c++ - Visual Studio : automatically update C++ cpp/header file when the other is changed?

java - 如何验证服务器是否支持 TLS 1.0 协议(protocol)?

java - 创建一副牌时出现编译错误

java.lang.IllegalStateException : android.accessibilityservice.AccessibilityService.getSystemService(AccessibilityService.java:1602)

callback - 在 Electron 版本中,如何为6.0.0版本的dialog.showMessageBox设置回调?

c++ - MFC:CFormView 派生类的 OnInitialUpdate 函数

javascript - 编程标准和重构 try/catch 语句