Show result of a servlet list in JSP page

1

I need to capture an input name, query the database, and return the result in a jsp page. I want to show the result in a short section of the JSP page, in case I mix the JSP page text with the result I want to capture.

jsp page with input                    

Nome: <input type="text" name="nome" />
<br/>
Cpf: <input type="text" name="cpf" />
<br/>
<p>
<input type="submit" name="enviar" value="Enviar" />
<input type="reset" name="limpar" value="Limpar" />

</form>
</div>

</body>

List

PrintWriter out = response.getWriter();

 SessionFactory factory = new Configuration().configure().buildSessionFactory();
 Session session = factory.openSession();
 session.beginTransaction();

 List<Pessoa> listForm = new ArrayList<>();

 listForm = session.createQuery("from Pessoa where cpf like '%"+cpf+"%' and nome like '%"+nome+"%'").list();

 int tamanho = listForm.size();

 for(int i=0;i<tamanho;i++){
     Pessoa pessoa = listForm.get(i);
     out.println(pessoa.getId()+" - "+ pessoa.getNome());

 }
    
asked by anonymous 17.03.2018 / 22:08

1 answer

1

From the HttpServletRequest object, you can retrieve the session and add the attributes you want to display in the view.

For example: (Servlet)

protected void doPost(HttpServletRequest request, HttpServletResponse 
response) {

    List<String> nomes = new ArrayList<>();

    request.getSession().setAttribute("nomes", nomes);
    response.sendRedirect("/view");
}

To view the attributes in the view, it is good practice to use EL (Expression Language) and JSTL (JSP Standard Tag Library).

To use JSTL you should download the jar and add it inside the lib folder or add the dependency in pom.xml if you use maven.

link

In your JSP you should import the JSTL library

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

And finally, to show the list of the example in the view, we can combine the e jstl.

 <ul>
     <c:forEach items="${nomes}" var="nome">
         <li> ${nome} </li>
     </c:forEach>
 </ul>

Useful links

link link

    
21.03.2018 / 02:21