java JSP搜索栏功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29724738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:47:44  来源:igfitidea点击:

JSP search bar function

javahtmljsptomcat

提问by coder4lyf

I'm trying to make a web interface using JSP and tomcat. I have a table of students and their information, and I want the user to be able to search for a student and then I want to display all of that student's information (in a table). So far I have displayed the entire student table and created a search box, but now I am at a loss of what to do when the user clicks "search". I'm thinking of creating a function to search the database but I'm not sure how to do this because I'm new to JSP. How do I call the function? Here is my code thus far:

我正在尝试使用 JSP 和 tomcat 制作一个 Web 界面。我有一张学生及其信息的表格,我希望用户能够搜索学生,然后我想显示该学生的所有信息(在表格中)。到目前为止,我已经显示了整个学生表并创建了一个搜索框,但是现在当用户单击“搜索”时我不知道该怎么做。我正在考虑创建一个函数来搜索数据库,但我不确定如何执行此操作,因为我是 JSP 的新手。如何调用函数?到目前为止,这是我的代码:

<%@ page import="java.sql.*" %>

<%
String connectionURL =
"jdbc:postgresql://cop4715-postgresql.ucf.edu:8472/******?user=*******&password=******";

Connection connection = null;
Statement statement = null;
ResultSet rs = null;
%>
<html><body>
<h1>Student Table</h1>
<table border = "2">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Birthday</th>
            <th>Address</th>
            <th>Email</th>
            <th>Level</th>
        </tr>
    </thead>
<%
Class.forName("org.postgresql.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL);
statement = connection.createStatement();
rs = statement.executeQuery("SELECT * FROM students");
ResultSetMetaData metadata = rs.getMetaData();

 while (rs.next()) { %>
    <tr>
    <%
    for(int i = 1; i <= metadata.getColumnCount(); i++){ %>
        <td>
        <%=rs.getString(i)%>
        </td>
    <%
       }
    %>
    </tr>
<%
 }
%>
</table>
<%
rs.close();
%>
<br>

<form action = test()>
Search By Name: <input type="text" name="Name">
<input type ="submit" value="Search">
</form>



</body></html>

采纳答案by Ravi Thapliyal

Your train of thought on calling a function is not correct. Why? Because, a function would invoke JavaScript which executes at client-side while you want to retrieve data from a database which should happen at server-side just like you're doing it already using <% scriptlets %>*see below

你调用函数的思路不对。为什么?因为,一个函数会调用在客户端执行的 JavaScript,而您想从数据库中检索数据,这应该发生在服务器端,就像您已经在使用<% scriptlets %>* 见下文一样

<form action = test()>

The simplest way to implement this would be to self-submit the JSP i.e. the HTML form would post the data to the same JSP it has been defined in. You do this by just removing the actionattribute altogether.

实现这一点的最简单方法是自行提交 JSP,即 HTML 表单将数据发布到定义它的同一个 JSP。您只需action完全删除该属性即可。

Now, to differentiate whether the JSP should retrieve the data about all the students or a specific one, you would change the code to check for the Namerequest attribute as follows.

现在,为了区分 JSP 应该检索有关所有学生的数据还是特定学生的数据,您将更改代码以检查Name请求属性,如下所示。

String name = request.getParameter("Name");
if (name != null && name.length() > 0) {
    rs = statement.executeQuery("SELECT * FROM students WHERE Name = '" + name + "'");
} else {
    rs = statement.executeQuery("SELECT * FROM students");
}

Since, the query above has now become parameterized, the use of PreparedStatementis highly recommended now.

因为,上面的查询现在已经参数化了,所以PreparedStatement现在强烈推荐使用。

if (name != null && name.length() > 0) {
    PreparedStatement ps = connection.prepareStatement(
                           "SELECT * FROM students WHERE Name = ?"); // ? = placeholder
    ps.setString(1, name); // Bind the value to the placeholder
    rs = ps.executeQuery(); // Execute the prepared statement and fetch results
}

A PreparedStatementhelps avoid SQL injection attacks as well as does away with the clunky and error-prone string concatenation.

APreparedStatement有助于避免 SQL 注入攻击以及消除笨重且容易出错的字符串连接。

*Scrptletshave been deprecated long ago. A much better approach would be to put a Servletin-between that handles all the JDBC code, populates the requestobject with the results and then forwardsto a JSP that then only handles how the results are presented to the user.

* Scrptlets很久以前就被弃用了。更好的方法是在中间放置一个Servlet,它处理所有 JDBC 代码,request用结果填充对象,然后转发到 JSP,然后只处理如何将结果呈现给用户。

回答by Ravi Thapliyal

Rachelle, you can refer to an example that displays employee details as output from JSP. This example makes use of servlet, jsp, jdbc, dao and properties file wherever appropriate. You can go thru this example and later modify to display student details from your database. Example link - http://theopentutorials.com/tutorials/java/design-patterns/post-redirect-get-prg-pattern-in-servlet-jsp/Going thru above tutorial you will be able to setup your code thru eclipse.

Rachelle,您可以参考一个示例,该示例将员工详细信息显示为 JSP 的输出。该示例在适当的地方使用了 servlet、jsp、jdbc、dao 和属性文件。您可以浏览此示例,然后进行修改以显示数据库中的学生详细信息。示例链接 - http://theopentutorials.com/tutorials/java/design-patterns/post-redirect-get-prg-pattern-in-servlet-jsp/通过以上教程,您将能够通过 Eclipse 设置您的代码。

回答by Annamalai Thangaraj

There is error in your form action.

您的表单操作有误。

<form action = test()>
Search By Name: <input type="text" name="Name">
<input type ="submit" value="Search">
</form>

Your form action must point to another JSP or Servlet

您的表单操作必须指向另一个 JSP 或 Servlet

<html>
<body>
<form action="student.jsp" method="GET">
Search By Name: <input type="text" name="Name">
    <input type ="submit" value="Search"></form>
</body>
</html>

In student.jsp

在 student.jsp 中

  • Add the database codes it will return all the student values.

    If you like to filter the value based on search input then get input value from form submit using <% String name = (String)request.getParameter("Name")%>and apply the value in rs = statement.executeQuery("SELECT * FROM students WHERE your condition");

  • 添加数据库代码,它将返回所有学生值。

    如果您想根据搜索输入过滤值,则从表单提交中获取输入值<% String name = (String)request.getParameter("Name")%>并应用该值rs = statement.executeQuery("SELECT * FROM students WHERE your condition");