Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 348
mbmihura Avatar asked Feb 17 '23 07:02

mbmihura


1 Answers

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

like image 126
Joakim Erdfelt Avatar answered Feb 26 '23 02:02

Joakim Erdfelt