是否有更简洁的方法来编写此方法?也许用正则表达式?
/**
* 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;
}
答案 0 :(得分:1)
我可以通过阅读你的代码来看到你想要提取参数的值,当它可以编码为url param或path时。
以下是使用正则表达式执行此操作的方法。请注意,我已经将方法更改为接受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
答案 1 :(得分: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() {...}