How do I get the name of the currently executing script?

Alex Chaffee

Use req.getRequestURI() or req.getServletPath(). The former returns the path to the script including any extra path information following the name of the servlet; the latter strips the extra path info. For example:

URL http://www.purpletech.com/servlets/HelloEcho/extra/info?height=100&width=200
getRequestURI /servlets/HelloEcho/extra/info
getServletPath /servlets/HelloEcho
getPathInfo /extra/info
getQueryString height=100&width=200

This is useful if your form is self-referential; that is, it generates a form which calls itself again. For example:

out.println("<FORM METHOD=POST ACTION="" +
	    res.encodeURL(req.getServletPath()) +
out.println("<INPUT NAME=value>");
out.println("<INPUT TYPE=submit>");
(encodeURL adds session information if necessary. See the Sun Servlet Tutorial and this FAQ's Session Tracking question. Note that this method was renamed from "encodeUrl" to the properly-capitalized "encodeURL" somewhere around version 2.1 of the servlet spec.)

Note that early versions of Java Web Server and some servlet engines had a bug whereby getRequestURI would also return the GET parameters following the extra path info.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact