You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

影院项目自定义电影搜索功能故障求助(Servlet+JQuery+DataTables)

Fixing Your Movie Search Functionality

Let's walk through the issues in your code and fix them one by one—there are several key problems in both the frontend jQuery and backend Java code that are blocking your search feature from working correctly.

1. Frontend jQuery Issues

Your $.get call has multiple critical errors that are preventing it from sending the right data to the servlet:

a. Incorrect Selectors

  • You’re missing the # for ID selectors: $("searchOptionBox option:selected") should be $("#searchOptionBox option:selected") (since searchOptionBox is an ID).
  • Your input box has the ID searchMovieInputBox, but you’re trying to get values from non-existent elements like $("#title") or $("#distributor"). You need to use the correct input box ID and map it to the right parameter based on the selected search option.

b. Wrong Parameter Mapping

Instead of sending all parameters regardless of the selected option, you should send only the parameter that matches the user’s chosen search type. For example, if the user selects "Title", send only the title parameter with the input box value.

c. Outdated DataTables API

While fnClearTable and fnAddData work in older DataTables versions, using the modern API is more reliable. Also, you should destroy/reinitialize the table properly to avoid conflicts.

Here’s the fixed jQuery code:

$(document).ready(function() {
  // Initialize DataTables
  let movieTable = $('#moviesTable1').DataTable();

  // Bind search button click event
  $("#searchMovieBtn").click(function() {
    // Clear existing table data
    movieTable.clear().draw();

    // Get selected option and input value
    let selectedOption = $("#searchOptionBox option:selected").val();
    let inputValue = $("#searchMovieInputBox").val().trim();

    // Build request parameters
    let params = { searchOptionBox: selectedOption };
    params[selectedOption] = inputValue; // Map input to the correct parameter key

    // Send GET request
    $.get('SearchMoviesServlet', params, function(data) {
      // Add new data to the table
      data.movies.forEach(movie => {
        movieTable.row.add([
          movie.title,
          movie.duration,
          movie.distributor,
          movie.originCountry,
          movie.yearOfProduction
        ]).draw();
      });
    });
  });
});

2. Backend Servlet Improvements

Your SearchMoviesServlet has a critical error that will cause crashes, plus inefficient parameter handling:

a. Safe Integer Parsing

Calling Integer.parseInt(request.getParameter("yearOfProduction")) directly will throw a NumberFormatException if the parameter is missing or empty. You need to validate it first:

Integer yearOfProduction = null;
String yearParam = request.getParameter("yearOfProduction");
if (yearParam != null && !yearParam.isEmpty()) {
  try {
    yearOfProduction = Integer.parseInt(yearParam);
  } catch (NumberFormatException e) {
    // Handle invalid year input (e.g., set to null or return error)
    yearOfProduction = null;
  }
}

b. Correct Parameter Retrieval

You should retrieve only the parameter that matches the selected search option, but your current code tries to get all parameters regardless. However, since the frontend now sends only the relevant parameter, you can keep your existing code but add null checks to avoid passing empty strings to the DAO.

Here’s the updated doGet method snippet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String searchOptionBox = request.getParameter("searchOptionBox");
  
  String title = request.getParameter("title");
  if (title != null && title.isEmpty()) title = null;
  
  String distributor = request.getParameter("distributor");
  if (distributor != null && distributor.isEmpty()) distributor = null;
  
  String originCountry = request.getParameter("originCountry");
  if (originCountry != null && originCountry.isEmpty()) originCountry = null;
  
  Integer yearOfProduction = null;
  String yearParam = request.getParameter("yearOfProduction");
  if (yearParam != null && !yearParam.isEmpty()) {
    try {
      yearOfProduction = Integer.parseInt(yearParam);
    } catch (NumberFormatException e) {
      yearOfProduction = null;
    }
  }

  List<Movie> movies = MovieDAO.searchMovies(title, distributor, originCountry, yearOfProduction);
  
  // Sorting logic remains the same...
  
  // Send JSON response (unchanged)
  Map<String, Object> data = new HashMap<>();
  data.put("movies", movies);
  ObjectMapper mapper = new ObjectMapper();
  String jsonData = mapper.writeValueAsString(data);
  response.setContentType("application/json");
  response.getWriter().write(jsonData);
}

3. MovieDAO Critical Fixes

Your DAO has SQL syntax errors and incorrect string comparisons:

a. SQL Query Construction

When multiple conditions are present, you need to add AND between them. Also, if no conditions are provided, the query will end with WHERE (invalid syntax). Here’s how to fix it:

String query = "SELECT * FROM movies";
List<String> conditions = new ArrayList<>();
List<Object> params = new ArrayList<>();

if (title != null && !title.isEmpty()) {
  conditions.add("title LIKE ?");
  params.add("%" + title + "%"); // Add wildcards for partial matches
}
if (distributor != null && !distributor.isEmpty()) {
  conditions.add("distributor LIKE ?");
  params.add("%" + distributor + "%");
}
if (originCountry != null && !originCountry.isEmpty()) {
  conditions.add("origincountry LIKE ?");
  params.add("%" + originCountry + "%");
}
if (yearOfProduction != null) {
  conditions.add("yearofproduction = ?");
  params.add(yearOfProduction);
}

// Add WHERE clause if there are conditions
if (!conditions.isEmpty()) {
  query += " WHERE " + String.join(" AND ", conditions);
}

b. Correct String Comparison

Never use != "" to check for empty strings—this compares object references, not content. Use !string.isEmpty() instead.

c. Safe Resource Closure

Your finally block doesn’t close the Connection object, which can lead to resource leaks. Add con.close() (wrap in try-catch):

finally {
  try { if (rs != null) rs.close(); } catch (Exception ex1) { ex1.printStackTrace(); }
  try { if (ps != null) ps.close(); } catch (Exception ex1) { ex1.printStackTrace(); }
  try { if (con != null) con.close(); } catch (Exception ex1) { ex1.printStackTrace(); }
}

Putting it all together, your searchMovies method in MovieDAO should now correctly build valid SQL queries and handle parameters safely.

After applying all these fixes, your search functionality should work as expected: users select a search category, enter a value, click search, and the table updates with matching movies.

内容的提问来源于stack exchange,提问作者Marko Lazarevic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:28:12