简体   繁体   English

Java Servlet处理html发布数据

[英]Java Servlet to handle html post data

I am trying to create a servlet on a specific URL to handle a HTML post from another server and receive all parameters and their values and insert them into a database. 我正在尝试在特定的URL上创建一个servlet,以处理来自另一台服务器的HTML帖子,并接收所有参数及其值并将其插入数据库中。

Got to this code so far: 到目前为止,已获得以下代码:

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.getParameterValues("instId")[0];
    String cartId=req.getParameterValues("cartId")[0];
    String desc=req.getParameterValues("desc")[0];
    String cost=req.getParameterValues("cost")[0];
    String amount=req.getParameterValues("amount")[0];
    String currency=req.getParameterValues("currency")[0];
    String name=req.getParameterValues("name")[0];
    String transId=req.getParameterValues("transId")[0];
    String transStatus=req.getParameterValues("transStatus")[0];
    String transTime=req.getParameterValues("transTime")[0];
    String cardType=req.getParameterValues("cardType")[0];
    Connection conn = null;
    Statement stmt = null;
    PrintWriter out=res.getWriter();
    try
    {
        conn = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/orders", "root", "root");
        stmt = conn.createStatement();

        String sqlStr = "insert into orderdetails values('"+transId+"','"+instId+"','"+cartId+"','"+desc+"'"+cost+"','"+amount+"','"+currency+"','"+name+"','"+transStatus+"','"+transTime+"','"+cardType+")";

        out.println("<html><head><title>Query Response</title></head><body>");
        out.println("<h3>Thank you for your query.</h3>");
        out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
        ResultSet rset = stmt.executeQuery(sqlStr);  // Send the query to the server
        }
        catch(SQLException ex)
        {
          ex.printStackTrace();       
        }
    }
}

I have tried some changes to it and I allways get errors. 我尝试对其进行一些更改,但始终会出错。

Could you give me a hand? 你能帮我一下吗?

Btw, I have very little knowledge of java, been trying to "hack my way" into doing this from other people examples and from going trough guides. 顺便说一句,我对Java的了解很少,一直在尝试通过其他人的例子和低谷指南来“破解我的方式”。

Thanks in advance 提前致谢


Edit: I can't log into my dev machine atm as it is having problems and is down, it had something to do with Null pointer or Null value, can't give the exact error atm, will update as soon as possible. 编辑:我无法登录到我的开发机器atm,因为它有问题并且已关闭,它与Null指针或Null值有关,无法给出确切的错误atm,将尽快更新。

I am also aware of the SQL injection with the code, just trying to test it first and make it work and change the code before I set it live. 我还知道带有代码的SQL注入,只是尝试先对其进行测试,使其能够正常工作,然后在我将其设置为有效之前更改代码。

There where some quote/comma hickups and it should be exevcuteUpdate. 那里有一些引号/逗号组织,应该是exevcuteUpdate。 However it is important to use a PreparedStatement: 但是,使用PreparedStatement很重要:

  • easier on the SQL string, escapes special chars in the strings (like apostrophe) 在SQL字符串上更容易,在字符串中转义了特殊字符(例如撇号)
  • you can used typed parameters, like BigDecimal below 您可以使用类型化的参数,例如下面的BigDecimal
  • security SQL injection 安全SQL注入

I used the try-with-resources syntax to close the stmt . 我使用try-with-resources语法关闭了stmt

    String instId = req.getParameter("instId");
    String cartId = req.getParameter("cartId");
    String desc = req.getParameter("desc");
    String cost = req.getParameter("cost");
    BigDecimal amount = new BigDecimal(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;
    Statement stmt = 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.setBigDecimal(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();

            out.println("<html><head><title>Query Response</title></head><body>");
            out.println("<h3>Thank you for your query. " + updateCount + " record(s) updated.</h3>");
            out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
            for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
                String paramName = en.nextElement();
                String paramValue = req.getParameter(paramName);
                out.println("<p>" + paramName + ": " + paramValue + "</p>"); // Echo for debugging
            }
        } // Does stmt.close()
    } catch (SQLException ex) {
        ex.printStackTrace();
    }

For inserting or updating or deleting use executeUpdate() but you are using executeQuery() 对于插入,更新或删除,请使用executeUpdate(),但您正在使用executeQuery()

and executeUpdate method returns an integer(No.of rows affected) so change 并且executeUpdate方法返回一个整数(受影响的行数),因此更改

ResultSet rset = stmt.executeQuery(sqlStr);

to

int update= stmt.executeUpdate(sqlStr);

Also prefer to use PreparedStatement 还喜欢使用PreparedStatement

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

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