Question

Im trying to write a code using the struts framework.

Im new in struts, I do not have experience in this field.

What i want to do, its to use the list of object in struts.

Assume that we have the java class extends from ActionForm as bellow:

ResumeMessages.java:

public class ResumeMessages_Form extends ActionForm{

private List<Message> listallmessages; // this is the list wich i want to use it
private DbMessage DbMessage; // a simple java class to connect from JDBC to xamp ...

public ResumeMessages_Form() {
    super();
    DbMessage = new DbMessage();
    try {
        listallmessages = DbMessage.List_Messages(); // return list of all messages in the database
    } catch (SQLException ex) {
        Logger.getLogger(ResumeMessages_Form.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public List<Message> getListallmessages() {
    return listallmessages;
}

public void setListallmessages(List<Message> listallmessages) {
    this.listallmessages = listallmessages;
}

@Override
public String toString() {
    return "ResumeMessages_Form{" + "listallmessages=" + listallmessages + ", DbMessage=" + DbMessage + '}';
}

@Override
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
    return errors;
}

}

And assume that i want to use the list 'listallmessages' in the jsp file as bellow:

Resum.jsp:

  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Untitled Page</title>
                 <jsp:include page="/files/resumemessages/resumemessages_style.jsp"/>

    </head>
    <body>
        <html:form action="/resum" method="post">
<table>
<% for (int i=0;i<listallmessages.size();i++){%>
    <tr><td> <%= listallmessages.get(i).message_name %>
</td></tr>
<%}%>
</table>
</html:form>
</body>
</html>

Notice: I have no problem with the struts-config.xml, I know well what i will do in the struts-config.xml, just I need someone to help me to use List in jsp file using struts.

Thanks a lot :) Binary Man

Was it helpful?

Solution

I wouldn't use scriptlets (Java code) in your JSP page - it's better practice to use a tag library such as JSTL or the Struts taglib.

Example using c:forEach and c:out from JSTL:

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

<c:forEach var="message" items="${listallmessages}">
    <c:out value="${message.message_name}"/> 
</c:forEach>

The Struts taglib contains logic:iterate and bean:write, which are similar to use:

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<logic:iterate name="listallmessages" id="message">     
    <bean:write name="message" property="message_name"/> 
</logic:iterate>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top