Search code examples
javaapachejspservletsservlet-mapping

How to correct servlet mapping in JSP?


I've set up a dynamic web project that contains a jsp home page and a servlet HelloServlet java class.

The home page takes an input value from the jsp page and has a submit button to transfer the input value to the servlet class.

But when I click submit on the home page I get a HTTP Status 500 - Error instantiating servlet class HelloServlet

Does anyone know if I'm missing a step in setting this up? Or if there is a mistake in my web.xml descriptor?

Servlet class's doPost method is a follows:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub


        // read form fields
        String fibNum = req.getParameter("fibNum");
        //print input from home page
        System.out.println("username: " + fibNum);

    }

This is how I have set up the mappings in the web.xml descriptor:

  <servlet>
  <servlet-name>hello</servlet-name>
  <servlet-class>HelloServlet</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>hello</servlet-name>
  <url-pattern>/say_hello/*</url-pattern>
</servlet-mapping>

Solution

  • You need to specify the package along with class in web.xml:

    <servlet>
      <servlet-name>hello</servlet-name>
      <servlet-class>ie.gmit.HelloServlet</servlet-class>
    </servlet>
    

    Also you can just get rid of the * here:

    <servlet-mapping>
      <servlet-name>hello</servlet-name>
      <url-pattern>/say_hello</url-pattern>
    </servlet-mapping>
    

    Also you are handling the post method in your servlet but sending a get request via the form. You can either change form to method="post" or put this in your servlet:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
            // TODO Auto-generated method stub
            doPost(request, response);
    }