How to Pass data from a JSP page to a Servlet using Plain Java J2EE

Below example explains how to use the JSP to get the Form data input and pass it to the servlet to store/update the database.


Step 1:  Create a class that extends the HttpServlet() as shown below.
public class FormServlet extends HttpServlet {}
Step 2 : 

Map this servlet in the web.xml as shown below
<servlet>
    <servlet-name>formServlet</servlet-name>
    <servlet-class>com.developersarena.FormServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>formServlet</servlet-name>
    <url-pattern>/form</url-pattern>
</servlet-mapping>
Step 3 :  In the Form action POST method , point the action to the Form as shown below.
<form action="form" method="post">
Step 4 :
Then create a doPost() method in your servlet which takes the input as request parameters. The input field name is the request parameter name.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String fname = request.getParameter("firstname");
    String lname = request.getParameter("lastname");
  }
Step 5 : 

Pass these details to the persistence API's as show below..
User user = new User(fname, lname);
userDAO.save(user);