java—使用servlet搜索数据库

mrwjdhj3  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(330)

我正在尝试使用servlet和jsp文件让用户通过电影数据库搜索他们想要的电影。我使用了一个下拉表让用户选择要搜索的内容,然后我给了他们一个输入字段来放入他们的搜索查询中。但是,我的servlet一直显示找不到,即使我知道值在数据库中。
高级搜索.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    import="java.sql.*"
    import="java.io.*"
    %>

<%@ include file = "constants.jsp" %>

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <title>Movie</title>
        <style>
            .affix {top: 0; width: 100%;}
            .affix + .container-fluid {padding-top: 50px;}
            .nav-wrapper {min-height: 50px;}
            #section1 {padding-top: 50px; min-height: 550px; background-color: #EFEFEF; border-bottom: 1px solid #D6D6D6;}
            #section2 {padding-top: 50px; min-height: 1000px; background-color: #EFEFEF; border-bottom: 1px solid #D6D6D6;}
            #section3 {padding-top: 20px; min-height: 400px; background-color: #EFEFEF; border-bottom: 1px solid #D6D6D6;}
            .add {width:600px;}
        </style>
        <script>
            //Smooth Scrolling
            $.fn.scrollBottom = function() { 
                return $(document).height() - this.scrollTop() - this.height(); 
            };
            window.onscroll = function() {myFunction()};
            $(document).ready(function(){
                $("a").on('click', function(event) {
                    if (this.hash !== "") {
                        event.preventDefault();
                        var hash = this.hash;
                        $('html, body').animate({
                            scrollTop: $(hash).offset().top
                        }, 400, function(){
                            window.location.hash = hash;
                        });
                    }
                });
            });
        </script>
    </head>
    <body>
        <%
        // Show username on page
        %>
        <%@ include file = "header.html" %>
        <div class="nav-wrapper">
            <nav id="site-navigation" class="container-fluid navbar navbar-inverse" data-spy="affix" data-offset-top="160" style="margin:auto;">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#top" style="font-size: 30px;"><b>Movie</b></a>
                </div>
                <ul class="nav navbar-nav">
                    <li><a href = "booking.jsp">Bookings</a>
                    <li><a href = "review.jsp">Reviews</a>
                    <li class="active"><a href="#top">Main Admin Page</a></li>
                    <li><a href="updateanddelete.jsp">Update&sol;Delete</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                </ul>
            </nav>
        </div>

        <section id="section1" class="container-fluid">
            <legend><h1 style="text-align: center;">Advanced search</h1></legend>

            <form action="SearchMovie" method="post">
                    <div class="form-group">
                        <label for="searchType">Search by: <input type="hidden" class="form-control add" required></label>
                            <select name="searchType">
                                <option value = "title">Title</option>
                                <option value = "genre">Genre</option>
                                <option value = "Actor">Actor</option>
                            </select>
                        <input type = "submit" value = "Search">
                    </div>
                    <div class="form-group">
                    <label for="query">Search term <input type="text" class="form-control add" name="search" placeholder="search" /></label>
                    </div>
                </form>

</body>
</html>

jsp显示允许用户选择类别并输入搜索词的页面。
搜索电影.java

package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.*;
import java.util.*;

/**
 * Servlet implementation class SearchMovie
 */
@WebServlet("/SearchMovie")
public class SearchMovie extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html");
        HttpSession session = request.getSession(true);
        List movielist = new ArrayList();

        String searchType = "";
        String search = "";

        searchType = request.getParameter("searchType");
        search = request.getParameter("search");

        String sqlStr = null;

        if(searchType.equals("title")){
            sqlStr = "Select Moviename, genre, duration, cast, release_date, summary, timeslot FROM movie where Moviename like '%" + search + "%'";
        }
        else if(searchType.equals("genre")) {
            sqlStr = "Select Moviename, genre, duration, cast, release_date, summary, timeslot FROM movie where genre like '%" + search + "%'";
        }
        else if(searchType.equals("Actor")) {
            sqlStr = "Select Moviename, genre, duration, cast, release_date, summary, timeslot FROM movie where cast like '%" + search + "%'";
        }else {
            System.out.println("How did you not select from the drop down table?");
        }
        System.out.println(sqlStr);
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/database?user=root&password=password&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");

            try{

                Statement statement = conn.createStatement();
                ResultSet rs = statement.executeQuery(sqlStr);

                while (rs.next()) {
                    List movie = new ArrayList();
                    movie.add(rs.getInt(1));
                    movie.add(rs.getString(2));
                    movie.add(rs.getString(3));
                    movie.add(rs.getString(4));
                    movie.add(rs.getString(5));
                    movie.add(rs.getString(6));

                    movielist.add(movie);
                }
            } catch (SQLException s){
                System.out.println("Value could not be found");
            }
            } catch(Exception e){
                e.printStackTrace();
        }
            request.setAttribute("movielist", movielist);
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/searchresult.jsp");
            dispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchMovie() {
        super();
        // TODO Auto-generated constructor stub
    }

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

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */

}

java是执行sql语句并将结果发送到显示页的servlet。
搜索结果.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    import="java.util.*"
    import="java.io.*"
    %>

<%@ include file = "constants.jsp" %>

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <title>Movie</title>
        <style>
            .affix {top: 0; width: 100%;}
            .affix + .container-fluid {padding-top: 50px;}
            .nav-wrapper {min-height: 50px;}
            #section1 {padding-top: 50px; min-height: 550px; background-color: #EFEFEF; border-bottom: 1px solid #D6D6D6;}
            #section2 {padding-top: 50px; min-height: 1000px; background-color: #EFEFEF; border-bottom: 1px solid #D6D6D6;}
            #section3 {padding-top: 20px; min-height: 400px; background-color: #EFEFEF; border-bottom: 1px solid #D6D6D6;}
            .add {width:600px;}
        </style>
        <script>
            //Smooth Scrolling
            $.fn.scrollBottom = function() { 
                return $(document).height() - this.scrollTop() - this.height(); 
            };
            window.onscroll = function() {myFunction()};
            $(document).ready(function(){
                $("a").on('click', function(event) {
                    if (this.hash !== "") {
                        event.preventDefault();
                        var hash = this.hash;
                        $('html, body').animate({
                            scrollTop: $(hash).offset().top
                        }, 400, function(){
                            window.location.hash = hash;
                        });
                    }
                });
            });
        </script>
    </head>
    <body>
        <%
        // Show username on page
        %>
        <%@ include file = "header.html" %>
        <div class="nav-wrapper">
            <nav id="site-navigation" class="container-fluid navbar navbar-inverse" data-spy="affix" data-offset-top="160" style="margin:auto;">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#top" style="font-size: 30px;"><b>Movie</b></a>
                </div>
                <ul class="nav navbar-nav">
                    <li><a href = "booking.jsp">Bookings</a>
                    <li><a href = "review.jsp">Reviews</a>
                    <li class="active"><a href="#top">Main Admin Page</a></li>
                    <li><a href="updateanddelete.jsp">Update&sol;Delete</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                </ul>
            </nav>
        </div>
        <div class = "section1">
        <table align="center">
        <%
            List movielist = new ArrayList();
            movielist = (ArrayList)request.getAttribute("movielist");
            if(movielist != null && movielist.size() > 0) {

        %>
        <h2 align="center">Result</h2>

        <tr>

            <th>Movie</th>

            <th>Genre</th>

            <th>Duration</th>

            <th>Cast</th>

            <th>Release date</th>

            <th>Summary</th>

            <th>Time slot</th>

        </tr>

        <%

        for(int i=0;i<movielist.size();i++){

        List movie=(List)movielist.get(i);

        %>

        <tr>

        <td><%=movie.get(1) %></td>

        <td><%=movie.get(2) %></td>

        <td><%=movie.get(3) %></td>

        <td><%=movie.get(4) %></td>

        <td><%=movie.get(5) %></td>

        <td><%=movie.get(6) %></td>

        <td><%=movie.get(7) %></td>

        </tr>

        <%

            }

        }else{

        %>
        <tr>

            <td> No records found </td>

        </tr>

        <%}%>

        </table>
        </div>
    </body>

</html>

最后,searchresult.jsp显示从数据库检索到的详细信息。
我需要帮助,因为即使查询在数据库中,结果页也显示NotFound。
编辑:我在运行这个时在eclipse中遇到了一个错误。
这是我在搜索电影时遇到的错误,例如《复仇者》。

java.lang.NumberFormatException: For input string: "avengers"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)
    at com.mysql.cj.protocol.a.MysqlTextValueDecoder.decodeDouble(MysqlTextValueDecoder.java:228)
    at com.mysql.cj.result.StringConverter.createFromBytes(StringConverter.java:110)
    at com.mysql.cj.protocol.a.MysqlTextValueDecoder.decodeByteArray(MysqlTextValueDecoder.java:238)
    at com.mysql.cj.protocol.result.AbstractResultsetRow.decodeAndCreateReturnValue(AbstractResultsetRow.java:129)
    at com.mysql.cj.protocol.result.AbstractResultsetRow.getValueFromBytes(AbstractResultsetRow.java:233)
    at com.mysql.cj.protocol.a.result.ByteArrayRow.getValue(ByteArrayRow.java:91)
    at com.mysql.cj.jdbc.result.ResultSetImpl.getNonStringValueFromRow(ResultSetImpl.java:628)
    at com.mysql.cj.jdbc.result.ResultSetImpl.getInt(ResultSetImpl.java:827)
    at servlet.SearchMovie.doPost(SearchMovie.java:59)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
dw1jzc5e

dw1jzc5e1#

用于检索每个电影的信息的查询如下所示: Select Moviename, genre, duration, cast, release_date, summary, timeslot FROM movie where Moviename like '%" + search + "%'" 运行时,尝试对结果集执行以下操作:

while (rs.next()) {
List movie = new ArrayList();
movie.add(rs.getInt(1));
movie.add(rs.getString(2));
movie.add(rs.getString(3));
movie.add(rs.getString(4));
movie.add(rs.getString(5));
movie.add(rs.getString(6));

movielist.add(movie);
}

这将失败 movie.add(rs.getInt(1)); 因为查询返回的第一个元素是 String ,因为您检索了 Moviename 因此 NumberFormatException 你看。
除此之外,对于您如何处理检索到的信息,我有点困惑。
你有一个名单电话 movie 我只是假设 String . 在其中添加各种元素,然后依次将其添加到另一个名为 movielist . 据我所知,这是错误的。应该有一个名为 Movie 所有你需要描述的领域。结果集的结果将用于创建新的 Movie 对象,然后将其添加到 movielist .
我想你需要重新考虑一下你的方法。

相关问题