简体   繁体   中英

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?

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

Actually, most MVC frameworks support RESTful actions (ie 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> 

我写了一个名为jurlmap的库,其中包括你要求的东西。

You can do such things with Spring web MVC. Their controller API can map parts of the URL to specific calls on the back end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM