[英]Spring MVC: How to modify @Pathvariable(URI) in Interceptor before going to controller?
我在预处理器拦截器中获得了控制器的@PathVariable。
Map<String, String> pathVariable = (Map<String, String>) request.getAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE );
但是我希望修改@PathVariable值(如下)。
@RequestMapping(value = "{uuid}/attributes", method = RequestMethod.POST)
public ResponseEntity<?> addAttribute(@PathVariable("uuid") String uuid, HttpServletRequest request, HttpServletResponse response) {
//LOGIC
}
如何在进入控制器之前在拦截器中修改@PathVariable(“ uuid”)值? 我正在使用Spring 4.1和JDK 1.6。 我无法升级。
拦截器的一般用途是将通用功能应用于控制器。 即在所有页面,安全性等上显示的默认数据。您想将其用于一项通常不应该使用的功能。
拦截器无法实现您想要实现的目标。 首先,基于映射数据来检测要执行的方法。 在执行该方法之前,将执行拦截器。 在此,您基本上想更改传入的请求并执行其他方法。 但是该方法已被选择,因此将不起作用。
当您最终要调用同一方法时,只需添加另一个请求处理方法,该方法要么最终调用addAttribute
要么简单地重定向到具有UUID的URL。
@RequestMapping("<your-url>")
public ResponseEntity<?> addAttributeAlternate(@RequestParam("secret") String secret, HttpServletRequest request, HttpServletResponse response) {
String uuid = // determine UUID based on request
return this.addAttribute(uuid,request,response);
}
请尝试以下给定的代码。
public class UrlOverriderInterceptor implements ClientHttpRequestInterceptor {
private final String urlBase;
public UrlOverriderInterceptor(String urlBase) {
this.urlBase = urlBase;
}
private static Logger LOGGER = AppLoggerFactory.getLogger(UrlOverriderInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
URI uri = request.getURI();
LOGGER.warn("overriding {0}", uri);
return execution.execute(new MyHttpRequestWrapper(request), body);
}
private class MyHttpRequestWrapper extends HttpRequestWrapper {
public MyHttpRequestWrapper(HttpRequest request) {
super(request);
}
@Override
public URI getURI() {
try {
return new URI(UrlUtils.composeUrl(urlBase, super.getURI().toString())); //change accordingly
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.