Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet mapping: url-pattern for URLs with trailing slash

I have a problem related to the servlet mapping. I have the following in web.xml:

<servlet>
    <servlet-name>HelloWorldServlet</servlet-name>
    <servlet-class>test.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

If I access to http://localhost:<port>/MyApp/HelloWorld the servlet HelloWorldServlet is called.

I also want my servelet to respond to http://localhost:<port>/MyApp/HelloWorld/. How can I achieve this effect? I'm developing with NetBeans but it does not allow me to put a pattern ended with /.

like image 527
Gabriel Llamas Avatar asked Dec 07 '10 14:12

Gabriel Llamas


2 Answers

After you've added your wildcard on your <url-pattern>

<url-pattern>/HelloWorld/*</url-pattern>

You can get the extra path associated with the URL by using HttpServletRequest.getPathInfo().

E.g.

http://localhost:<port>/MyApp/HelloWorld/one/

The result will be

/one/

From the JavaDoc:

Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character.

like image 187
Buhake Sindi Avatar answered Nov 14 '22 04:11

Buhake Sindi


Use a wildcard. You can redirect all the traffic going to a specific URL to the same servlet. For example, you can add the following:

<servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/HelloWorld/*</url-pattern>
</servlet-mapping>

This will redirect the URL with a slash to your original servlet.

One thought - this would redirect anything to this URL pattern to the servlet. If you want to have other URL's past this URL, you should create a servlet that will redirect to the correct URL (by looking at the URL specified). Alternatively, you could use a framework that provides mapping for you.

like image 29
Jonathan B Avatar answered Nov 14 '22 04:11

Jonathan B