How to decode path parameters in All REST WebServices calls
TL:DR
如果有多个位置需要在WebServices RESTful调用期间解码参数,则可以使用springframework中的UrlPathHelper在中央位置执行此操作
想像在一个RESTful URL中有一个参数1
,其中可能包含一些非URL友好
字符,例如正斜杠/
。您当然可以在每次调用时都去使用URLCodec()。decode(param1
。但这不但麻烦且容易出错。
借助于springframework对URL Intercepor的支持,您可以扩展UrlPathHelper并覆盖encodePathVariables,这样就可以集中在一个地方进行所有此类操作。
以下是仅供参考的kotlin
和java
示例:
Kotlin
import org.apache.commons.codec.net.URLCodec
import org.springframework.web.util.UrlPathHelper
import javax.servlet.http.HttpServletRequest
class MyPathHelper : UrlPathHelper() {
override fun decodePathVariables(request: HttpServletRequest, vars: MutableMap<String, String>): MutableMap<String, String> {
val map = super.decodePathVariables(request, vars)
map.computeIfPresent("param1") { _, v -> URLCodec().decode(v) }
return map
}
}
Java
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.net.URLCodec;
import org.springframework.web.util.UrlPathHelper;
import java.util.Map;
public class MyPathHelper extends UrlPathHelper {
@Override
public Map<String, String> decodePathVariables(javax.servlet.http.HttpServletRequest request, Map<String, String> vars) {
Map<String, String> map = super.decodePathVariables(request, vars);
map.computeIfPresent("param1", (k,v) -> {
try {
return new URLCodec().decode(v);
} catch (DecoderException e) {
e.printStackTrace();
}
return v;
});
return map;
}
}
期望这个对你有所帮助
--End--
网友评论