3 Replies Latest reply: May 25, 2012 6:09 PM by 939350 RSS

    How to receive parameters from a form and insert values in db using servlet

    939350
      Hi friends,
      My first question here.
      I'm trying to create a Servlet that takes input from a form and process it and insert it in database.tablename.

      My MAIN ISSUE IS WITH THE NUMBER OF COLUMNS THAT WOULD BE DYNAMIC AND THUS CANT RECEIVE THE PARAMETERS IN STATIC CODE.

      Here is the form code

      <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <!DOCTYPE html>
      <form action="Test" method="post" />
      <table width="90%" border="1" cellspacing="1" cellpadding="1">
      <tr>
      <th scope="col">Student Name</th>
      <th scope="col">RollNo</th>
      <th scope="col">Java</th>
      <th scope="col">J2ee</th>
      </tr>
      <tr>
      <td><input type="text" name="studentname" /></td>
      <td><input type="text" name="rollno" /></td>
      <td><input type="text" name="java" /></td>
      <td><input type="text" name="j2ee" /></td>
      </tr>
      <tr>
      <td><input type="text" name="studentname" /></td>
      <td><input type="text" name="rollno" /></td>
      <td><input type="text" name="java" /></td>
      <td><input type="text" name="j2ee" /></td>
      </tr>
      <tr>
      <td><input type="text" name="studentname" /></td>
      <td><input type="text" name="rollno" /></td>
      <td><input type="text" name="java" /></td>
      <td><input type="text" name="j2ee" /></td>
      </tr>
      </table>
      <input type ="submit" value="insert values in the database now"/>
      </form>
      </html>

      ------------

      And here is the Servlet

      import javax.servlet.*;
      import javax.servlet.http.*;
      import java.sql.*;
      import java.io.*;
      public class Test extends HttpServlet {
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      String title = "Module: Process Result Values from previous page";
      out.println("<html>\n" +
      "<head><title>" + title + "</title></head>\n" +
      "<body>");
                try
                {
                     Class.forName("com.mysql.jdbc.Driver");
                     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/","root", "root");
                     Statement s = con.createStatement();

      ResultSet res = s.executeQuery("SELECT * FROM dbname.tablename");
      ResultSetMetaData rmeta=res.getMetaData();
      int noofcolumns=rmeta.getColumnCount();

                                    
                                    
                     if(!con.isClosed())
      {
      }
      }
                catch(Exception e)
                {
      System.out.println("Exception"+e);
      out.println(e);

                }
      if(connectionFlag==1)
      {
      }
      out.println("</body></html>");
      doGet(request, response);
      }
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
      }
      }


      This is the basic code structure and I'm trying to figure out this special case with handling the multiple parameters:
      1. I dont' want to use String []a=request.getParameterValues("studentname"); as hard code. The reason being the number of rows will be diyamic and I would like to get the column name and then then use an array of string to take values. But how can I connect these to form a query so that the rows goes on inserted one after other.

      Thanks,
      Mashall
        • 1. Re: How to receive parameters from a form and insert values in db using servlet
          srhcan
          use an enumeration on request parameter names and loop through them to get values.
          • 2. Re: How to receive parameters from a form and insert values in db using servlet
            gimbal2
            Marshall141 wrote:
            My MAIN ISSUE IS WITH THE NUMBER OF COLUMNS THAT WOULD BE DYNAMIC AND THUS CANT RECEIVE THE PARAMETERS IN STATIC CODE.
            No need to shout!

            Your form may be dynamic, you still need SOMETHING that says "add X text fields", where X is a variable.

            Use that same "something" to read X values from the form. If you give the form fields a name that is easily calculated, say a name with a sequence number, its all too easy. Or alternatively give all the form fields the exact same name and retrieve all values at once using request.getParameterValues(). It depends on the requirements which path you would take, but it is certainly far from a problem that the number of form is dynamic.
            • 3. Re: How to receive parameters from a form and insert values in db using servlet
              939350
              Thank you for your help.

              I'm something close to it but this segment of code throws a NullPointerException Error. I counted number of rows and columns using the methods getColumnCount() and getColumnName(i).

              ResultSetMetaData md = res.getMetaData(); //Get meta data for the resultset
              int noofcolumns=md.getColumnCount();
              out.println("<br />Number of columns in table (including name and roll number) :::: "+noofcolumns+"<br />");

              for(int i=1;i<=noofcolumns;i++) // access column 1....n
              {
              String columnname = md.getColumnName(i); // get name of column 1....n
              out.println("<br />Current column name ::: "+columnname+"<br />"); //check if the name appear correct.
              String []columndata = request.getParameterValues(columnname); //Get raw value in array

              for(int j=1;j<=rows;j++) // here rows is number of rows in each column
              {
              out.println("To be inserted: <b>"+columndata[j]+"</b> in Row ::: "+j+"<br />");
              //The line above thows null pointer exception.
              }
              }