Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Routing in Java

Coming from other web frameworks, I'm used to being able to map parts of a URL to method parameters. I know that web.xml provides a way to map an entire URL to a Servlet but is there a way to get more features out of this, such as mapping pieces of the URL to method parameters?

like image 569
Jack Edmonds Avatar asked May 31 '10 13:05

Jack Edmonds


3 Answers

Using Spring (MVC) is overkill for this. If you don't need dependency injection, you'll be happy with redirect filter.

like image 69
calavera.info Avatar answered Oct 04 '22 09:10

calavera.info


Actually, most MVC frameworks support RESTful actions (i.e. allow to map URLs on methods of actions): Spring MVC, Stripes, Struts 2 with the REST plugin.

If you're not using any of them, you could achieve this with URL rewriting. The UrlRewriteFilter is pretty famous and allows to implements such things. From the documentation about Method Invocation:

The standard servlet mapping that is done via web.xml is rather limiting. Only .xxx or /xxxx/, no abilty to have any sort of smart matching. Using UrlRewriteFilter any rule when matched can be set to run method(s) on a class.

Invoke a servlet directly

<rule>
<from>^/products/purchase$</from>
<run class="com.blah.web.MyServlet" method="doGet" />
</rule>

This will invoke doGet(HttpServletRequest request, HttpServletResponse response) when the "from" is matched on a request. (remeber this method needs to be public!)

Use it to delegate cleanly to your methods

<rule>
    <from>^/pref-editor/addresses$</from>
    <run class="com.blah.web.PrefsServlet" method="runAddresses" />
</rule>
<rule>
    <from>^/pref-editor/phone-nums$</from>
    <run class="com.blah.web.PrefsServlet" method="runPhoneNums" />
</rule>
like image 41
Pascal Thivent Avatar answered Oct 04 '22 07:10

Pascal Thivent


I have written a library called jurlmap which among other things does what you are asking for.

like image 35
mtomis Avatar answered Oct 04 '22 09:10

mtomis