使用 Spring 禁用控制器端点

Jun*_*une 5 java spring spring-mvc

假设我有一个 Spring MVC 控制器,如下所示:

@Controller
public class MyController {

    @RequestMapping(value = "/doSomething", method = RequestMethod.POST)
    public @ResponseBody JSONObject doSomething() {
    //...
    }

    @RequestMapping(value = "/doOtherThing", method = RequestMethod.POST)
    public @ResponseBody JSONObject doOtherThing() {
    //...
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法使用 Spring XML 文件或其他一些配置来禁用此控制器的一个端点?例如,禁用 /doSomething 并保持启用 /doOtherThing?

我问的原因是因为我需要添加两个不同版本的组件 (jar),它有一个带有多个端点的控制器,但我需要禁用 jar 1.0 中的 doSomething 并在 jar 2.0 上使用 doSomething。

小智 0

您可以使用过滤器...配置一个对象,其中每个实例都是控制器中存在的受限映射。现在假设您想阻止“www.someaddress.com/yourapp/finalMapping”,请添加一个带有以下类型的DisabledUrl对象id 字段是完整的映射。定义一个存储库或一种方法供您查询此类表,您瞧,您可以在运行时限制对资源的访问..更好的方法是在 eh-cache 中保留“禁用”映射列表并避免查询每个请求的数据库,但我们可以说这是一个粗略的解决方案。

            @Component(value = "yourNiceFilter")
            public class YourNiceFilter extends OncePerRequestFilter{

            @Autowired
            private DisabledUrlRepository disabledUrlRepository;

                private static final Logger logger = LoggerFactory.getLogger(YourNiceFilter.class);

                @Override
                protected void doFilterInternal(HttpServletRequest request,
                        HttpServletResponse response, FilterChain filterChain)
                                throws ServletException, IOException {
                    //String[] path = request.getRequestURL().toString().split("/");

                                if (letPagePass(request.getRequestURL().toString()) == false)
                                {   
                                    response.sendRedirect(request.getContextPath()+"/your/courtesy/page/requestMapper");
                                    return;
                                }
                    filterChain.doFilter(request, response);

                }

                public boolean letPagePass(String url)
                {
                String mappedPage = null;
                //do something and extract the identifier of the "mapping"
                if (mappedPage != null)
                {
                    if (disabledUrlRepository.findOne(mappedPage) != null);
                    {
                    return false;
                    }
                }
                return true;
                }
Run Code Online (Sandbox Code Playgroud)