Question

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.

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.

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.

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.

Was it helpful?

Solution

There where some quote/comma hickups and it should be exevcuteUpdate. However it is important to use a PreparedStatement:

  • easier on the SQL string, escapes special chars in the strings (like apostrophe)
  • you can used typed parameters, like BigDecimal below
  • security SQL injection

I used the try-with-resources syntax to close the 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();
    }

OTHER TIPS

For inserting or updating or deleting use executeUpdate() but you are using executeQuery()

and executeUpdate method returns an integer(No.of rows affected) so change

ResultSet rset = stmt.executeQuery(sqlStr);

to

int update= stmt.executeUpdate(sqlStr);

Also prefer to use PreparedStatement

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top