【问题标题】:Instead of returning the whole table, how can I just return the row they searched for?我怎样才能返回他们搜索的行,而不是返回整个表?
【发布时间】:2013-05-03 19:50:58
【问题描述】:

刚接触编程和这个网站。我当前的 .jsp 是

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page import="java.sql.*" 
         import="action.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"             "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Here is your videogame!</title>
</head>

<BODY>
    <H1>The Videogame Database Table </H1>

    <%
        Connection c = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/videogamesdb", "root", "password");

        //instantiating a SQL statement
        Statement statement = c.createStatement();
        String sql = "SELECT * FROM videogamedetails";
        ResultSet resultset = 
            statement.executeQuery(sql) ;
    %>

    <TABLE BORDER="1">
        <TR>
            <TH>Name</TH>
            <TH>Genre</TH>
            <TH>Developer</TH>
            <TH>Rating</TH>
        </TR>
        <% while(resultset.next()) {%>
        <TR>
            <TD> <%= resultset.getString("vidgameName") %></TD>
            <TD> <%= resultset.getString("vidgameGenre") %></TD>
            <TD> <%= resultset.getString("vidgameDev") %></TD>
            <TD> <%= resultset.getInt("vidgameRating") %></TD>
        </TR>
        <% } %>
    </TABLE>
</BODY>
</HTML>

我相当确定我需要使用“SELECT * FROM videogamedetails WHERE vidgameName = p_Name”,但我不确定如何让 p_Name 成为用户搜索的内容。谢谢!

【问题讨论】:

  • p_Name 的值应该在请求参数中。此外,最好不要发送游戏名称,而是发送 id。由于您正在学习,请正确并停止使用 scriptlet,这是非常不鼓励的,请参阅here 的解释。此外,这将是了解 MVC 模式和分层应用程序的绝佳机会。

标签: java mysql jsp search


【解决方案1】:

您想更改为 PreparedStatement,以便它可以接受参数。

PreparedStatement statement = c.prepareStatement("select * from videogamedetails where vidgamename = ?");
statement.setString(1, "nameOfVideoGame");

另外,还有两个一般提示:

  1. 最佳实践是在 JSP 中使用 EL/JSTL 而不是 scriptlet
  2. 最好将 Java 代码保留在 JSP 之外。在线搜索 MVC 以了解如何将两者分开。

【讨论】:

  • OP 的问题是关于如何在其 JSP 中获取此 nameOfVideoGame
  • 错过了。所以它会是 statement.setString(1, request.getParameter("searchParamName").
  • 也许,也许不是。我们甚至不确定 OP 是否将其作为请求参数传递,或者只是从 Servlet 中检索所有数据或他/她所做的任何事情。
【解决方案2】:

我不确定您如何将搜索参数 p_Name 传递给此 JSP。

一种方法是将 p_Name 设置为请求属性,从那里重定向到此页面,然后在此 jsp 上检索它。

  String p_Name = (String) request.getAttribute("someVariable");

使用准备好的语句将值传递给您的查询。

  PreparedStatement statement = c.prepareStatement("select * from videogamedetails where vidgamename = ?");
  statement.setString(1,  p_Name);

  rs = statement.executeQuery();

【讨论】:

  • 我不知道如何让 p_Name 成为用户搜索的内容你读了吗?如果是这样,您的回答中哪里谈到在 JSP 中检索 p_Name
猜你喜欢
  • 2016-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 2019-06-13
  • 1970-01-01
  • 2020-02-27
相关资源
最近更新 更多