gpt4 book ai didi

java - 当没有值在 html post 上传递到 Java Servlet 时将值设置为 0

转载 作者:搜寻专家 更新时间:2023-10-30 20:27:38 25 4
gpt4 key购买 nike

得到这段处理一些参数并将其写入数据库的代码:

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import java.sql.*;

public class QueryServlet extends HttpServlet {

@Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
{
String instId = req.getParameter("instId");
String cartId = req.getParameter("cartId");
String desc = req.getParameter("desc");
String cost = req.getParameter("cost");
String amount = req.getParameter("amount");
String currency = req.getParameter("currency");
String name = req.getParameter("name");
String transId = req.getParameter("transId");
String transStatus = req.getParameter("transStatus");
String transTime = req.getParameter("transTime");
String cardType = req.getParameter("cardType");
Connection conn = null;
PrintWriter out = res.getWriter();
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "root", "root");

String sqlStr = "insert into orderdetails "
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
stmt.setString(1, transId);
stmt.setString(2, instId);
stmt.setString(3, cartId);
stmt.setString(4, desc);
stmt.setString(5, cost);
stmt.setString(6, amount);
stmt.setString(7, currency);
stmt.setString(8, name);
stmt.setString(9, transStatus);
stmt.setString(10, transTime);
stmt.setString(11, cardType);
int updateCount = stmt.executeUpdate();
for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
String paramName = en.nextElement();
String paramValue = req.getParameter(paramName);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}

如果我在发布消息中传递所有参数,数据库就会更新。但是,如果我不传递其中一个参数,则不会向数据库写入任何内容。

你能帮我修改一下吗,如果一个参数不在发布消息中,它会在数据库中将该值设置为 0 或 null?

感谢迄今为止的所有帮助。

最佳答案

对于 String 类型的参数值,如果参数不在 POST 方法中,您可以设置空字符串或 null。尝试对每个字段值使用 三元 运算符,

  String instId = req.getParameter("instId") == null ? "" : req.getParameter("instId");

关于java - 当没有值在 html post 上传递到 Java Servlet 时将值设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23672796/

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