SQL 使用文本框搜索和按钮查询 jsp 文件

SQL Query on jsp file using Text Box Search and button

我在搜索中遇到困难(选择sql语句)。如何将我在文本框中输入的值放入sql查询中 这样我就可以根据我插入的值搜索部门名称。

我不知道这个 "SELECT * FROM department where department_name ='"%search%"'"

的正确查询

下面是我的 jsp 文件:

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
 /head>


 <body>

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

 <sql:query dataSource="${snapshot}" var="sql">
SELECT * from department;
<!-- SELECT * FROM department where department_name ='"%search%"'-->
</sql:query>

  <FORM NAME="form1" METHOD="POST">
  <input type="text" name="search"/>
   <INPUT TYPE="BUTTON" VALUE="Button 1">
   </FORM><br>


    <table border=1>
        <thead>
            <tr>
                <th>department Id</th>
                <th>department Name</th>

                <th colspan=1>Action</th>
            </tr>
        </thead>
        <tbody>
        <c:forEach var="user" items="${sql.rows}">
                <tr>
                    <td><c:out value="${user.department_id}" /></td>
                    <td><c:out value="${user.department_name}" /></td>
                  </tr>
            </c:forEach>
        </tbody>
    </table>


</body>
</html>

首先,插入参数给你SQL查询

<sql:query dataSource="${snapshot}" var="sql">
SELECT * from department WHERE department_name = <%= request.getParameter("query") %>;
</sql:query>

将方法更改为 METHOD="GET" 和

<input type="text" name="query"/>
<INPUT TYPE="submit">

当你点击按钮时,url就像

http://hostname.com/mywebapp/mypage.jsp?query=John+Smith