[英]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.