泽西岛JAX-RS中的可选路径段 [英] Optional path segment in Jersey JAX-RS

查看:95
本文介绍了泽西岛JAX-RS中的可选路径段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了几个小时,但还不太正确.

I've searched for hours on this and haven't quite got it right.

我正在处理的项目上的API未版本控制(/controller/blah),因此我们要介绍版本控制.例如,我们有一个与@Path("/controller")关联的类.为了避免API损坏,它现在必须支持//v1/,因此以下内容将有效:

An API on a project I'm working on is not versioned (/controller/blah), so we want to introduce versioning. For example, we have a class with @Path("/controller") associated to it. Naturally to avoid API breakage, this now has to support either / or /v1/, so the following would be valid:

/controller/blah
/v1/controller/blah

我觉得必须有一个简单的解决方案来解决我遗漏的问题?

I feel there must be an easy solution to this that I am missing?

提前谢谢!

推荐答案

我将使用过滤器来重定向与某些模式(在您的情况下/v1/* )相匹配的那些请求.

I would use a Filter to redirect those requests which matched certain pattern (on your case /v1/*).

您的过滤器应如下所示:

@WebFilter(filterName = "MyCustomFilter")
public class MyCustomFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        try {
            String url = ((HttpServletRequest)arg0).getRequestURI();
            //Take into account thet the url here would be the complete url. I just put an example taking into account
            //your application name is JAX-RS_tutorial
            String redirect = url.substring("/JAX-RS_tutorial/v1".length(), url.length());
            arg0.getRequestDispatcher(redirect).forward(arg0, arg1);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new ServletException(e);
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}

然后在 web.xml 上:

<filter>
    <filter-name>MyCustomFilter</filter-name>
    <filter-class>com.myapplication.filter.MyCustomFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyCustomFilter</filter-name>
    <url-pattern>/v1/*</url-pattern>
</filter-mapping>
<servlet-mapping>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <url-pattern>/api/*</url-pattern>
    <url-pattern>/v1/api/*</url-pattern>
</servlet-mapping>

更新

真的,您只需要为 servlet映射添加新的 url-pattern .因此只需要 web.xml :

Really you just need to add new url-pattern for your servlet-mapping. So just need on web.xml:

<servlet-mapping>
    <servlet-name>JAX-RS Servlet</servlet-name>
    <url-pattern>/api/*</url-pattern>
    <url-pattern>/v1/api/*</url-pattern>
</servlet-mapping>

这篇关于泽西岛JAX-RS中的可选路径段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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