0

I am trying to read the input by the user as soon as he clicks on a button. But unfortunately the request.getParamater() is always returning a null value. Can someone please help me I have been hours Trying to sort this out :(

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<html> 
<head>

    <script language="javascript">



        function add()
        {
        <%
    Integer quantity = 500;
    Integer code = 1000;

    //String codes = request.getParameter("code");
    String codes = (String) request.getParameter("code");
    String quanti = (String) request.getParameter("quantity");

    if (codes != null && quanti != null) {
        quantity = Integer.parseInt(quanti);
        code = Integer.parseInt(codes);
    }

    out.println(code);
    out.println(quantity);

    String connectionURL = "jdbc:mysql://localhost:3306/products";

    Connection connection = null;

    PreparedStatement pstatement = null;

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    int updateQuery = 0;

    // check if the text box is empty
    if (code != null && quantity != null) {
        // check if the text box having only blank spaces
        if (codes != "" && quanti != "") {
            try {
                /* Create a connection by using getConnection()
                 method that takes parameters of string type 
                 connection url, user name and password to connect 
                 to database. */
                connection = DriverManager.getConnection(connectionURL, "root", "170293m");
                // sql query to insert values in the secified table.
                String queryString = "INSERT INTO sales (code, quantity, price, name) VALUES (?, ?, ?, ?)";
                /* createStatement() is used for create statement
                 object that is used for 
                 sending sql statements to the specified database. */
                pstatement = connection.prepareStatement(queryString);
                pstatement.setInt(1, code);
                pstatement.setInt(2, quantity);
                pstatement.setDouble(3, 50);
                pstatement.setString(4, "aw ras");
                updateQuery = pstatement.executeUpdate();
                if (updateQuery != 0) {
                    out.println("Error in query");
                }
            } catch (Exception ex) {
                out.println("Unable to connect to batabase.");

            } finally {
                // close all the connections.
                pstatement.close();
                connection.close();
        }
        }
    }%>
            print();
        }

        function remove()
        {

        }
    </script>
    <title>BestWholesaler LTd.</title>
</head> 
<body>
    <h1>Welcome to BestWholesaler Ltd. Online Ordering</h1>
    <h2>Items Currently in Stock</h2>

    <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
                       url="jdbc:mysql://localhost:3306/products"
                       user="root"  password="170293m"/>

    <sql:query dataSource="${snapshot}" var="result">
        SELECT Name, Code, PricePU, Quantity from productinfo;
    </sql:query>

    <table border="1" width="100%">
        <tr>
        <th>Name</th>
        <th>Code</th>
        <th>Price/Unit</th>
        <th>Quantity Available</th>
    </tr>
    <c:forEach var="row" items="${result.rows}">
        <tr>
        <td><c:out value="${row.Name}"/></td>
        <td><c:out value="${row.Code}"/></td>
        <td><c:out value="${row.PricePU}"/></td>
        <td><c:out value="${row.Quantity}"/></td>
    </tr>
</c:forEach>
</table>

<br>
<br>
Enter Code:     <input type="text" name="code" id="code" value="" />
<br>
Enter Quantity: <input type="text" name="quantity" id="quantity" value="" />
<input type="button" value="ADD" name="add" onclick="add()" />
<input type="button" value="REMOVE" name="remove" onclick="remove()" />

</body>

</html>
user987339
  • 10,519
  • 8
  • 40
  • 45
user3420231
  • 23
  • 1
  • 1
  • 5
  • request.getParameter() Returns the value of a request parameter as a String, or null if the parameter does not exist. where do you have `code` and `quantity` specified? – Sionnach733 Mar 14 '14 at 14:25
  • they are specified in the last part of the body i.e. Enter Code: etc... – user3420231 Mar 14 '14 at 14:36

3 Answers3

0

You are not using any <form> HTML tag. All input tag must go inside it, and the button click should do a submit of the form.

By the way, you are mixing Javascrit client code and Java server code in a way that cannot work, you have different rendering timings.

On this example, assuming you are wanting to have a unique component both for client-side and for server-side, as you are doing, you can add the following to your JSP. For commodity I'm going to separate client-side and server-side logics.

Client side

<script>
  function flagLoaded(){
     document.forms[0]["loaded"].value = "true";
  }
</script>

<form name="input" action="myself.jsp" method="get" onsubmit="flagLoaded()">
  <!-- put here all your client-side's inputs -->

  <!-- ... TODO ... -->

  <input type="hidden" name="loaded" value="false">
    <input type="submit" value="Submit">
</form>

Server side

<%
  if("true".equals(request.getParameter("loaded"))){
      //TODO
      /*
         Do here server-side logic...
      */
  }
%>
robermann
  • 1,722
  • 10
  • 19
0

The main reason behind this is you are using the javascript i.e <script language="javascript"> and you are trying to run the server side code inside it . you must close the javascript by using </script> and then try to run the server side code..

iamsuman
  • 1,413
  • 19
  • 32
0

You don't need javascript here, go with basic html form tag to submit the details. Also don't use scriplets as you are already aware of jstl. Note below code is only implemented for add, you need to write your code for remove.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

    <sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/products" user="root" password="170293m" />
    <title>BestWholesaler LTd.</title>
    <style>
      .error {
        color: red;
      }
    </style>

    <body>
      <h1>Welcome to BestWholesaler Ltd. Online Ordering</h1>
      <h2>Items Currently in Stock</h2>

      <!-- add button was clicked -->
      <c:if test="${null != param.add}">
        <c:catch var="error">
          <sql:update dataSource="${snapshot}" scope="page" var="result">
            INSERT INTO sales (code, quantity, price, name) VALUES (?, ?, ?, ?)
            <sql:param value="${param.code}" />
            <sql:param value="${param.quantity}" />
            <sql:param value="50" />
            <sql:param value="aw ras" />
          </sql:update>
        </c:catch>
      </c:if>

      <!-- error occured -->
      <c:if test="${null != error}">
        <div class='error'>
          Failed to save stock details
        </div>
      </c:if>

      <c:catch var="error">
        <sql:query dataSource="${snapshot}" var="result">
          SELECT Name, Code, PricePU, Quantity from productinfo;
        </sql:query>
      </c:catch>

      <c:if test="${null != error}">
        <div class='error'>
          Failed to get stock details
        </div>
      </c:if>

      <c:if test="${null == error}">
        <table border="1" width="100%">
          <tr>
            <th>Name</th>
            <th>Code</th>
            <th>Price/Unit</th>
            <th>Quantity Available</th>
          </tr>
          <c:forEach var="row" items="${result.rows}">
            <tr>
              <td>
                <c:out value="${row.Name}" />
              </td>
              <td>
                <c:out value="${row.Code}" />
              </td>
              <td>
                <c:out value="${row.PricePU}" />
              </td>
              <td>
                <c:out value="${row.Quantity}" />
              </td>
            </tr>
          </c:forEach>
        </table>
      </c:if>

      <br/>
      <br/>
      <form method='post'> <!-- no action required, still you can give the same jsp file name -->
        Enter Code:
        <input type="text" name="code" />
        <br/>Enter Quantity:
        <input type="text" name="quantity" />
        <input type="submit" value="ADD" name="add" />
      </form>
    </body>