【问题标题】:Integer parsing in a servletservlet 中的整数解析
【发布时间】:2014-09-08 15:17:24
【问题描述】:

这只是在员工数据库中使用员工 ID 进行的简单查询,其中 ID 是一个整数值。我做了以下操作来解析整数 ID 的值。

     String value = request.getParameter("Employee_ID");
     int id = Integer.parseInt(value);
  // Step 3: Execute a SQL SELECT query
     String sqlStr = "select * from Employee where ID = id ";

但它给了我以下错误:

Multiple markers at this line
    - Line breakpoint:QueryServlet [line: 45] - doGet(HttpServletRequest, 
     HttpServletResponse)
    - The value of the local variable id is not used

我的html文件:

<html>
<head>
  <title>Employee Details</title>
</head>
<body>
  <h2>Employee Details</h2>
  <form method="get" action="http://localhost:9999/abcd/query">
    <b>Select Employee ID:</b>
    <input type="text" name="Employee_ID" value="ex101">

    <input type="submit" value="Search">
  </form>
</body>
</html>

【问题讨论】:

  • 您的问题有什么错误?一个是断点,另一个是警告。我在您的问题中找不到任何错误
  • @msrd0 问题是 OP 想要/需要使用这个 id 变量,但它无法做到。

标签: java servlets


【解决方案1】:

问题是您没有在代码中使用id 变量。这是一个文字字符串:

"select * from Employee where ID = id "
                                   ^ here id is part of the string, it's not the id variable

实现这项工作的天真的方法是将变量连接到字符串

String sqlStr = "select * from Employee where ID = " + id;

但是这不是创建动态查询的正确方法。您应该使用PreparedStatement 并相应地传递参数。代码应该是这样的:

//placeholder for id variable
String sqlStr = "select * from Employee where ID = ?";
//retrieve the connection to database
Connection con = ...;
//prepare the statement from the connection
PreparedStatement pstmt = con.prepareStatement(sqlStr);
//pass the id as parameter to the prepared statement
pstmt.setInt(id);
//execute the statement
ResultSet rs = pstmt.execute(); 

另外,请确保将您的代码分层。所有这些与数据库连接和 SQL 执行相关的代码都属于 DAO 层。

更多信息:

【讨论】:

    【解决方案2】:

    改变

    String sqlStr = "select * from Employee where ID = id ";
    

    通过

    String sqlStr = "select * from Employee where ID = "+ id ;
    

    但是,您应该阅读有关 SQL Injection 的内容

    【讨论】:

    • 这在技术上是正确的,但这不是正确的做法。
    • 不仅是 SQL 注入,还有代码可维护性和 SQL 语句执行性能。
    【解决方案3】:

    以下应该可以:

    String sqlStr = "select * from Employee where ID ="+id;
    

    您必须将 id 连接到您编写的查询字符串。

    编辑如cmets中所说,最好使用参数化查询来防止sql注入。

    【讨论】:

    • 类似于@Andres 的回答,这在技术上是正确的,但这不是正确的做法。
    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多