Lets say that you have a following simple application:
<form action="helloServlet" method="post">
Give name:<input type="text" name="name" />
<input type="submit" value="Send"/>
</form>
And a servlet handling that form:
package org.servlets.hello;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="helloServlet", urlPatterns={"/helloServlet"})
public class helloServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet helloServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello " + name + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
Now this works perfectly when it is ran from a web page located at the "Web Pages" folder but when I try to do the same in a subfolder in Web Pages I am given 404 error (The requested resource () is not available.). Am I supposed to change something to make the subfolder a valid location to call for a servlet?
Alright I figured it out myself. Here's my solution in case someone else runs into same problem. As I understand it the standard java web project folder structure is as follows:
As such if we have a hello.jsp in a SUBFOLDER where we have a form with the following:
And a servlet in org.whatever.name with such:
Then the servlet location is mapped based on the Web Pages folder and the two files cannot find each other. So in order to make the servlet available to subfolders then we either change the servlet:
or the form:
Use a domain-relative URL.
No need to repeat every single folder in servlet mapping.
See also:
If the
POST
action url starts with"/"
it is absolute. Or else, it is relative to the current pageBecause the post url
<form action="helloServlet"
, helloServlet is relative to the current path.This is how the helloservlet url will be accessed:
And in your case, the Usage 1 works because Servlet is mapped to
/helloservlet
.Solution:
Modify line
<form action="helloServlet" method="post">
to
<form action="/{contextPath}/}helloServlet" method="post">
I think your context path is not default
"/"
context path. In that case, you should be having url relative to the domain. Replace {contextpath} with the actual context path.