有没有更简洁的方法来写这个方法?也许用正则表达式?
/**
* 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/