Spring中请求映射中的多个正斜杠

5
@RestController
@RequestMapping("/api")
public class AbcController {

  @RequestMapping(value = "/abc", method = RequestMethod.GET)
  public String abc(){
    return "Hello";
  }
}

有效的URL:http://localhost:8080/api/abc
无效的URLs:
http://localhost:8080////api/abc
http://localhost:8080/////api////abc
http://localhost:8080/////////api/////abc

问题:我的控制器接受所有上述URL。我想限制它,只接受有效的URL,并在无效的URL上抛出错误。
注意:我没有使用任何自定义路由。这是默认的Spring路由。


你是否在使用Spring Security或任何过滤器来处理你的请求? - Shubham Dixit
1
https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/set-use-trailing-slash-match.html - Amogh
尝试将您的值从“/abc”更改为“abc”,让您的servlet进行分派。 - M46
是的,我也尝试了这个,但对我没用。 - Tayyab Razaq
1
不,我没有使用Spring Security。我正在使用Keycloak模块。这是一个第三方模块,用于管理用户的身份验证和授权。 - Tayyab Razaq
2个回答

1
最简单的方法是 添加自定义处理拦截器来验证url。
public class ValidateURLInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isValidUrl(request.getRequestURI())) {
            return true;
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid URL");
        return false;
    }

    private static boolean isValidUrl(String url) {
        return !url.contains("//");
    }
}

然后更新MVC配置

@Configuration
public class AppConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ValidateURLInterceptor());
    }
}

0

添加Spring Security的Maven依赖,并使用以下代码允许在未登录情况下访问所有路径。

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity web) throws Exception
    {
        web
                .ignoring()
                .antMatchers("/**");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接