Я сейчас работаю над проектом кино, я застрял в поиске фильмов из базы данных. Итак, у меня есть таблица фильмов на моей главной странице
<div id="moviesTable">
<div class="col-md-2 text-center" id="moviesSearchBox">
<div class="col-md-3 text-center" id="searchOptions">
<select id="searchOptionsBox" name="searchOptionsBox" class="browser-default custom-select">
<option value="title">Title</option>
<option value="distributor">Distributor</option>
<option value="originCountry">Origin country</option>
<option value="yearOfProduction">Year of production</option>
</select>
</div>
<div id="searchMovieInput">
<input id="searchMovieInputBox" type="text" class="form-control">
</div>
<div id="searchMovieBtnBox">
<button class="btn btn-primary" type="submit" id="searchMovieBtn">Search</button>
</div>
</div>
<table id="moviesTable1" class="table table-striped table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Duration</th>
<th>Distributor</th>
<th>Origin country</th>
<th>Year of production</th>
</tr>
</thead>
<tbody id="moviesTbody">
</tbody>
</table>
</div>
, как вы можете видеть, у меня есть выбор с опциями и один ввод для поиска, я хочу, чтобы пользователь вводил ввод, выбирал один вариант и получал желаемый результаты (я использую datatable, но должен реализовать пользовательский поиск)
Это мой MovieDAO, который я использую для связи с базой данных. Кстати, у меня есть метод getAll в MovieDAO, и я могу получить все фильмы и заполнить их данными.
public static List<Movie> searchMovies(String title, String distributor, String originCountry, Integer yearOfProduction) {
List<Movie> movies = new ArrayList<>();
Connection con = ConnectionManager.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM movies WHERE";
if (title != null && title !="") {
query += " title LIKE ?";
}
if (distributor != null && distributor !="") {
query += " distributor LIKE ?";
}
if (originCountry != null && originCountry !="") {
query += " origincountry LIKE ?";
}
if (yearOfProduction != null && yearOfProduction !=0) {
query += " yearofproduction = ?";
}
try {
ps = con.prepareStatement(query);
int index = 1;
if (title != null && title !="") {
ps.setString(index++, title);
}
if (distributor != null && distributor !="") {
ps.setString(index++, distributor);
}
if (originCountry != null && originCountry !="") {
ps.setString(index++, originCountry);
}
if (yearOfProduction != null) {
ps.setInt(index++, yearOfProduction);
}
rs = ps.executeQuery();
while (rs.next()) {
index = 1;
int id = rs.getInt(index++);
String title_rs = rs.getString(index++);
String duration = rs.getString(index++);
String distributor_rs = rs.getString(index++);
String originCountry_rs = rs.getString(index++);
int yearOfProduction_rs = rs.getInt(index++);
Movie movie = new Movie();
movie.setId(id);
movie.setTitle(title_rs);
movie.setDuration(duration);
movie.setDistributor(distributor_rs);
movie.setOriginCountry(originCountry_rs);
movie.setYearOfProduction(yearOfProduction_rs);
movies.add(movie);
}
} catch (Exception e) {
System.out.println("SQL query error!");
e.printStackTrace();
} finally {
try {ps.close();} catch (Exception ex1) {ex1.printStackTrace();}
try {rs.close();} catch (Exception ex1) {ex1.printStackTrace();}
}
return movies;
}
SearchMoviesServlet
public class SearchMoviesServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String searchOptionBox = request.getParameter("searchOptionBox");
String title = request.getParameter("title");
String distributor = request.getParameter("distributor");
String originCountry = request.getParameter("originCountry");
Integer yearOfProduction = Integer.parseInt(request.getParameter("yearOfProduction"));
List<Movie> movies = MovieDAO.searchMovies(title, distributor, originCountry, yearOfProduction);
if(searchOptionBox != null) {
switch(searchOptionBox) {
case "title":
Collections.sort(movies, Movie.titleComparator);
break;
case "distributor":
Collections.sort(movies, Movie.distributorComparator);
break;
case "originCountry":
Collections.sort(movies, Movie.originCountryComparator);
break;
case "yearOfProduction":
Collections.sort(movies, Movie.yearOfProductionComparator);
break;
default:
break;
}
}
Map<String, Object> data = new HashMap<>();
data.put("movies", movies);
ObjectMapper mapper = new ObjectMapper();
String jsonData = mapper.writeValueAsString(data);
System.out.println(jsonData);
response.setContentType("application/json");
response.getWriter().write(jsonData);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
jquery script
searchMovies : function() {
$('#moviesTable1').dataTable().fnClearTable();
$.get('SearchMoviesServlet?searchOptionBox=' + $("searchOptionBox option:selected").val() + '&title='
+ $("#title").val() + "&distributor=" + $("#distributor").val() + "&originCountry="
+ $("#originCountry").val() + "&yearOfProduction=" + $("#yearOfProduction").val(), function(data){
for(m in data.movies) {
$('#moviesTable1').dataTable().fnAddData ([
data.movies[m].title,
data.movies[m].duration,
data.movies[m].distributor,
data.movies[m].originCountry,
data.movies[m].yearOfProduction
]);
}
});
}
Мне ясно, что что-то не так в $ get (), но я не могу обдумать это, и я застрял, любая помощь приветствуется, спасибо.