How to call servlet class from HTML form

Just create a class extending HttpServlet and annotate it with @WebServlet on a certain URL pattern.

@WebServlet("/login")
public class LoginServlet extends HttpServlet {}

Or when you’re still on Servlet 2.5 or older (the annotation was new since Servlet 3.0), then register the servlet as <servlet> in web.xml and map it on a certain URL pattern via <servlet-mapping>.

<servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.example.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

Then, just let the HTML link or form action point to an URL which matches the url-pattern of the servlet.

<a href="https://stackoverflow.com/questions/2395251/${pageContext.request.contextPath}/login">Login</a>
<form action="https://stackoverflow.com/questions/2395251/${pageContext.request.contextPath}/login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit">
</form>

When using submit buttons, make sure that you use type="submit" and not type="button". Explanation on the ${pageContext.request.contextPath} part can be found in this related question and answer: How to use servlet URL pattern in HTML form action without getting HTTP 404 error.

Links and forms with method="get" will invoke doGet() method of the servlet. You usually use this method to preprocess a request “on page load”.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...
}

Forms with method="post" will invoke doPost() method of the servlet. You usually use this method to postprocess a request with user-submitted form data (collect request parameters, convert and validate them, update model, invoke business action and finally render response).

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...
}

To learn more about servlets and to find more concrete examples, head to our Servlets wiki page. Noted should be that you can also use a JSP file instead of a plain HTML file. JSP allows you to interact with backend via EL expressions while producing HTML output, and to use taglibs like JSTL to control the flow. See also our JSP wiki page.

Leave a Comment