gpt4 book ai didi

java - 为什么文本字段总是返回 null?

转载 作者:行者123 更新时间:2023-12-01 19:05:12 24 4
gpt4 key购买 nike

以下代码片段向数据库提交标题。填写完文本后,我单击“提交”,但令我惊讶的是,表格中总是显示 null。我已经提到了下面的servlet代码和html设计:

<form method="post" action="Handler" enctype="multipart/form-data">
<table>
<tr>
<td> <strong> Leave a caption </strong> </td>
<td> <input type="text" name="caption box" size="40" /></td>
</tr>

<tr colspan="2">
<td> <input type="submit" value="submit caption"/> </td>
</tr>
</table>
</form>

Servlet

String caption = request.getParameter("caption box"); // get the caption from the caption field
HandleCaption hc = new HandleCaption(caption,emailOfTheUser,fileName);
hc.SubmitCaptionToTheDatabase();

类别

public class HandleCaption {
private String Caption = null;
private String UserEmail = null;
private String NameOfThe = null;

public HandleCaption(String caption,String email,String filename) {
Caption = caption;
UserEmail = email;
NameOfThe = filename;
}

public void SubmitCaptionToTheDatabase() {
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/DS");
Connection connection = ds.getConnection();
String sqlQuery = "insert into CAPTIONS values ('" + UserEmail + "','" + NameOfThe + "','" + Caption + "')";
PreparedStatement statement = connection.prepareStatement(sqlQuery);
int x = statement.executeUpdate();
}catch(Exception exc) {
exc.printStackTrace();
}
}

}

我尝试打印 servlet 中文本字段返回的值,甚至打印 null。为什么文本字段返回 null ?

最佳答案

我不知道为什么会发生这种情况,但在我身上发生过一两次..在您的 Caption 类 Handle Caption 中,将其声明为

private String Caption = "";
private String UserEmail = "";
private String NameOfThe = "";

我知道这看起来像是问题的愚蠢答案,因为在构造函数中您实际上指的是传递的值,但我经历过这一点,这就是我的解决方案。请尝试回复!!

更新:很抱歉错误地解决了这个问题这是由于编码类型造成的,将了解其发生的原因..但只需删除编码类型即可工作..尝试了示例代码

更新: 3.0 版之前的 Servlet API 默认情况下确实不支持 multipart/form-data 编码请求。 Servlet API 默认使用 application/x-www-form-urlencoded 编码来解析参数。当使用不同的编码时,request.getParameter()调用将全部返回null。

关于java - 为什么文本字段总是返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10345941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com