简体   繁体   中英

getParameterValues sometimes return null from hidden input

I have a website and I used form inside .jsp file when the user submit the form the action goes to servlet which insert data into database. sometimes it works fine without any problem and sometimes even the user submitted the form nothing inserted in the database and throws NullPointerException in line 154.

org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for 
servlet [NewServlet] in context with path [] threw exception
java.lang.NullPointerException
at org.example.test.NewServlet.processRequest(NewServlet.java:154)

index.jsp

<form action="NewServlet" method="post">
<table>
<tbody>
<tr>
<td><sql:query dataSource="${snapshot}" var="subjects1">
SELECT * FROM glf2 ORDER BY RAND()LIMIT 1
</sql:query>
<c:set var="comments_m1" value="${subjects1.rows[0]}"/>
${comments_m1.comment_message} 
</td>
</tr>
<tr>
<td><sql:query dataSource="${snapshot}" var="subjects2">
SELECT * FROM egy ORDER BY RAND()LIMIT 1
</sql:query>
<c:set var="comments_m2" value="${subjects2.rows[0]}"/>
${comments_m2.comment_message} 
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="com" value="${comments_m1.comment_message}"/>
<input type="hidden" name="com" value="${comments_m2.comment_message}"/>
<input type="submit" value="submit">  
</form> 

the comment message selected from database and shown in the screen and the user need to select some options, then the comment message and the user options send to servelt to be inserted into database table.

newservlet.java acording to the log file the problem in getParametersValues

try (PrintWriter out = resp.getWriter()) {
comment1= req.getParameterValues("com");
for(int z=0; z<comment1.length;z++)
comment[z] = new String(comment1[z].getBytes("ISO-8859-1"),"UTF-8"); 

Any one could advice me please how to solve the problem.

Your queries aren't necessarily return a record with comment_message is not null.

So, for example, you may have to add a null check.

if (comment1 != null) {
    for (int z=0; z<comment1.length;z++)
    comment[z] = new String(comment1[z].getBytes("ISO-8859-1"),"UTF-8"); 
}

Put a check for Null from the value of the parameter before insertion,

boolean comBool = comment1.equals("") || comment1.length<0 ;
if(!comBool){
       //Do the insertion into database
}else{
//the value from entered field is null
}

This will solve your NullPointerException

You are actually using same name for both the input tag in form, because of that the compiler might be getting confused about which value to get.

You should check naming both input tags different. It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM