Search code examples
formsservletsjava-ee-6

Multiple folders in Java EE 6 web pages


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?


Solution

  • If the POST action url starts with "/" it is absolute. Or else, it is relative to the current page

    Because the post url <form action="helloServlet" , helloServlet is relative to the current path.

    This is how the helloservlet url will be accessed:

              Current Page          Servlet URL
    Usage 1   /form.html            /helloservlet
    Usage 2   /subfolder/form.html  /subfolder/helloservlet
    

    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.