Search code examples
javastrutsstruts-1

getting object's attribute in view from request


Is there a way to set an attribute on my DispathAction like this:

request.setAttribute("myObject", object);

And then on my jsp get the object's attributes?

<%=request.getAttribute("object.attr1") %>
<%=request.getAttribute("object.attr2") %>

My page is not a form.


Solution

  • Yes. Simply forget about scriptlets and learn to use the JSP EL and the JSTL:

    <c:out value="${myObject.attr1}"/>
    <c:out value="${myObject.attr2}"/>
    

    Note that this assumes the object respects JavaBean conventions, and will call getAttr1() and getAttr2() on your object. The JSTL <c:out> tag escapes the HTML special characters (<, >, &, etc.).