Jetty '{servlet}/{parameter}' url routing

12,801

Solution 1

You'll have 2 parts to worry about.

  1. The pathSpec in your WEB-INF/web.xml
  2. The HttpServletRequest.getPathInfo() in your servlet.

The pathSpec

In your WEB-INF/web.xml you have to declare your Servlet and your url-patterns (also known as the pathSpec).

Example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   metadata-complete="false"
   version="3.0"> 

  <display-name>Example WebApp</display-name>

  <servlet>
    <servlet-name>clientServlet</servlet-name>
    <servlet-class>com.mycompany.ClientServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>clientServlet</servlet-name>
    <url-pattern>/client/*</url-pattern>
  </servlet-mapping>
</web-app>

This sets up the servlet implemented as class com.mycompany.ClientServlet on the name clientServlet then specifies the url-pattern of /client/* for incoming request URLs.

The extra /* at the end of the url-pattern allows any incoming pattern that starts with /client/ to be accepted, this is important for the pathInfo portion.

The pathInfo

Next we get into our Servlet implementation.

In your doGet(HttpServletRequest req, HttpServletResponse resp) implementation on ClientServlet you should access the req.getPathInfo() value, which will receive the portion of the request URL that is after the /client on your url-pattern.

Example:

Request URL        Path Info
----------------   ------------
/client/           /
/client/hi         /hi
/client/world/     /world/
/client/a/b/c      /a/b/c

At this point you do whatever logic you want to against the information from the Path Info

Solution 2

You can use Jersey and register the following class in the ResourceConfig packages, which is handling ../worker/1234 url patterns.

read more: When to use @QueryParam vs @PathParam

@Path("v1/services/{entity}")
@GET
public class RequestHandler(@PathParam("entity")String entity, @PathParam("id")String id){
   @path({id})
   public Entity handle(){

   }
}
Share:
12,801
mbmihura
Author by

mbmihura

Updated on June 04, 2022

Comments

  • mbmihura
    mbmihura almost 2 years

    I'm using jetty 9.0.3.

    How to map an URL such as www.myweb.com/{servlet}/{parameter} to the given servlet and parameter?

    For example, the URL '/client/12312' will route to clientServlet and its doGet method will receive 12312 as a parameter.

  • mbmihura
    mbmihura almost 11 years
    Thanks! I did something similar but in the servlet I used 'req.getRequestURI().split("/(.*?)")[2];' instead to filter the uri string. I will implement 'getPathInfo()' which it's far more cleaner.