I need some advice on how I am using JQuery, JSP and Lucene to create my web application. I am not sure if I am doing it the correct way or if there is a better way I should be doing it. This is what I have:
When the user clicks on the search button I execute JQuery Ajax
$.ajax({
url : "search.jsp",
dataType:'json',
data : "q=" + searchTerm,
success : function(json) {
var video = _.template($("#video_template").text());
$.each(json, function(messageIndex, jsonObject) {
var html = video({'_link': jsonObject.link, '_title': jsonObject.title, '_video': jsonObject.video});
$("#search_results").append(html);
});
}
});
As you can see I go to search.jsp with my JQuery and return a json object which I use underscore.js to display the results.
This all works fine but I have a couple of questions.
Instead of using search.jsp, should I be using an HTTPServlet?
For example when I POST. Below I’ll have a collection of the search results which I can put into a JSON Object and send back to JQuery to display results
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String searchWord = request.getParameter("q");
SearchManager searchManager = new SearchManager(searchWord);
List searchResult = searchManager.search();
RequestDispatcher dispatcher = request.getRequestDispatcher("index");
request.setAttribute("searchResult", searchResult);
dispatcher.forward(request, response);
}
At the moment I am only displaying 10 results, however I want to have a next button which the goes to my lucene application to get more results. The problem I have is that lucene will need to know about the search term and the number of results already there in order to display more. Is there a way I can hold onto a search object that knows about the current state of the search? Can JSON do this?
Hope someone can help. I used to Java and haven’t built a web application before.
Thanks
Yes, you should definitely have your “real” Java code (like calling the Lucene API) in a Java class, not in the jsp.
For simple cases and small applications, it’s perfectly fine to go with a servlet. But if your application will grow and become more complex in the future, you should probably rather switch to using a web/presentation tier framework. These frameworks will bring some ready-to-use features that you’d need to build on your own when working on the raw servlet API, and they will also enforce a better technical design of the application, which can greatly improve maintanabilty.
For a scenario like the one above, it might make sense to go either for a REST services oriented framework like Jersey or any JAX-WS implementation, or you could use a framework that’s based on controller classes and the MVC pattern, like Spring MVC or Struts. These MVC frameworks might be the better choice if you want to also serve full HTML pages, not only JSON data.