Mapping URLs in Servlets

I am creating a site with JSP and servlets. How do I match a url like this example.com/12345

to get the response as if the request was example.com/content.jsp?id=12345

?

+2


a source to share


1 answer


Use url-pattern

from /*

, compile pathinfo with HttpServletRequest#getPathInfo()

and finally forward the request to the desired destination RequestDispatcher#forward()

.

Basic startup example (business logic and exception handling):



String pathInfo = request.getPathInfo();
String id = pathInfo.substring(1); // Get rid of trailing slash.
String newURL = String.format("/content.jsp?id=%d", id);
request.getRequestDispatcher(newURL).forward(request, response);

      

Alternatively, especially if there isn't really any business logic, you can also use the Tuckey UrlRewriteFilter . This way you can rewrite your url the way you would with Apache HTTPD, well known mod_rewrite

.

+3


a source







All Articles