I'm developing a webapp using Struts2. I used to work with Struts1
is there a way to reference a session object directly to the JSP so that if I change the value in the formular, the value in the referenced session object will also be updated.
<s:textfield name="%{#session.order.amount}"/>
for e.g. I have a session object order which has attribute amount with getter and setter.
it seems like, after I put some values into the textfield
and then submit the page, the value in the session didn't get updated.
currently I'm using another approach which involves session.put()
inside the setter of an action attributes. Personally I dislike my current solution.
You could try having the name be the string
session.order.amount
and make your action implement SessionAware, and expose the session. Currently you're setting the name to the value ofsession.order.amount
.I don't know if it would work, and you might need to use array/collection notation, but off the top of my head I don't know why it wouldn't work.
That said, I feel like direct view-layer writes into web app internals is a Bad Idea.
From the Struts1 where form bean placed to the session scope by default or just by setting an attribute value
scope="session"
and everything was good.In the Struts2 you have not form beans nor session scoped beans. And to use session scoped beans you need to either implement it yourself, or use other frameworks like Spring, Guice or CDI where session scoped is implemented and available to user.
On the other hand Struts2 is in heavy use of interceptors, which provide you additional features like
scope
interceptor, orscopedModelDriven
interceptor that allows you to put some action properties to the session scope. It will initialize the properties each time the action is executed referencing objects are put on the session scope.Without this helper interceptors you could always intercept a session object by implementing
SessionAware
(see How do we get access to the session) and initialize the properties somewhere when the action is executed, i.e.prepare()
method, because it's comming after the session map is injected. Putting initializer to the accessors is a bad idea.