如何使用Java Servlet输出SQL查询的结果

时间:2019-01-17 15:26:20

标签: java html jsp web servlets

我正在尝试对我的Web应用程序实施搜索功能,该功能允许用户搜索产品数据库。我尝试使用以下方法执行此操作:

该网页的.jsp文件首先列出所有产品(productSearch.jsp):

<%@page import="java.sql.Connection"%>
<%@page import="databaseManagement.DBConnection"%>
<%@page import="java.sql.ResultSet" %>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Search Our Products</title>
</head>
<body>
<form method="post">
        Search:<input type="text" name="Search"> 
        <input type="submit" value="Go">

<table border="2">
<tr>
<td>ID</td>
<td>NAME</td>
<td>DESCRIPTION</td>
<td>PRICE</td>
</tr>
<%

try
{
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products");
ResultSet rs = ps.executeQuery();
while(rs.next())
{

%>
    <tr>
        <td><%=rs.getInt("ID") %></td>
        <td><%=rs.getString("NAME") %></td>
        <td><%=rs.getString("DESCRIPTION") %></td>
        <td><%=rs.getString("PRICE") %></td>
    </tr>
        <%
}
%>
    </table>
    <%
    rs.close();
    con.close();
    }
catch(Exception e)
{
    e.printStackTrace();
    }

%>
</form>
</body>
</html>

获取用户输入并运行查询的类(ProductSearch.java):

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import databaseManagement.DBConnection;

@WebServlet("/ProductSearch")
public class ProductSearch extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ProductSearch() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub

        String searchTerm = request.getParameter("Search");

        try {
            DBConnection db = new DBConnection();
            Connection con = db.getConnection();
            PreparedStatement ps = con.prepareStatement("select * from products where name like %?%");
            ps.setString(1, searchTerm);
            ResultSet rs = ps.executeQuery();
            return;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

最后是一个类,用于处理与数据库的连接(DBConnection):

package databaseManagement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

    public Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // TODO: finish
            //CHANGE USERNAME AND PASSWORD WHEN IMPLIMENTING ON VM
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/applicationdata", "root", "safepassword");
            return con;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
}

我现在遇到的问题是,我不确定如何获取从ProductSearch类获得的结果并将其显示在productSearch.jsp页面中。

我对此很陌生,所以如果我犯了任何明显的错误,我深表歉意。任何帮助,我们将不胜感激:)

1 个答案:

答案 0 :(得分:1)

首先,创建一个类,在该类中声明要返回的所有值,并获取/设置该变量。 即假设变量用户。

import java.util.*;

public class Abc{

    private String user;
    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }



    public Abc(String user) {
        this.user = user;

    }
}

下一步,在您的ProductSearch.java文件中输入以下代码:

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub

        String searchTerm = request.getParameter("Search");
 ArrayList<Abc> ab= new ArrayList();


try
  {

String sql1 ="select * from products where name like %?%";

PreparedStatement ps = conn.prepareStatement(sql1);

ps.setString(1,searchTerm);

resultSet = ps.executeQuery();
while(resultSet.next())
{

   Abc b=new Abc();
    b.setUser(resultSet.getString("user"));
     ab.add(b);

 }

request.setAttribute("r1", ab);      
request.getRequestDispatcher("productSearch.jsp").forward(request, response);


   }

catch(Exception s2)
{
   s2.printStackTrace();
}

    }
}

最后使用 jstl

将结果打印回您的 productSearch.jsp 页面
<!-- this is use because we use jstl tag-->
    <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>

    <table align="center"  border="1">


    <tr bgcolor="#d9ac26">

    <td><b>search</b></td>


    </tr>
  <!--Here we are printing result-->
    <c:forEach var="book" items="${r1}">

        <tr bgcolor="">

            <td>${book.user}</td>
        </tr> 
    </c:forEach>
    </table>

希望这对您有所帮助。根据您的要求进行必要的更改。这不是完整的代码。