【问题标题】:Spring MVC: How to modify @Pathvariable(URI) in Interceptor before going to controller?Spring MVC:如何在进入控制器之前修改拦截器中的@Pathvariable(URI)?
【发布时间】:2019-08-08 10:46:18
【问题描述】:

我在 Pre-Handler Interceptor 中获得了 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。我不能升级它。

【问题讨论】:

  • 为什么?该变量是 URL 的一部分,为什么要更改它。一般来说,你不应该这样做。
  • 我有两种访问资源的方法。首先使用 UUID 访问(请参见上面给出的代码),最后一种方式是一些可以识别 UUID 的 URI。所以我希望使用最后一种方式修改 URI(一些 URI 到 UUID)。然后,控制器不需要修改。
  • 不要...请不要,因为这将是复杂和麻烦的。只需向控制器添加一个方法,该方法正是这样做并重定向到路径 URL,或者只是使用 UUID 调用其他方法。两者都比试图在拦截器中硬塞它更简单。
  • 是的,控制器中的其他方法可以将某些 URI 修改为 UUID。我要添加方法。正如你所说。谢谢!

标签: java spring spring-mvc interceptor jdk6


【解决方案1】:

拦截器的一般用途是将通用功能应用于控制器。 IE。所有页面上显示的默认数据、安全性等。您希望将其用于通常不应该执行的单个功能。

拦截器无法实现您想要实现的目标。首先,根据映射数据检测要执行的方法。在执行该方法之前,拦截器被执行。在这种情况下,您基本上想要更改传入请求并执行不同的方法。但是该方法已经被选中,因此它不起作用。

当您最终想要调用相同的方法时,只需添加另一个最终调用 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);
}

【讨论】:

    【解决方案2】:

    试试下面给定的代码。

    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);
            }
        }
    }
    

    }

    【讨论】:

    • Sir UrlUtils 是自定义类,您可以使用自己的字符串操作工具/代码
    猜你喜欢
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2014-05-19
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    相关资源
    最近更新 更多