RaceBase
RaceBase

Reputation: 18848

Preserving Struts2 ModelBean data from jsp

I have ModelBean (suppose MyBean), where I am setting lot of data from the database

class MyBean{
   List<String> someData;
   //getters and setters and other properties
}

Now I am displaying this data in jsp. it's fine till this point.

Now when I submit any action from JSP, once Flow enters into Action class, the ModelBean data is missing apart from the parameters which are again submitted using hidden variables or so. I am aware that we need to submit them using hidden variables in order to keep them in bean if we are showing the data for view purpose only.

Since I have so much amount of data coming from db, i don't want to put them in hidden and make my jsp load very slow. Any other workaround to keep data flowing from model bean to jsp to model bean without using session/hidden. I am fine with request params.

Upvotes: 0

Views: 551

Answers (1)

Jensen Ching
Jensen Ching

Reputation: 3164

There is no clean alternative to the behavior you want. By nature, HTTP is a stateless protocol, and in order to store state, e.g., your modelBean, you're going to have to either put it in the session, or pass the entire bean to the next action through request params (usually through a form). Now, you don't want to do both, so there is very little else you can do.

Do you actually update all those information you're placing in your modelBean? How about if you just place the bean ID in a hidden field, then when you pass it to the next action, retrieve the bean from the DB and do what you want with it. That way, your state is stored in the DB, and you don't need to pass around this huge object in your JSPs.

Now if you really want to pass the entire object around, and you're looking for a third alternative, the best I can think of is convert the object into a json object using something like GSON then pass it into a javascript object on your JSP, e.g.:

//Java code
String modelBeanJson = GSON.toJson(modelBean, ModelBean.class);

//JS code
var jsonToPass = <s:property value="modelBeanJson" escape="false" />;
//On next action
window.location.href = "NextAction?param1=" + JSON.stringify(jsonToPass);

But... this is almost the same as putting the object in hidden fields.

TL;DR If you don't really need to pass around the whole beanObject, consider just passing the bean's ID and retrieving it from the DB in your next action.

Upvotes: 2

Related Questions