0

I am writing a simple JSP code that should take a textbox value, form a sql, execute and return the result to another text field. I get an empty result. The following is my code.

The driver is working and value is set if no condition in the statement like selecting first name if rownum<1 for example, so I am sure it is registered fine.

<html>
<head>
<title>Holiday Master</title>
</head>
<body>
<%@ page import = "java.sql.*" %> 
<div>

        <input id="input1" name="Text1" type="text"><input id="input2" name="Text2" type="text"><input name="Button1" onclick="get_data()" type="button" value="button"></div>
<script>
function get_data()
{
<%
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr");
    Statement stmt  = conn.createStatement();
    String sql2 = request.getParameter("input1"); 
    String sql="select last_name from employees where first_name ='"+sql2+"'";
    ResultSet rs = stmt.executeQuery(sql);
    try
    {
    if(rs!=null)
    {

    while(rs.next())
    {
    %>

   document.getElementById("input2").value="<%=rs.getString("last_name")%>";    

    <%
    }
    }        
    }
    catch(SQLException e)
    {
        e.printStackTrace();
    }
    stmt.close();
    rs.close();
    conn.close();
    stmt=null;
    rs=null;
    conn=null;
    %>



}

</script>
</body>
</html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.

Jozef Chocholacek
  • 2,874
  • 2
  • 20
  • 25
  • So as i understand from your reply that document.getElementById("input2").value<%=rs.getString("last_name")%>"; will not understand what rs means because it executes server side ? so how do you suggest i fill the text box with the query result ? – Ahmed Sharaf Sep 03 '16 at 12:28
  • The problem begins even earlier, the `sql2` string is `null` on the first call of the page, so (IMHO) the whole query should fail. (Btw. `request.getParameter(String parameterName)` expects `name` of the input attribute as `parameterName`, not its `id`.) You need AJAX for what you want to achieve, see e.g. [this answer](http://stackoverflow.com/a/4113258/3511123) for a brief introduction. – Jozef Chocholacek Sep 05 '16 at 06:19
  • And btw. **never ever** compose SQL statements by concatenating the strings. Learn to use `PreparedStatement`s. Reason: [SQL Injection](http://www.royabubakar.com/blog/2014/01/19/sql-injection-in-java-web-application/) - i.e. what if I enter into your first input field something like `'; drop table employees; --`? ;-) – Jozef Chocholacek Sep 05 '16 at 06:23