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

查看:31
本文介绍了如何将带有斜杠的 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/

到没有它的网址:

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

但这通常有两个问题:

  1. 控制器太多
  2. 参数问题:如编码错误

问题

有没有办法拦截所有的 URL,如果它们有斜杠,将它们重定向到没有斜杠的相关 URL?

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天全站免登陆