There the Servlet
is for. You can make use of it to control, preprocess and postprocess requests to a high degree. You can make use of query string to pass request specific information to the servlet, e.g. http://example.com/context/servlet?name1=value1&name2=value2
, which can be accessed in Servlet as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name1 = request.getParameter("name1"); // Now contains "value1".
String name2 = request.getParameter("name2"); // Now contains "value2".
// Do your business thing with them.
}
You can also make use of request pathinfo to pass request specific information to the servlet, this results in more nicer URL's, e.g. http://example.com/context/servlet/value1/value2
, which can be accessed in Servlet as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo = request.getPathInfo(); // Now contains "/value1/value2".
// Do your business thing with them.
}
In both cases the Servlet
is of course mapped in web.xml
as follows:
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.example.Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
To display results in JSP, you need to store the data in the request scope and forward the request to a JSP for display. E.g.:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("query");
List<Result> results = searchDAO.list(query);
request.setAttribute("results", results);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
Here the Result
class is just an ordinary JavaBean class roughly representing one row of the database table. The JSP is placed in /WEB-INF
to prevent from direct access by URL. You of course want that only the servlet can access it. In JSP you can in turn use Expression Language to access any scoped attributes, such as results
from the above example. You can also use taglibs in JSP to control the page flow and output. A well known standard taglib is JSTL (just drop jstl-1.2.jar in /WEB-INF/lib
to get it to work), here's an example how to display results nicely in a JSP:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<c:forEach items="${results}" var="result">
<tr>
<td>${result.name}</td>
<td>${result.description}</td>
</tr>
</c:forEach>
</table>
To learn more about JSP/Servlets, I can recommend the Marty Hall's Coreservlets.com tutorials. To learn more about interacting with databases the right way (the DAO pattern), you may find this article useful as well.
Good luck.