servlets form data
Servlets can handle form data submitted by users in HTML forms. To handle form data in a servlet, we can use the HttpServletRequest
object, which provides methods to retrieve form data submitted by the client.
Here's an example of a simple HTML form that collects a user's name and email address:
<!DOCTYPE html> <html> <head> <title>Simple Form</title> </head> <body> <form action="submit-form" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br> <label for="email">Email:</label> <input type="email" id="email" name="email"><br> <input type="submit" value="Submit"> </form> </body> </html>
In this example, the form has an action
attribute of "submit-form", which indicates that the form data should be submitted to a servlet at the URL "/submit-form". The method
attribute is set to "post", indicating that the form data should be sent in the request body rather than in the URL.
To handle the form data in a servlet, we can define a doPost()
method that reads the form data from the HttpServletRequest
object:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FormServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the form data String name = request.getParameter("name"); String email = request.getParameter("email"); // Generate the response response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>"); out.println("# Form Data:"); out.println("<p>Name: " + name + "</p>"); out.println("<p>Email: " + email + "</p>"); out.println("</body></html>"); } }
In this example, we define a new servlet called FormServlet
that extends HttpServlet
. The doPost()
method is overridden to handle POST requests, which is what our HTML form is using. We use the getParameter()
method of the HttpServletRequest
object to retrieve the values of the "name" and "email" form fields submitted by the client. We then generate an HTML response that displays the form data submitted by the client.
To deploy this servlet, we need to compile it and package it as a WAR file, and then deploy the WAR file to a servlet container. When the user submits the HTML form, the servlet container will invoke the doPost()
method of the FormServlet
, which will read the form data and generate a response. The response will be sent back to the client, who will see the form data displayed in their web browser.