I'm developing a web-app and I want to retrieve data from the d开发者_运维百科atabase and send them to the homepage.I thought to set the servlet as my welcome page,retrieve my data from the database,redirect to the homepage and pass my data as parameters.Any better ideas?
Implement doGet()
method, set the data as request attribute and forward the request to the JSP. Assuming that you want to display some list in a table in JSP:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Entity> entities = entityDAO.list();
request.setAttribute("entities", entities); // Will be available as ${entities} in JSP.
request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request, response);
}
Map this servlet on an url-pattern
of /home
so that you can execute it by http://example.com/context/home and have in JSP something like this:
<table>
<c:forEach items="${entities}" var="entity">
<tr>
<td>${entity.id}</td>
<td>${entity.name}</td>
<td>${entity.value}</td>
</tr>
</c:forEach>
</table>
This will display the list of entities in a table.
See also:
- Beginning and intermediate JSP/Servlet tutorials
An idea: create a tag in a taglib that fetches your data from your backend/bussiness and use it a jsp. if the data is always the same, consider caching it.
another option, use a framework like Spring MVC, Struts2, Play! Framework ...
精彩评论