Issue
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
Solution
WebServlet documentation states the following:
At least one URL pattern MUST be declared in either the
value
orurlPattern
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 theurlPattern
attribute should be used.
Answered By - CrazyCoder