Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does a Servlet get it's URI?

 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a servlet named "EmailServlet" and it's mapped to "/HandleEmail". All other parts of the application deal with it through "/HandleEmail" so they've stored info under that key. How, then, does this servlet get that URI? I don't want to hardcode it because someone could easily change it in the deploy web.xml and then everything but this servlet would work. All I can find is: getServletConfig().getServletName();
 
James Swan
Ranch Hand
Posts: 403
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out some of the methods of HttpServletRequest.
request.getServletPath();
is probably a good one to start with.
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THANKS!!
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
YIKES! It doesn't work! Here's what I'm doing:
1. Person goes to JSP page
2. JSP Page includes a servlet:
getServletConfig().getServletContext().getRequestDispatcher( "something" ).include( req, res );
3. Now the servlet that is being included is doing the doPost(). how does it get it's URI?
In the above scenario, request.getServletPath() returns the path of the JSP page! (That's because it is the path, the servlet's merely included server-side) HELP!!!
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did a workaround, but frankly I think it's stupid that a Servlet can't know what URL it's mapped to. Pretty stupid. Anyways, all I did was add an initParameter to each servlet in web.xml:

Basically, I'm just putting what ever is already in the mapping into the servlet's config params. Pretty stupid. This is the BEST workaround I could figure out because all the others dealt with adding stuff in to JSP code to add an attribute to request or whatever. This way, it's 100% in synch with the deployment choices. When the mapping's changed, they can change the init-param and everything works.
 
Sudd Ghosh
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Robert -
I don't know if I understood your question correctly, but I tried the HttpServletRequest's getRequestURL() which gave me the actual URL starting from the protocol. There is also a getRequestURI() to try out, which gives only the URI. Also there is ServletContext.getRealPath() which can give you the system path/directory location.
Hope this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic