Issue
As a beginner in JSP and Servlets, I learned two ways to call my Servlet from HTML file. One is using servlet annotation, and another one is using XML's mapping configuration. Pardon my ignorance, but why can't I simply write the name of Servlet inside form's action attribute? What is happening behind the "curton" that forces us developers to pay special attention to Servlets? Unlike HTML and JSP files which we can call directly.
This is what I am talking about. Or, why simply doing this is not correct:
index.html:
<html><body>
<form action="MyServlet" method="POST">
Enter name: <input type="text" name="name">
<button>Submit name</button>
</form>
</body></html>
MyServlet.java:
public class MyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
String input = req.getParameter("name");
pw.println("hello " + input);
}
}
I understanding mapping servlets provides us flexibility and security. But my question still stands. Why "direct calling" Servlet class file is not available and gives 404 error not found
? Why server can't find my servlet?
Solution
Your HTML page is being rendered in the user's browser, running in one process. Your servlet is running in a servlet engine, in a JVM, in a different process, and probably on a different computer.
The only way they can communicate is via HTTP requests from the browser to the servlet engine.
There is no way for the browser to find classes in the JVM, all it can do is blindly send HTTP requests to the URLs that were rendered in the HTML and hope that the servlet engine responds.
It would be possibly to provide a servlet which despatched HTTP requests based on class names given in a parameter of the HTTP request, which would then do what you suggest.
Answered By - tgdavies
Answer Checked By - Timothy Miller (JavaFixing Admin)