Hi all I'm developing a web-app and I want to retrieve data from the database 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?
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 ...
What you mentioned will work. It all depends on the complexity of your project. If it is something simple, yea.. a 2-tier architecture with servlet and jsp works fine. But, if your project is a reasonably moderate in size, you might want to use some well known frameworks to handle most of the plumbing configuration and code for you. You end up writing less code, less clutter and more loose couplings. In my projects, I use Struts or Spring MVC instead of servlets. Then I use Spring to wire up the rest of the components.
Of course, more frameworks used means more learning curve. You just need to strike a balance based on what you need to accomplish with your given project deadline.
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.