How to pass parameters by URL in web.xml?
I need to have something like this:
/{paramvalue}/url
And get the value开发者_如何学运维 of param value, and point the url to the servlet.
For example:
/josua/profile /mary/messages
"/josua/" and "/mary/" is the parameter that I need to get
And then I need to map /{username}/profile to ProfileServlet.class and /{username}/messages to MessagesServlet.class
Is there any way that I could do this?
Map a Filter
on /*
which does basically the following in doFilter()
method.
String[] pathParams = ((HttpServletRequest) request).getRequestURI().substring(1).split("/", 2);
String userName = pathParams[0];
String servletUrl = pathParams[1];
request.setAttribute("userName", userName);
request.getRequestDispatcher("/" + servletUrl).forward(request, response);
And map the ProfileServlet
on /profile/*
and MessagesServlet
on /messages/*
. In both servlets, the username should be available by request.getAttribute("userName")
.
It somewhat sounds like Pretty URLs. If you are actually up to it, I suggest you to look into any of these frameworks, PrettyFaces (for JSF), and Stripes.
Beside, its not how we usually practice in Java and this might come with few disadvantages, you should be able to map your URL to a filter in your web.xml
, see BalusC post. And then make use of HttpServletRequest
method like getRequestURI()
to continue further. Further, its good to look into regex
and try to utilise that in order to come-up with this system, as Django (a python web development framework) achieved it.
精彩评论