JeroenD
JeroenD

Reputation: 43

Map with @WebServlet url pattern annotation in JSP

When trying to make a simple webservlet a stumble upon this problem: if I use a name that includes /../ it won't find the resource.

This is what I have that WORKS:

Controller.java

@WebServlet(urlPatterns = {"/Controller"})
public class Controller extends HttpServlet{ ... }

And the JSP-page:

<form action="Controller">
...
</form>

However, what I try to do specify the name as a folder, to work more structured. This is the code I struggle with and that DOESN'T work:

@WebServlet(urlPatterns = {"/servletController/Controller"})
public class Controller extends HttpServlet{ ... }

JSP-page:

<form action="/servletController/Controller">
...
</form>

And I tried numerous variations. So my question, how to properly use a folder-structure with the urlPatters-annotation, or is it just not possible?

Upvotes: 1

Views: 5541

Answers (1)

BalusC
BalusC

Reputation: 1108722

It's caused by the leading slash you specified in the <form action>. It makes the specified URL domain-relative. I.e. it's resolved relative to the domain root in the URL as you see in browser's address bar, instead of to the currently requested path (folder) in the URL as you see in browser's address bar.

Imagine that your JSP is opened by

http://localhost:8080/contextname/some.jsp

and the URL has thus the folder /contextname in it. The form action as you have would submit to

http://localhost:8080/servletController/Controller

while the servlet is as per your mapping actually at the following URL:

http://localhost:8080/contextname/servletController/Controller

Fix the form action accordingly to make it path-relative instead of domain-relative:

<form action="servletController/Controller">

Or, by specifying a valid domain-relative URL:

<form action="/contextpath/servletController/Controller">

Or, if you worry about the dynamicness of the context path and rather like not to hardcode it:

<form action="${pageContext.request.contextPath}/servletController/Controller">

See also:

Upvotes: 1

Related Questions