【问题标题】:Implementing a REST api which switches between XML and JSON in Servlets实现一个在 Servlet 中切换 XML 和 JSON 的 REST api
【发布时间】:2009-09-23 02:13:22
【问题描述】:

Twitter 的 REST api 允许您在 URI 的末尾附加 JSON 或 XML。

例如

http://twitter.com/statuses/public_timeline.json
http://twitter.com/statuses/public_timeline.xml

在 servlet 的上下文中,状态将是 webapp 上下文名称 & public_timeline.json 映射到某个 servlet。我想维护一个 servlet 来进行调度。这可以在 servlet 中完成吗?

【问题讨论】:

    标签: java json tomcat rest


    【解决方案1】:

    Servlet 中的 URL 映射只支持扩展名匹配,不支持前缀匹配。所以这行不通,

      <url-pattern>/public_timeline.*</servlet-class>
    

    这是我的建议,

    <servlet-mapping>
      <url-pattern>/*</servlet-class>
      <servlet-name>YourServlet</servlet-class>
    </servlet-mapping>
    

    在servlet中,你可以这样做,

        String path = request.getPathInfo();
    
        if (path == null) return;
    
        int index = path.indexOf('/');
        String api;
        if (index < 0) 
            api = path;
        else
            api = path.substring(index+1);
    
            if (api.equals("public_timeline.json"))
                // Process it as JSON
    
            if (api.equals("public_timeline.xml"))
                // Process it as XML
    

    大多数 API 使用格式参数来指示响应格式。我认为这是更好的方法。

    【讨论】:

      【解决方案2】:

      在 Java 中,如果您将 JAXRS 用于您的 REST 服务,请注释您的 REST 服务方法,例如:

      @Path("/statuses/public_timeline{fileExt}")
      

      然后将以下内容添加到您的方法参数中:

      @PathParam(value="fileExt") String fileExt
      

      fileExt 变量将是您的扩展名。我认为这将是使用 JAXRS 的标准 REST 方式

      【讨论】:

        【解决方案3】:

        是的,有可能。

        查看 web.xml 文件,您可能会使用如下模式:

        <servlet-mapping>
            <url-pattern>public_timeline.*</servlet-class>
            <servlet-name>myservlet</servlet-class>
        </servlet-mapping>
        

        我认为你甚至可以使用 public_timeline.[json|xml]

        【讨论】:

          【解决方案4】:

          您可以在 url-pattern 中进行简单的全局匹配:

          <servlet>
            <servlet-name>public_timeline</servlet-name>
            <servlet-class>your.package.PublicTimelineServlet</servlet-class>
          </servlet>
          
          <servlet-mapping>
            <url-pattern>/public_timeline.*</servlet-class>
            <servlet-name>public_timeline</servlet-class>
          </servlet-mapping>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-12-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多