POJO's collection not populated when submitting form - struts2

I have a POJO named "FlashCard" which has a field named "links" which is collection (set) of Link objects. When I submit a FORM to my Action all the POJO fields are populated with values from the form except the collection of "links". I have no idea why this isn't getting populated.
Any advice on how to resolve this problem or how to better troubleshoot it would be much appreciated.
Also, my POJO's collection is a Set. Does it matter (or complicate things) that I'm using a Set and not a List?
I'm including a simplified version of my code below.
Here's my POJO:
public class FlashCard implements java.io.Serializable {
private int flashCardId;
private String question;
private String answer;
private Set<Link> links = new HashSet<Link>(0);
public FlashCard() {
}
public FlashCard(String question, String answer) {
this.question = question;
this.answer = answer;
}
public FlashCard(String question, String answer, Set<Link> links) {
this.question = question;
this.answer = answer;
this.links = links;
}
public int getFlashCardId() {
return this.flashCardId;
}
public void setFlashCardId(int flashCardId) {
this.flashCardId = flashCardId;
}
public String getQuestion() {
return this.question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return this.answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public Set<Link> getLinks() {
return this.links;
}
public void setLinks(Set<Link> links) {
this.links = links;
}
}
Here's the POJO for the Link object:
public class Link implements java.io.Serializable {
private int linkId;
private String url;
private Set<FlashCard> flashcards = new HashSet<FlashCard>(0);
public Link() {
}
public Link(String url) {
this.url = url;
}
public Link(String url, Set<FlashCard> flashcards) {
this.url = url;
this.flashcards = flashcards;
}
public int getLinkId() {
return this.linkId;
}
public void setLinkId(int linkId) {
this.linkId = linkId;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public Set<FlashCard> getFlashcards() {
return this.flashcards;
}
public void setFlashcards(Set<FlashCard> flashcards) {
this.flashcards = flashcards;
}
}
Here's the relevant part of the Action
public class FlashCardAction extends FlashCardsAppBaseAction implements ModelDriven<FlashCard>, Preparable, SessionAware {
static Logger logger = Logger.getLogger(FlashCardAction.class);
FlashCard flashCard = new FlashCard();
Map <String,Object> httpSession;
Session session;
FlashCardPersister fcPersister;
public Map<String, Object> getHttpSession() {
return httpSession;
}
public FlashCard getFlashCard() {
return this.flashCard;
}
public void setFlashCard(FlashCard flashCard) {
this.flashCard = flashCard;
}
public void validate() {
logger.debug("Entering validate()");
if ( flashCard.getQuestion().length() == 0 ){
addFieldError("flashCard.question", getText("error.flashcard.question"));
}
if ( flashCard.getAnswer().length() == 0 ) {
addFieldError("flashCard.answer", getText("error.flashcard.answer"));
}
}
public String saveOrUpdate() {
logger.debug("Entering saveOrUpdate()");
// assume we'll fail
boolean result = false;
// are we creating a New Flash Card or Updating and existing one
// for now, let's assume we are creating a New Flash Card
boolean newFlashCard = true;
// if this is an Update of an existing Flash CArd then we'll have a Flash Card Id other than 0
if (this.flashCard.getFlashCardId() != 0) {
newFlashCard = false;
}
try {
result = fcPersister.saveOrUpdateFlashCard(this.flashCard, session);
// did we save a new FlashCard successfully?
if (result == true && newFlashCard) {
logger.debug("Flash Card created successfully");
this.addActionMessage(getText("actionmessage.flashcard.created"));
}
// did we update an existing Flash Card successfully?
else if (result == true && newFlashCard == false) {
logger.debug("Flash Card updated successfully");
this.addActionMessage(getText("actionmessage.flashcard.updated"));
}
// such a failure
else {
logger.error("unable to create or update FlashCard");
return "error";
}
return "success";
} catch (Exception e) {
logger.error("Exception in createFlashCard():", e);
return "error";
}
}
#Override
public FlashCard getModel() {
return this.flashCard;
}
#Override
public void setSession(Map<String, Object> httpSession) {
this.httpSession = httpSession;
}
#Override
public void prepare() throws Exception {
logger.debug("Entering prepare()");
// get a handle to a Hibernate session
session = getHibernateSession();
// get a handle to the FlashCard persistance utility class
fcPersister = new FlashCardPersister();
}
}
And lastly here's the JSP
<%#page import="com.opensymphony.xwork2.ActionContext"%>
<%#page import="com.opensymphony.xwork2.ActionSupport"%>
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sjr" uri="/struts-jquery-richtext-tags"%>
<h3><s:text name="label.flashcard.title"/></h3>
<s:actionerror theme="jquery" />
<s:actionmessage theme="jquery"/>
<s:fielderror theme="jquery"/>
<s:form action="saveOrUpdate" method="post">
<s:hidden name="flashCard.flashCardId" />
<s:textfield name="flashCard.question" key="label.flashcard.question" size="66" />
<sjr:tinymce
id="flashCard.answer"
name="flashCard.answer"
key="label.flashcard.answer"
rows="20"
cols="50"
editorTheme="simple"
/>
<s:textfield name="flashCard.links.url" key="label.flashcard.link" size="66" />
<tr>
<td>
<s:submit label="label.flashcard.submit" align="center" theme="simple" />
</td>
<td>
<s:submit key="label.flashcard.cancel" name="redirectAction:list" theme="simple" />
</td>
</tr>
</s:form>
<%((ActionSupport)ActionContext.getContext().getActionInvocation().getAction()).clearErrorsAndMessages();%>

First of all I don't think you can use Set here, because Sets are unordered and you can't get an item from a set by an index or key like List and Map. The only way is to iterate through the set and get the items.
Second assuming you're using a collection other than set, in:
<s:textfield name="flashCard.links.url" key="label.flashcard.link" size="66"/>
You try to set the value of the text field to url field of links which is a collection and doesn't have such a field. So you need to get the specific item from the collection you're editing and pass the value. Like:
<s:textfield name="flashCard.links[0].url" key="label.flashcard.link" size="66"/>
But since you can't get the specific item you are editing I suggest you create a link field in your Action and set the updated link to it. Then you can perform a logic to relace the updated link with obsolete one in you flashcards. Hope this helps.

Since you are using modeldriven and the model is FlashCard, i think the following
<sjr:tinymce
id="flashCard.answer"
name="flashCard.answer"
key="label.flashcard.answer"
rows="20"
cols="50"
editorTheme="simple"/>
should be changed to
<sjr:tinymce
id="flashCard.answer"
name="answer"
key="label.flashcard.answer"
rows="20"
cols="50"
value="answer"
editorTheme="simple"/>
the name field should be given without the prefix flashcard.also you should provide the 'value' attribute in order for it to be pre-populated.

Related

How to retrive data from dynamic text box using Blazor

MyCustomControl.razor
<input type="text" id="#id" />
#code {
[Parameter]
public string id { get; set; }
}
Test.Razor
#page "/test"
<button #onclick="#addCompoment">add text box</button>
<div class="simple-list-list">
#if (componentListTest == null)
{
<p>You have no items in your list</p>
}
else
{
<ul>
#foreach (var item in componentListTest)
{
#item<br/>
}
</ul>
}
</div>
#functions {
private List<RenderFragment> componentListTest { get; set; }
private int currentCount { get; set; }
private string TxtExample { get; set; }
protected void OnInit()
{
currentCount = 0;
componentListTest = new List<RenderFragment>();
}
protected void addCompoment()
{
if(componentListTest==null)
{
componentListTest = new List<RenderFragment>();
}
componentListTest.Add(CreateDynamicComponent(currentCount));
currentCount++;
}
RenderFragment CreateDynamicComponent(int counter) => builder =>
{
try
{
var seq = 0;
builder.OpenComponent(seq, typeof(MyCustomControl));
builder.AddAttribute(++seq, "id", "listed-" + counter);
builder.CloseComponent();
}
catch (Exception ex)
{
throw;
}
};
}
After Adding the textbox dynamically,how to retrieve all input data from the textbox (after clicking on the submit button.)
How to interact with dynamic component and fetch Value.
MyCustomControl is component, Append in Test Razor Page.
for these component create an attribute like bind-value to get input field data given by user
There are a couple of solutions to this type of issue, depending on the general design of your app, constraints, and such like. The following solution is simple. Generally speaking, it involves passing the value of the added text box to a parent component to be saved in a list object. The parent component has a button that displays the list of text when clicked.
The following is the definition of the child component:
MyCustomControl.razor
<input type="text" #bind="#Value" id="#ID" />
#code {
private string _value;
public string Value
{
get { return _value; }
set
{
if (_value != value)
{
_value = value;
if (SetValue.HasDelegate)
{
SetValue.InvokeAsync(value);
}
}
}
}
[Parameter]
public string ID { get; set; }
[Parameter]
public EventCallback<string> SetValue { get; set; }
}
Usage in a parent component
<button #onclick="#addCompoment">add text box</button>
<div class="simple-list-list">
#if (componentListTest == null)
{
<p>You have no items in your list</p>
}
else
{
<ul>
#foreach (var item in componentListTest)
{
#item
<br />
}
</ul>
}
</div>
<p><button #onclick="#ShowValues">Show values</button></p>
#if (Display)
{
<ul>
#foreach (var value in values)
{
<li>#value</li>
}
</ul>
}
#code {
public void SetValue(string value)
{
values.Add(value);
}
private List<RenderFragment> componentListTest { get; set; }
private List<string> values = new List<string>();
private int currentCount { get; set; }
protected override void OnInitialized()
{
currentCount = 0;
componentListTest = new List<RenderFragment>();
}
private bool Display;
private void ShowValues()
{
if (values.Any())
{
Display = true;
}
}
protected void addCompoment()
{
if (componentListTest == null)
{
componentListTest = new List<RenderFragment>();
}
componentListTest.Add(CreateDynamicComponent(currentCount));
currentCount++;
}
RenderFragment CreateDynamicComponent(int counter) => builder =>
{
try
{
builder.OpenComponent(0, typeof(MyCustomControl));
builder.AddAttribute(1, "id", "listed-" + counter);
builder.AddAttribute(2, "SetValue", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.EventCallback<System.String>>(Microsoft.AspNetCore.Components.EventCallback.Factory.Create<System.String>(this, this.SetValue )));
builder.CloseComponent();
}
catch (Exception ex)
{
throw;
}
};
}
Note:
Notice the SetValue attribute I've added to the CreateDynamicComponent's builder. This provides a Component Parameter to MyCustomControl of type EventCallback<string> which is assigned to the SetValue parameter property:
[Parameter]
public EventCallback<string> SetValue { get; set; }
And it is used (trigger the method which is also called SetValue in the parent component. You can change the name if you like) to pass the changed value from the child component to the parent component.
Use code instead of functions.
Note that I've made some modifications in your code: OnInitialized instead of OnInit (obsolete), sequence numbers should not created the way you do. Refer to this article written by Steve Sanderson ...
Hope this helps...

How to access DropDown values in Struts 2 Action

My requirement is, at beginning I want to show users data on page and when user make changes in form, I want to access changed data.
Below is my code in Action class,
public class DisplayData extends ActionSupport implements ModelDriven<List<User>>, Preparable {
private List<User> userList;
#Override
public void prepare() throws Exception {
userList = new ArrayList<User>();
userList.add(new User("Demo","N"));
userList.add(new User("Demo1","Y"));
userList.add(new User("Demo2","Y"));
userList.add(new User("Demo3","N"));
}
#Override
public List<User> getModel() {
return userList;
}
public String execute(){
for (User value: userList) {
System.out.println(value.getName() +":"+value.getFlag());
}
return "success";
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
User class,
public class User implements Serializable
{
private String name;
private String flag;
public User() {}
public User(String name,String flag) {
super();
this.name = name;
this.flag = flag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
Code in Jsp page,
<s:form name="getData" action="getData" method="post">
<table>
<s:iterator value="model" status="rowStatus">
<tr>
<td>
<s:textfield name="model[%{#rowStatus.index}].name" value="%{model[#rowStatus.index].name}"/>
<s:select name="%{model[#rowStatus.index].flag}" value="%{model[#rowStatus.index].flag}"
list="#{'Y':'Yes','N':'No'}" />
</td>
</tr>
</s:iterator>
</table>
<s:submit name="ok" value="ok" />
</s:form>
When page get rendered, it shows appropriate value of textfield and dropdown.
If I changed the values in Textfield and droprdown and submit the form then I am getting modified value of textfield but for the dropdwon it shows old value. How can I access selected value of dropdown?
Got the answer... :)
It was syntax mistake. Instead of
<s:select name="%{model[#rowStatus.index].flag}" value="%{model[#rowStatus.index].flag}"
list="#{'Y':'Yes','N':'No'}" />
Use
<s:select name="model[#rowStatus.index].flag" value="%{model[#rowStatus.index].flag}"
list="#{'Y':'Yes','N':'No'}" />
I have used %{ } in name attribute..

PrimeFaces AutoComplete error

I am facing a strange problem with p:autoComplete, I get following error
java.lang.NumberFormatException: For input string: "player"
My code is as below
xhtml
<p:autoComplete id="schedChemAC" value="#{testMB.selectedPlayer}" completeMethod="#{testMB.completePlay}" process="#this" var="m" itemLabel="#{m.player}" itemValue="#{m}" converter="#{testConverter}">
<p:ajax event="itemSelect" listener="#{testMB.onSelectFrstL}" process="#this"/>
</p:autoComplete>
MBean
public List<Player> getSelectedPlayer() {
return selectedPlayer;
}
public void setSelectedPlayer(List<Player> selectedPlayer) {
this.selectedPlayer = selectedPlayer;
}
public void getName() {
playerName = playerSession.getAll();
}
public List<Player> completePlay(String query) {
List<Player> suggestion = new ArrayList<Player>();
if (playerName == null) {
getName();
}
for (Player c : playerName) {
if (c.getPlayer().toUpperCase().contains(query.toUpperCase())) {
suggestion.add(c);
}
}
return suggestion;
}
public void onSelectFrstL(SelectEvent event) {
}
Converter
#Named(value = "testConverter")
public class TestConverter implements Converter {
#EJB
PlayerSession playSession;
public static List<Player> playLst;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (playLst == null) {
playLst = playSession.getAll();
}
if (value.trim().equals("")) {
return null;
} else {
try {
int number = Integer.parseInt(value);
for (Player c : playLst) {
if (c.getPk() == number) {
return c;
}
}
} catch (Exception ex) {
System.out.println("error");
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
return String.valueOf(((Player) value).getPk());
}
}
}
I am not able to find what is wrong in the above code, if i remove the var,itemValue,itemLabel,converter part then it works fine but once i put the var,itemValue,itemLabel,converter code (as given in prime showcase) i get the above error.
Kindly guide me on what is that i am doing wrong or what is that i should check.
Note: My sample table has only two columns, pk(int) & player(string).
I figured out the problem, its basically if i Pass a List to value(AutoComplete) then the Multiple="true" has be used. Whereas to just do one selection i need to pass only Player object to value(AutoComplete).
Hope this helps somebody else who post without understanding how it works (like me).

Prepopulating form's textfields with bean default value in Struts2

In Struts 1.x , I have prepopulated the forms text fields using form bean's with default values as follows,
<html:form action="/actions/signup1">
First name: <html:text property="firstName"/><BR>
And in form bean, I have default value as follows...
public class ContactFormBean {
private String firstName = "First name";
But in Struts 2.x , when I tried with struts-tags textfield as follows, its not prepopulating the default value from the bean,
<s:form action="signup1">
<s:textfield name="formBean.firstName" label = "First Name" />
I have the formBean declared in my Action class as follows with appropriate getter and setter methods...
public class SignupAction1 extends ActionSupport {
private ContactFormBean formBean;
#Override
public String execute() throws Exception {
....
}
public ContactFormBean getFormBean(){
return formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
}
Please let me know if this can be accomplished at Request level and not at session level.
Thanks in advance.
<--Edited-->
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="basicstruts2" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="signup">
<result>/SignUp.jsp</result>
</action>
<action name="signup1" class="coreservlets.action.SignupAction1" method="execute">
<result name="success">/SignUp-Confirmation.jsp</result>
<result name="error">/SignUp.jsp</result>
</action>
</package>
</struts>
SignUp.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sign UP</title>
</head>
<body>
<H1 ALIGN="CENTER">Sign Up</H1>
<s:form>
<s:textfield name="formBean.firstName" label = "First Name" />
<s:textfield name="formBean.lastName" label = "Last Name" />
<s:textfield name="formBean.email" label = "Email Address" />
<s:textfield name="formBean.faxNumber" label = "Fax Number" />
<s:submit action="signup1" method="loginAfterSubmit" value="Click here to Submit"/>
</s:form>
</body>
</html>
ContactFormBean.java
public class ContactFormBean {
private String firstName = "First name";
private String lastName = "Last name";
private String email = "user#host";
private String faxNumber = "xxx-yyy-zzzz";
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return(lastName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return(email);
}
public void setEmail(String email) {
this.email = email;
}
public String getFaxNumber() {
return(faxNumber);
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
public boolean isMissing(String value) {
if ((value == null) || (value.trim().equals(""))) {
return(true);
} else {
for(int i=0; i<defaultValues.length; i++) {
if (value.equals(defaultValues[i])) {
return(true);
}
}
return(false);
}
}
}
SignupAction1.java
public class SignupAction1 extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private ContactFormBean formBean;
#Override
public String execute() throws Exception {
this.formBean = new ContactFormBean();
return SUCCESS;
}
public String loginAfterSubmit() {
String firstName = formBean.getFirstName();
String lastName = formBean.getLastName();
String email = formBean.getEmail();
String faxNumber = formBean.getFaxNumber();
if (formBean.isMissing(firstName)) {
return ERROR;
} else if (formBean.isMissing(lastName)) {
return ERROR;
} else if ((formBean.isMissing(email)) ||
(email.indexOf("#") == -1)) {
return ERROR;
} else if (formBean.isMissing(faxNumber)) {
return ERROR;
} else {
return SUCCESS;
}
}
public ContactFormBean getFormBean(){
return this.formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
}
Change your signup action declaration to
<action name="signup" class="coreservlets.action.SignupAction1">
<result>/SignUp.jsp</result>
</action>
and signup1 to
<action name="signup1" class="coreservlets.action.SignupAction1" method="signup1">
create method signup1 in your SignupAction1 action class and move your logic from execute to it. In execute then create new instance of your ContactFormBean.
put your default value to the constructor:
public class ContactFormBean {
private String firstname;
public ContactFormBean (){
this.firstName = "First name";
}
}
You are returning a null formBean object with the getFormBean method,
then the constructor is never called and the attempt to acces the formBean attribute firstName is giving an error (that is not showed because it is wrapped by the Struts2 tag on the JSP.
You can
1) instantiate it on your execute method:
public String execute() throws Exception {
this.formBean = new ContactFormBean();
}
2) instantiate it lazily on your getter:
public ContactFormBean getFormBean(){
if (formBean==null)
this.formBean = new ContactFormBean();
return this.formBean;
}
EDIT (due to your comments):
I don't know how you've structured your web application;
But if you are on a JSP, an Action (and its execute() method, or another method if specified) was called BEFORE rendering the JSP.
So, regardless if you have ActionOne loading stuff and ActionTwo called after submit, or ActionOne loading stuff and another method of ActionOne called after submit, you can know if you are in a "pre-JSP" state or in a "post-submit" state...
That said, if you are exposing an Object, and you want its value or its attributes to be different from null, you have to instantiate it in one of the way described above.
Obviously, your object should contain getters and setters for its attributes, and they must have been bound to your JSP objects.
In your example, you could have:
ContactFormBean:
public class ContactFormBean {
private String firstName = "First name";
public String getFirstName(){
return this.firstName;
}
public String setFirstName(String firstName){
this.firstName = firstName;
}
}
Your Action:
public class SignupAction1 extends ActionSupport {
private ContactFormBean formBean;
public ContactFormBean getFormBean(){
return formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
#Override
public String execute() throws Exception {
/* this method is executed before showing the JSP */
/* first time initialization */
this.formBean = new ContactFormBean();
return SUCCESS;
}
public String loginAfterSubmit() throws Exception {
/* this method is executed after the submit button was pressed */
/* i don't initialize nothing here,
ContactFormBean is coming from the page */
System.out.println("ContactFormBean's firstName value is: " +
this.formBean.getFirstName());
return "goSomewhereElse";
}
}
and in Your JSP:
<s:form>
<s:textfield name="formBean.firstName" label = "First Name" />
<s:submit action="signup1" method="loginAfterSubmit" value="Press here to submit" />
</s:form>
You can do this with two Action by splitting the execute() and the loginAfterSubmit() methods into two execute() methods of two different Actions;
Then you must have your formBean in BOTH the Actions, with at least the getter in the first, and the setter in the second.
You can also set the Name value in your bean in execute method, it will populate it in your JSP page. Example is :
public String execute() throws Exception {
this.formBean = new ContactFormBean();
//Set your Name value here
formBean.setName("John Doe");
return SUCCESS;
}
Once JSP is populated you will find this value in Name text box.
Hope this will help.
Tapan

Struts2 Iteration of ArrayList with JavaBean

This Question may be asked in several threads...but could not fine the correct answer
a Java Bean
package com.example;
public class Document {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
An ArrayList creation of JavaBean as displayed below
package com.example;
import java.util.ArrayList;
public class classdocs {
public ArrayList getData() {
ArrayList docsmx = new ArrayList();
Document d1 = new Document();
d1.setName("user.doc");
Document d2 = new Document();
d2.setName("office.doc");
Document d3 = new Document();
d3.setName("transactions.doc");
docsmx.add(d1);
docsmx.add(d2);
docsmx.add(d3);
return docsmx;
}
}
an Action Class
package com.example;
import java.util.ArrayList;
import com.opensymphony.xwork2.ActionSupport;
public class FetchAction extends ActionSupport {
private String username;
private String message;
private ArrayList docsmx = new ArrayList();
public ArrayList getDocuments() {
return docsmx;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String execute() {
classdocs cx = new classdocs();
if( username != null) {
docsmx = cx.getData();
return "success";
} else {
message="Unable to fetch";
return "failure";
}
}
}
Jsp with Struts2 Iterator Tag
Documents uploaded by the user are:</br>
<s:iterator value="docsmx">
<s:property value="name" /></br>
</s:iterator>
Question Why the ArrayList of Bucket containing JavaBean not displayed when Iterated ...
Am I doing some thing wrong ???
with regards
karthik
Depending your version, you should either provide a getter for docsmx (preferred, pre-S2.1.mumble), or make docsmx public (not as preferred, S2.1+).
Or, based on your code, use the correct getter:
<s:iterator value="documents">
<s:property value="name" /></br>
</s:iterator>
A couple of notes: documents should likely be declared a List, not ArrayList, although in this case it almost certainly doesn't matter. It's a good habit to get in to, though, coding to an interface when the implementation doesn't matter.
I'd also consider tightening up the code a little bit:
public String execute() {
if (username == null) {
message = "Unable to fetch";
return "failure";
}
docsmx = cs.getData();
return "success";
}
This allows a more natural reading, makes it more clear what the two states are (success and failure), keeps them very distinct, and slightly shorter.

Resources