user2613539 user2613539 - 2 months ago 8
Java Question

Error instantiating servlet class - HTTP Status 500

Trying to create a new servlet .... but getting error

HTTP Status 500 - Error instantiating servlet class


  1. My servlet class looks like

    package com.example.tutorial;

    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(description = "Test servlet this is", urlPatterns = { "/servletexample" })
    public class ServletExample extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ServletExample() {
    super();
    }

    protected void service(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Testing servlet !!!");
    }

    }

  2. My web.xml looks like :

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>ServletJSPExample</display-name>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
    <servlet-name>ServletExample</servlet-name>
    <servlet-class>com.example.tutorial.ServletExample</servlet-class>
    </servlet>

    <servlet-mapping>
    <servlet-name>ServletExample</servlet-name>
    <url-pattern>/servletexample</url-pattern>
    </servlet-mapping>

    </web-app>



Don't know what is happening...... Would appreciate help .....

Answer

you can either remove your annotation or the web.xml mapping.

if you need both approaches, it should be similar to below:

@WebServlet(name = "ServletExample", urlPatterns = {"/servletExample"})
public class ServletExample extends HttpServlet {
....
}

and the mapping in web.xml should be:

<servlet>
    <servlet-name>ServletExample</servlet-name>
    <servlet-class>com.example.tutorial.ServletExample</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ServletExample</servlet-name>
    <url-pattern>/servletExample</url-pattern>
</servlet-mapping>

It looks to me that you're missing the "name" attribute in your @WebServlet annotation. put it and try again.