2014-09-29 83 views
1

我有一个spring的mvc应用程序,运行在Tomcat 7上,http和ajp连接器配置为URIEncoding =“UTF-8”。 我的REST控制器片段:Spring MVC uri映射与百分比编码字符

@Controller 
@RequestMapping("") 
public class ClientRestApi { 
    private final String API_PREFIX = "/api/1.0/client"; 
    ... 
    @RequestMapping(value = API_PREFIX + "/{clientId}", method = RequestMethod.GET) 
    @ResponseBody 
    public ClientDetails get(@PathVariable String clientId, HttpServletRequest request) { 
     log.info("Client API GET [" + clientId + "] | " + request.getRequestURI()); 
     ... 
    } 
} 
  • 当我去:http://www.example.pl/api/1.0/client/abc我得到ABC客户端页面 - 正确
  • 当我去:http://www.example.pl/%07api/1.0/client/abc我得到ABC客户端页面 - 错误
  • 当我去:http://www.example.pl/%0bapi/1.0/client/abc我得到abc客户端页面 - 错误
  • 当我去:http://www.example.pl/ap%0bi/1.0/client/abc我得到HTTP 404 - 正确

在应用程序日志中我可以看到(用于前3个请求):

ClientRestApi - Client API GET [abc] | /api/1.0/client/abc 
ClientRestApi - Client API GET [abc] | /%07api/1.0/client/abc 
ClientRestApi - Client API GET [abc] | /%0bapi/1.0/client/abc 

我的问题是为什么我的错了的例子是错的? 他们为什么不是http 404?

在应用程序的web.xml文件中,我使用了UTF-8编码的CharacterEncodingFilter过滤器。我在应用程序中从来没有错误编码的问题。

编辑: 从扩展的日志,请http://www.example.pl/%0bapi/1.0/client/abc给出:

DEBUG RequestMappingHandlerMapping - Looking up handler method for path /^Kapi/1.0/client/abc 
TRACE RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/^Kapi/1.0/client/abc] : [{[/api/1.0/client/{ 
clientId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}] 
DEBUG RequestMappingHandlerMapping - Returning handler method [public ClientDetails ...ClientRestApi.get(java.lang.String,javax.servlet.http.HttpServletRequest)] 

回答

1

AntPathMatcher标记路径并默认修剪所有段(请参阅Javadoc的String.trim)。这种行为可以被控制。因为您可以使用setTrimTokens(false)配置带有AntPathMatcher的RequestMappingHandlerMapping。

+0

如果有人不知道如何可以做到这一点,我已经成功使用配置类扩展'WebMvcConfigurationSupport',然后像这样的方法来实现它:) '@Bean \t公共RequestMappingHandlerMapping requestMappingHandlerMapping({ \t \t RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping(); \t \t AntPathMatcher antPathMatcher = new AntPathMatcher(); \t \t antPathMatcher.setTrimTokens(false); \t \t handlerMapping.setPathMatcher(antPathMatcher); \t \t return handlerMapping; \t}' – 2016-04-15 09:02:24

0

这是我的客人,但它似乎是URL模式解析器正在搜索的"/api/1.0/client"存在。所有示例都有该字符串,因此执行搜索字符串API_PREFIX将返回true。

http://www.example.pl/%07api/1.0/client/ABC

http://www.example.pl/%0bapi/1.0/client/ABC

你的最后一个例子没有确切 /api/1.0/client字符串,而是使用0bi/1.0/client

简短回答:您不必为分析器定义一个确切的URL来进行选择。我相信没有spring的普通Java EE也是如此。如果您在web.xml文件中定义了/api/1.0/client/*,则任何具有该字符串的URL都会触发您分配给它的专用控制器。即使字符串被前置,但垃圾如/SDSFDFSFSFSF/api/1.0/client

+0

我检查了你的解决方案,但它不是真的。当我去:'www.example.pl/xapi/1.0/client/abc'或'www.example.pl/x/api/1。0/client/abc'我总是得到http 404 - 正确的行为。我注意到这种奇怪的行为只发生在百分比编码字符放在uri路径的开头。 – 2014-09-30 08:36:47