If I have action to a servlet, we should use mapping in XML which is recommended. So it would look like this:
HTML index:
<!DOCTYPE html>
</head><body>
<form action="go" method="POST">
Enter name: <input type="text" name="name">
<button>Submit form :)</button>
</form>
</body></html>
XML mapping:
<web-app..........
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>ServletOne</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
</web-app>
Servlet class
public class ServletOne extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String s = req.getParameter("name");
PrintWriter pw = resp.getWriter();
pw.println("Welcome " + s);
}
}
And it works fine. But my question is what if I don't want to make a mapping - I want to call Servlet class directly. I removed my XML file and I did all of these lines:
<form action="ServletOne" method="POST">
<form action="ServletOne.class" method="POST">
<form action="ServletOne.java" method="POST">
And.. none of them work. Can I actually call Servlet directly without mapping at all? If yes, how? Sometimes for testing purposes, I don't need to waste time on mapping every servlet.
You can use annotation e.g.
In fact, Servlet 3.0 onwards, most of the developers prefer this to XML configuration.
Note that the Servlet Specification requires the mapping to start with a
/
. Check this to learn more about it.