In order to find the proper URL to which to submit forms, I need to manually set the context name in every URL.

Roger Hand

[Short answer: No, unfortunately you need to actively make your URLs "context-aware". Some frameworks make this easier for you, but I end up doing something like you described. -Alex]

You can avoid a lot of the base path problems by having your forms submit to a jsp page, and having that jsp page forward to the servlet. So your form submission avoids all path problems:

<form action="MySubmitPage.jsp">
I started by making a dummy jsp page that did nothing but forwarded, but now I put the forwarding action at the top of the jsp page with the form ... there's a small bit of code that checks to see if the query includes the form variables from a form submission. It the query vars (or, actually, a single "marker" var - see example below) are there we forward to the servlet for processing. If not we display the page with the form, ready to be filled in.

Since the browser sees the return url as being in the same dir as the original form jsp page, all image links, etc., work correctly even though it's the servlet that's doing all the work and then forwarding to the result page. (Of course if you do a redirect you avoid the path problems too but you burn an extra trip to the browser.)

Of course this really just offloads the problem you bring up of the path to the servlet ... instead of the problem being in the action tag in the jsp code that forwards to the servlet. To make my code portable I use something similar to the method you suggest:

if ("true".equals(request.getParameter("_saveNew"))) {
  String urlForward = pageContext.getServletContext()
     + "com.mycompany.editinfo.BeanSaveServlet";
  <jsp:forward page="<%= urlForward %>"/>
} //if saving data
/* We have no data to save; show the form. */