Search code examples
struts2struts

Migrating from struts-1 to struts-2(<bean:write>, request.getAttribute("attr1"),session.getAttribute("attr2"))


Lets Say user object exists in any one of the scope(PageContext,request,session,application)

so to get the user object (from any one of the scope) in jsp, below code works super fine in struts1.X

**<bean:write name="user" property="someProperty"/>**

so in struts-2 how can i achieve this, please provide any suggestion

apart from the above one, is there a way to achieve in struts-2 for following code in JSP

    <%
    User user = (User)session.getAttribute("user");
    if(null != user){%>
    // some html code
    <%}%> 

    <%
    if(null != user.getSomeProperty() && "".equals(user.getSomeProperty())){%>
    //some html code
    <%}%>

<%
    if(null != user.getSomeProperty() && "prop1".equals(user.getSomeProperty())){%>
    //some html code
    <%}%>

i believe by using struts-2 tags i can make code simpler and cleaner rather than using above scriplets.

so whats the best in struts-2 for above things, please help me out


Solution

  • The equivalent of the <bean:write name="user" property="someProperty" /> is:

    ${user.someProperty}
    

    If JSP EL isn't your jam:

    <s:property value="user.someProperty" />
    

    Or the more-explicit OGNL:

    <s:property value="%{user.someProperty}" />
    

    All of this is covered in the S2 docs; I'd strongly recommend taking some time to read through the docs and tutorial(s) because this is Struts 2 101. Basic stuff.

    As for your second, completely-unrelated question, this should not be handled via scriptlets. Scriptlets are a code smell. Don't do that.

    You'll want to use the <s:if > tag, which is also in the docs.

    You'll find things go much more efficiently if you take a step back and just learn the framework you're trying to use.