繁体   English   中英

getParameterValues有时会从隐藏的输入中返回null

[英]getParameterValues sometimes return null from hidden input

我有一个网站,当用户提交表单时,我在.jsp文件中使用了表单,该动作将移至将数据插入数据库的servlet。 有时它工作正常,没有任何问题,有时甚至用户提交的表单都没有插入数据库,并在第154行抛出NullPointerException。

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> 

从数据库中选择并在屏幕上显示的注释消息,用户需要选择一些选项,然后注释消息和用户选项发送到servelt,以插入数据库表中。

根据日志文件的newservlet.java,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"); 

任何人都可以建议我如何解决该问题。

您的查询不一定返回带有comment_message不为null的记录。

因此,例如,您可能必须添加一个空检查。

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

插入前,请检查参数值是否为Null,

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

这将解决您的NullPointerException

实际上,您为表单中的两个输入标签都使用了相同的名称,因为编译器可能会混淆要获取的值。

您应该检查两个输入标签的命名是否不同。 它应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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