1

使用 servlet 将动态文本输入值插入 mysql

我有一个表单,我在其中使用 javascript 添加其他文本字段。我如何将这些值存储在数据库中?在我的 servlet 中,当我尝试 request.getParameterValues() 时,我得到 java.lang.NullPointerException

这是我的表格

<form method="POST" action="ServletDB" name="submissionForm" id="submissionForm" onsubmit="return validate()">
 <div id="authors">
   <b>Author 1</b><br/>
   <b>Name:    </b><input type='text' name='name[]'><br/>
   <b>Surname:</b><input type='text' name='surName[]'><br/>
   <b>Email:</b><input type='text' name='eMail[]'><br/>
   <b>Affiliations:</b><textarea rows='4' cols='50' name='affiliations[]'></textarea>   <br/>

 </div>
 <input type="button" value="Add Author" onClick="addAuth('authors');">

这是我的 javascript

var authCount = 1;

函数 addAuth(authDiv){

      var newAuth = document.createElement('div');
      newAuth.innerHTML = "Author " + (authCount + 1) + "<br/> <b>Name:    </b><input type='text' name='name[]'><br/><b>Surname:</b><input type='text' name='surName[]'><br/><b>Email:</b><input type='text' name='eMail[]'><br/><b>Affiliations:</b><textarea rows='4' cols='50' name='affiliations[]'></textarea><br/>";
      document.getElementById(authDiv).appendChild(newAuth);
      authCount++;
 }

在 servlet 的 DoPost 中的实现:

String[] name = req.getParameterValues("name");
          String[] surName = req.getParameterValues("surName");
          String[] eMail = req.getParameterValues("eMail");
          String[] affiliations = req.getParameterValues("affiliations");

          int authCount = name.length;

          boolean rs1 = true;
          try {
          // Load the database driver
          Class.forName("org.gjt.mm.mysql.Driver");
          // Get a Connection to the database
          connection = DriverManager.getConnection
          (connectionURL, "root",""); 
          //Add the data into the database
          for(int i=0;i<authCount;i++){
          String sql ="INSERT INTO mytable.author(articleld,Surname,FirstName,Email,) VALUES (?,?,?,?)";
          PreparedStatement pst = 
          connection.prepareStatement(sql);

          pst.setString(1,surName[i]);
          pst.setString(3,name[i]);
          pst.setString(4,eMail[i]);

          out.println(pst);
          rs1=pst.execute();
          pst.close();
          }
4

0 回答 0