0

I've just started writing some java servlets and running them with Tomcat (v7). My understanding of how the directory structure works is that URLs are relative to the name of your application:

  • So if my app is MyWebApp then by visiting http://server/MyWebApp I'll see, for example, the "index.jsp" file I created in the root directory of my web app.
  • If said index.jsp has a form with POSTs to "submit" then the broswer will send to http://server/MyWebApp/submit
  • And in my web.xml file I can point a class which extends HttpServlet to handle this POST request. Something like:

    <servlet> <servlet-name>MyHandler</servlet-name> <servlet-class>org.me.handler</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyHandler</servlet-name> <url-pattern>/submit</url-pattern> </servlet-mapping>

  • However, suppose my form POSTs to "/submit". Then the browser sends the request to http://server/submit

  • I don't see any way to intercept this from my web app.

One approach is just to deploy my web app as the ROOT. Is there another approach?

wero
  • 32,544
  • 3
  • 59
  • 84
Matthew Daws
  • 1,837
  • 1
  • 17
  • 26

1 Answers1

1

Each web application in servlet container has a context path. It can only receive requests below the context path. For good reasons there is no way to "break out" of its context path (except if the servlet container has a bug).

A servlet mapping is always to be seen as relative to the context path.

You can deploy web applications as root, i.e. with context path "/". See here how to do this for Tomcat.

When your pages contain URLs to the server (href-, src-, action-attributes, etc.) you basically have two options:

  1. Use a relative URL. E.g. the form in your example could simply have action="submit" which is turned into an absolute URL by the browser.

  2. Use absolute URLs. Since (if) you don't want that your application is dependent on a fixed content path, you therefore should (need) to dynamically generate your pages and prefix those URLs with the actual context path.

Community
  • 1
  • 1
wero
  • 32,544
  • 3
  • 59
  • 84