Well currently i’m doing a simple application using jsp, servlet, jstl with hibernate integration, I have a problem regarding my servlet method since doPost and doGet require action(clicking the link/submit button) to happen. My question is how can I fetch the database records onload without doing any action on my servlet. What I want to do is once the admin(user) click the userlist.jsp page the combobox will be populated by the records coming from the database, onload.
So far this is what I’ve got:
my Register.jsp page
I already implement and call jstl so I can easily loop through the wole list(records) from the database.
<select name="role" >
<c:forEach var="load" items="${load}">
<option><c:out value="${load}"></c:out></option>
</c:forEach>
</select>
and my servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
loadRole(request, response);
}
This is my method loadRole I just call the method just to separate the logic from the request and response object.
private void loadRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
HttpSession roleSession = request.getSession();
Session session = factory.openSession();
session.beginTransaction();
Query query = session.createQuery("SELECT cd FROM Role");
List load = query.list();
roleSession.setAttribute("load", load);
request.getRequestDispatcher("Forms/Register.jsp").forward(request, response);
session.getTransaction().commit();
session.close();
}
This piece of code is working however it need to do first doPost/doGet method before fetching the database records.
You can use
init()method for initialization. Reference here.Next
how can I pass the result to session using init method?
Use
service()method. You can retrieveHttpRequestandHttpResponse.You have to reference Servlet Life Cycle. Here