cubeb
cubeb

Reputation: 457

Servlet not found in Intellij

I trying to run my jsp page along with a servlet. The Servlet is not found when I try to call it via url

http://localhost:8080/StudentServlet I get a 404 error saying:

"requested resource not available".

I am also trying to call it via a Form. When I click submit, its not recognised either producing same error.

Read answers here asking to use Maven or set up mapping via web.xml. From my understanding, setting up via web.xml is the old way and the new way is to set up name on the servlet which I have. Unsure what I am doing wrong.

I am not using and build tool and just starting up my Tomcat server used locally to run jsp pages which works. But Servlets are not recognised. Added screenshot for project structure in case something is wrong there.

Servlet

@WebServlet(name = "StudentServlet")
public class StudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println("<html><body>");

        out.println("<h3>Student name is:" +
                request.getParameter("firstname") +
                " " +
                request.getParameter("lastname") +
                "</h3>");

        out.println("</body></html>");

    }
}

index.jsp

<form action="StudentServlet" method="get">
    First Name: <input type="text" name="firstname"/>
    <br/><br/>
    Last Name: <input type="text" name="lastname"/>
    <br/><br/>
    <input type="submit" value="Submit"/>
</form>

Project Structure

enter image description here

Upvotes: 3

Views: 8281

Answers (2)

CrazyCoder
CrazyCoder

Reputation: 402581

WebServlet documentation states the following:

At least one URL pattern MUST be declared in either the value or urlPattern attribute of the annotation, but not both.

You can just use the following:

@WebServlet("/StudentServlet")

or this:

@WebServlet(name = "StudentServlet", urlPatterns={"/StudentServlet"})

or this:

@WebServlet(name = "StudentServlet", value="/StudentServlet")

The value attribute is recommended for use when the URL pattern is the only attribute being set, otherwise the urlPattern attribute should be used.

Upvotes: 6

iLearn
iLearn

Reputation: 1189

Give a Context Path in the your Form action. This way, it will automatically find your Servlet's path. For example

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

Also, write the URL pattern "/" in the @WebServlet(name = "/StudentServlet") This annotation indicates that the URL pattern /StudentServlet follows the context root.

Plus, give the the Context Root in your localhost eg: http://localhost:8080/ContextRoot/StudentServlet

Upvotes: 0

Related Questions