Method call within JSP

Asked

Viewed 663 times

1

Good morning, everyone! I was having trouble formatting dates in jsp, but with the help of friends here, I was able to solve.

The problem is that I think my code is far from good practices in JSP, I had to program inside the page, but friends told me that I could call the getInicioFormated() direct method that I would solve, but I couldn’t... I’m leaving the classes down here, I removed most of what I found unnecessary, but if anyone needs anything just say.

Obs.: for persistence I am using Hibernate.

Thanks for the personal help!

Supplier class.

/* imports e anotations desnecessários para o exemplo, foram omitidos.

public class Fornecedor extends Pessoa{

@Column
private Integer codigo;
@Column
private String pessoaContato;
@Column
private String cnpj;
@Column
private Date inicioAtividades;

    /* construtores, get and seters desnecessários para o exemplo, foram omitidos.

public  Date getInicioAtividades()  {


    return inicioAtividades;
}
public void setInicioAtividades( java.util.Date inicioAtividades) {
    this.inicioAtividades = (Date) inicioAtividades;
}


public String getInicioFormatado() { 
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    String data = sdf.format(inicioAtividades);
    return  data;
    }

Servlet Control Supplier

protected void buscar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try{
List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();

    request.setAttribute("listaFornecedores", listaFornecedores);
    request.getRequestDispatcher("cadFornecedores.jsp").forward(request, response);

}catch(Exception e){
    e.printStackTrace();
}

Vendor Dao

public List<Fornecedor> listarFornecedores() {
    session = HibernateUtil.getSessionFactory().openSession();
    List<Fornecedor> listaFornecedores = new ArrayList<Fornecedor>();
    query = session.createQuery("FROM Fornecedor");

    listaFornecedores = query.list();
    session.close();
    return listaFornecedores;   
    }

Registration of JSP suppliers (where I did a lot of work)

<c:if test="${fn:length(listaFornecedores) > 0 }">

    <br>
    <table class="table table-hover">
        <tr>
            <th>Nome</th>
            <th>Código</th>
            <th>Telefone</th>
            <th>Endereço</th>
            <th>Nº</th>
            <th>Cep</th>
            <th>Bairro</th>
            <th>Cidade</th>
            <th>Estado</th>
            <th>E-mail</th>
            <th>Nome do Contato</th>
            <th>CNPJ</th>
            <th>Início das Atividades</th>
            <th></th>
        </tr>

        <% List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();
            Integer i = 0;
            Fornecedor f = new Fornecedor();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        %> 


        <c:forEach items="${listaFornecedores }" var="forn">


            <tr>
                <td id="nome${forn.id}">${forn.nome }</td>
                <td id="codigo${forn.id}">${forn.codigo }</td>
                <td id="telefone${forn.id}">${forn.telefone }</td>
                <td id="endereco${forn.id}">${forn.endereco }</td>
                <td id="numero${forn.id}">${forn.numeroDoEndereco }</td>
                <td id="cep${forn.id}">${forn.cep }</td>
                <td id="bairro${forn.id}">${forn.bairro }</td>
                <td id="cidade${forn.id}">${forn.cidade }</td>
                <td id="estado${forn.id}">${forn.estado }</td>
                <td id="email${forn.id}">${forn.email }</td>
                <td id="nomecontato${forn.id}">${forn.pessoaContato }</td>
                <td id="cnpj${forn.id}">${forn.cnpj }</td>
                <td id="inicioAtividades${forn.id}">


                <% 
                f.setid(listaFornecedores.get(i).getid());
                f.setInicioAtividades(listaFornecedores.get(i).getInicioAtividades());  
                    String data =  sdf.format(f.getInicioAtividades());
                out.print(data);
                    //System.out.println(f.getInicioFormatado());
                    i=i+1;

                %>
                                    </td>
                                <td><a href="#alterarFornecedor"
                                    class="btn btn-xs btn-info alterarFornecedor"
                                    data-togle="modal" data-id = "${forn.id }">Alterar</a> <a
                                    href="excluirForn.html?id=${forn.id }"
                                    class="btn btn-xs btn-danger">Remover</a></td>
                            </tr>


                        </c:forEach>
                    </table>
                </c:if>

1 answer

1


Some remarks:

How are you adding your vendor list as a àttribute your request in that passage:

request.setAttribute("listaFornecedores", listaFornecedores);

The following code snippet in your JSP becomes unnecessary:

<% List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();
        Integer i = 0;
        Fornecedor f = new Fornecedor();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
%>

If you had mentioned in the other topic that the goal of having a Date formatted was to display it in your JSP, we could have instructed you to use taglib fmt and format it within JSP itself. Thus. Example:

<fmt:formatDate value="${fornecedor.inicioAtividades}" pattern="dd/MM/yyyy" />

Your code would look like this:

Your Servlet:

protected void buscar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try{
        List<Fornecedor> listaFornecedores = new FornecedorDao().listarFornecedores();

        request.setAttribute("listaFornecedores", listaFornecedores);
        request.getRequestDispatcher("cadFornecedores.jsp").forward(request, response);

    } catch(Exception e){
        e.printStackTrace();
    }
}

Your JSP:

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

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Lista de Fornecedores</title>

    <!-- Seu css, javascript, etc -->

</head>
<body>

    <!-- O resto do conteúdo da sua página -->

    <table class="table table-hover">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Código</th>
                <th>Telefone</th>
                <th>Endereço</th>
                <th>Nº</th>
                <th>Cep</th>
                <th>Bairro</th>
                <th>Cidade</th>
                <th>Estado</th>
                <th>E-mail</th>
                <th>Nome do Contato</th>
                <th>CNPJ</th>
                <th>Início das Atividades</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach var="fornecedor" items="${listaFornecedores}">
                <tr>
                    <td id="nome${fornecedor.id}">${fornecedor.nome}</td>
                    <td id="codigo${fornecedor.id}">${fornecedor.codigo}</td>
                    <td id="telefone${fornecedor.id}">${fornecedor.telefone}</td>
                    <td id="endereco${fornecedor.id}">${fornecedor.endereco}</td>
                    <td id="numero${fornecedor.id}">${fornecedor.numeroDoEndereco }</td>
                    <td id="cep${fornecedor.id}">${fornecedor.cep}</td>
                    <td id="bairro${fornecedor.id}">${fornecedor.bairro}</td>
                    <td id="cidade${fornecedor.id}">${fornecedor.cidade}</td>
                    <td id="estado${fornecedor.id}">${fornecedor.estado}</td>
                    <td id="email${fornecedor.id}">${fornecedor.email}</td>
                    <td id="nomecontato${fornecedor.id}">${fornecedor.pessoaContato}</td>
                    <td id="cnpj${fornecedor.id}">${fornecedor.cnpj}</td>
                    <td id="inicioAtividades${fornecedor.id}">
                        <fmt:formatDate value="${fornecedor.inicioAtividades}" pattern="dd/MM/yyyy" />
                    </td>
                </tr>
            </c:forEach>
            <c:if test="${empty listaFornecedores}">
                <tr><td colspan="100%">Nenhum fornecedor cadastrado</td></tr>
            </c:if>
        </tbody>
    </table>
</body>

  • Kra, thank you, really! Even more than I needed. It worked perfectly, and even gave me the idea in case you have no registered supplier, show the message with c:if. :)

Browser other questions tagged

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