如何将带有斜杠的URL重定向到没有它的相应的URL? [英] How to redirect URLs with trailing slash to the corresponding ones without it?

查看:153
本文介绍了如何将带有斜杠的URL重定向到没有它的相应的URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring MVC(3.0)将带有和不带尾部斜杠的URL视为相同的URL。

Spring MVC (3.0) considers URLs with and without trailing slashes as the same URL.

例如:


http://www.example.org/data/something = http://www.example.org/data/something/

我需要使用尾部斜杠重定向URL

I need to redirect the URL with trailing slashes


http://www.example.org/data/something/

到没有它的URL:


http://www.example.org/data/something

我需要这样做内部应用程序(所以不要通过Apache重写规则等)。

I need to do this internally the application (so not rewrite rules via Apache, etc).

一种方法是:

@ResponseStatus(value=HttpStatus.MOVED_PERMANENTLY)
@RequestMapping(value = "/data/something/")
public String dataSomethingRedirect(...) {
    return "redirect:/data/something";
}

但这通常有2个问题:


  1. 太多控制器

  2. 参数问题:如错误编码



问题



有没有办法拦截所有网址,如果他们有一个尾部斜杠,将它们重定向到没有斜线的相对网址?

Question

Is there a way to intercept all the URLs and in case they have a trailing slash, redirect them to the relative one without slash?

推荐答案

您可以在网页配置中列出所需的所有重写规则



如果没有很多,你可以像这样配置重定向视图

You could list all the rewrite rules you need in your web configuration

If there aren't many of those, you can configure redirect views like this

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/my/path/", "/my/path")
      .setKeepQueryParams(true)
      .setStatusCode(HttpStatus.PERMANENT_REDIRECT); 
}



或者你可以创建一个自定义 HandlerInterceptor



但拦截器在请求映射到特定的 Controller.action 之前发生,并且您无法知道该上下文中的控制器和操作。

Or you could create a custom HandlerInterceptor

But interceptors occur before requests are mapped to a specific Controller.action and you've got no way of knowing Controllers and actions in that context.

您所拥有的只是HTTPServlet API和请求+响应;所以你可以:

All you've got is HTTPServlet API and request+response; so you can:

response.sendRedirect("http://example.org/whitout-trailing-slash");



您不想阅读的答案



当考虑HTTP时,此行为(具有尾部斜杠的URL =没有它的URL)完全有效。至少这是Spring的默认行为,您可以使用 useTrailingSlashMatch 禁用(参见javadoc )。

因此,在前端服务器上使用重写/重定向规则可以提供解决方案;但同样,我不知道你的约束(也许你可以详细说明这个,我们可以找出其他解决方案?)。

So using rewrite/redirect rules on the front-end server could a solution; but again, I don't know your constraints (maybe you could elaborate on this and we could figure out other solutions?).

这篇关于如何将带有斜杠的URL重定向到没有它的相应的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆