Rohi
Rohi

Reputation: 385

JSP/Servlet rewrite URL

I'd like to change the URL of some pages in my website in the same way as foursquare is doing:

from www.foursquare.com/v/anystring/venueid

to www.foursquare.com/v/venue-name/venueid

For example central park in new york:

https://foursquare.com/v/writeherewhatyouwant/412d2800f964a520df0c1fe3

becomes

https://foursquare.com/v/central-park/412d2800f964a520df0c1fe3

I'm developing a pure JSP/Servlet app, no frameworks, in a Tomcat container.

I'm thought of using tuckey's urlrewritefilter, but I don't see how can I use dynamic values coming from the servlet itself there (the venue name)

How can I accomplish this?

Upvotes: 1

Views: 2549

Answers (1)

David Levesque
David Levesque

Reputation: 22451

Off the top of my head, here's something you could try:

1) Create a servlet with a servlet-mapping matching the common (prefix) part of the URL (e.g. for foursquare the pattern would be /v/*).

2) In your servlet, retrieve the remaining part of the URL path using request.getPathInfo(). You can then parse it using regular string utilities and convert it to the new path you'd like.

3) Assuming your updated path is in a variable called newUrl, call response.sendRedirect(newUrl) to tell the browser to update its URL. This will also call your servlet again with the new path, so it needs to handle both cases.

See the javadoc for HttpServletResponse.sendRedirect() for more info about how it handles relative vs absolute paths, etc.

Upvotes: 2

Related Questions