Show output from a JSP page Servlet list

Asked

Viewed 754 times

1

I need to capture an input name, query the database and return the result on a jsp page. I want to show the result in a short snippet of the JSP page, in case I mix the text of the JSP page 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());

 }

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 display attributes in the view, it is good practice in this case to use EL(Expression Language) and JSTL(JSP Standard Tag Library).

To use JSTL you must download the jar and add inside the lib folder or add the dependency in pom.xml if you use Maven.

https://mvnrepository.com/artifact/javax.servlet/jstl/1.2

In your JSP you must import the JSTL library

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

And finally, to show the sample list in the view, we can combine el and jstl.

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

Links Úteis

https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.html https://docs.oracle.com/cd/E19798-01/821-1841/gjddd/index.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.