views:

465

answers:

4

Twitter's REST api allows you to append a JSON or XML at the end of the URI.

e.g.

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

In the context of servlet, statuses will be the webapp context name & public_timeline.json is mapped to some servlet. I want to maintain one servlet to do the dispatch. Can this be done in servlets ?

A: 

Yes, it is possible.

Take a look at the web.xml file you may use a pattern like:

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

I think you can even use public_timeline.[json|xml]

OscarRyz
What container do you use? This will not work on Tomcat.
ZZ Coder
A: 

You can do simple glob-matching in 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>
dcrosta
+2  A: 

The URL mapping in Servlet only supports extension matching, not prefix matching. So this doesn't work,

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

Here is my suggestion,

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

In the servlet, you can do this,

 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

Most APIs use a format parameter to indicate response format. I think that's the better way.

ZZ Coder
A: 

In Java, if you are using JAXRS for your rest services, annotate your REST service method like:

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

Then add the following to you method argument:

@QueryParam(value="fileExt") String fileExt

The the fileExt variable would be your extension. I think that would be a standard REST way to do it using JAXRS

jconlin