Retaining values between multiple JSPs and Actions in Struts 2 - java

My Struts project structure is as follows:
page1->action1->page2->action2->page3
What i need is for a value i entered in an input tag in page1 to be accessed in action2.
Here is my code:
page1:
<div class = "container">
<s:form id = "idinput" method = "post" action = "idEntered">
Enter id: <input id = "txtid" name = "txtid" type = "text" />
<input id = "cmdsubmit" name = "cmdsubmit" type = "submit" value = "enter details" />
</s:form>
</div>
action1:
public class AddId extends ActionSupport {
private int txtid;
//getter and setter
#Override
public String execute() throws Exception {
return "success";
}
}
page2:
<div class = "container">
<s:form id = "formvalues" method = "post" action = "formEntered">
<p>Your id entered is: <s:property value = "txtid" /></p>
First name: <input id = "txtfname" name = "txtfname" type = "text" />
Last name: <input id = "txtlname" name = "txtlname" type = "text" />
Age: <input id = "txtage" name = "txtage" type = "text" />
<input id = "cmdform" name = "cmdform" type = "submit" value = "submit form" />
</s:form>
</div>
action2:
public class AddForm extends ActionSupport {
private String txtfname;
private String txtlname;
private int txtage;
private int txtid;
//getters and setters
#Override
public String execute() throws Exception {
return "success";
}
}
and displaying everything in
page3:
<div class = "container">
ID: <s:property value = "txtid" /><br>
first name: <s:property value = "txtfname" /><br>
last name: <s:property value = "txtlname" /><br>
age: <s:property value = "txtage" />
</div>
this is where I face a problem as txtid is displayed as null, from which I inferred that the value is not passed from page2 to action2
a solution i have come up with is to use
<s:hidden value = "%{txtid}" name = "txtid2 />
in my form in page2 which will allow me to use the value of txtid as txtid2 in action2, this however seems more like a hack than an actual solution, so any other suggestions are welcome.

In the situation where you want to keep the field values passed from one action to another you could configure the scope of the field. Just place the same field with getters and setters in each action, in your case it will be action1 and action2. The field name is txtid. As well as scope interceptor doesn't include in the defaultStack you should reference it in the action configuration.
For example:
<action name="action1" class="com.package.action.AddId">
<result>/jsp/page2.jsp</result>
<interceptor-ref name="basicStack"/>
<interceptor-ref name="scope">
<param name="key">mykey</param>
<param name="session">txtid</param>
<param name="autoCreateSession">true</param>
</interceptor-ref>
</action>
<action name="action2" class="com.package.action.AddForm">
<result>/jsp/page3.jsp</result>
<interceptor-ref name="scope">
<param name="key">mykey</param>
<param name="session">txtid</param>
<param name="autoCreateSession">true</param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
</action>
Now you have the scope with the key mykey and field txtid under it. Providing accessors to the field in each action will make transfer field value from one action to another.
In the example above used the basicStack which is a skeleton for the interceptor stack and it does not include some interceptors including a validation interceptor.
If you need to have other features to your actions, you should either construct a custom stack or reference other interceptors in the action configuration.

Related

make a button disable/enable base on java flg in the struts2

Action:
public class TuAction() extends ActionSupport{
private boolean loseItemFlg=false;
private String doFuilureOrder(){
if(...){
loseItemFlg=true;
}
return SUCCESS;
}
public boolean isLoseItemFlg() {
return loseItemFlg;
}
public void setLoseItemFlg(boolean loseItemFlg) {
this.loseItemFlg = loseItemFlg;
}
}
And my Jsp:
function dialogOpen(formName,actionName){
if(comfirm("do you want do this?")){
....
document.forms[formName].action=actionName;
document.forms[formName].submit();
}else{
//i want do not reload the page.
}
}
<input type="button" disable="%{loseItemFlg}" value="lose"
onclick="dialogOpen('tuAction', '<%request.getContextPath()%>/tuAction_doFuilureOrder.action')"
/>
But this code the button's disable property is not by my control!!
Then i change the jsp to:
<s:submit type="button" disable="%{loseItemFlg}" value="lose"
onclick="dialogOpen('tuAction', '<%request.getContextPath()%>/tuAction_doFuilureOrder.action')"
/>
Now the button's disable property is by my control,but the "doFuilureOrder()" is not by used.
About do not reload the page should do what in my jsp.
My English is terrible,And this is my first time to use the stackoverflow. Someone know what I means.
For the input tag, disabled property is not based on true/false. When u write disabled attribute then the input is disabled by default, Please check Fiddle
<input type ='button' disabled='true' value='Button1'/>
<input type ='button' disabled='false' value='Button2'/>
In above code, both buttons is in disabled state.
For your purpose we can rewrite your code as:
Method 1:
By using struts if tag
<s:if test="%{loseItemFlg}"> // if true - button disabled state
<input type="button" disabled value="lose" onclick="dialogOpen('tuAction','<%request.getContextPath()%>/tuAction_doFuilureOrder.action')"/>
</s:if><s:else> //button enabled
<input type="button" value="lose" onclick="dialogOpen('tuAction','<%request.getContextPath()%>/tuAction_doFuilureOrder.action')"/>
</s:else>
Method 2:
Rewrite your java code as,
private String loseItemFlg='';
private String doFuilureOrder(){
if(...){
loseItemFlg="disabled";
}
return SUCCESS;
}
public String getLoseItemFlg() {
return loseItemFlg;
}
public void setLoseItemFlg(String loseItemFlg) {
this.loseItemFlg = loseItemFlg;
}
then in jsp :
<input type = "button"
<s:property value="%{loseItemFlg}"/> value="lose" onclick = "dialogOpen('tuAction'),'<%request.getContextPath()%>/tuAction_doFuilureOrder.action')" />
You can't nest scriptlet in Struts tags (like in your second case), while you can (but you should NOT, because using scriptlets is a bad-practice) inject them in HTML tags.
You can then use the <s:property /> tag in the HTML tag (first case)
<input type = "button"
disable = "<s:property value="%{loseItemFlg}"/>"
onclick = "dialogOpen('tuAction'), '<%request.getContextPath()%>/tuAction_doFuilureOrder.action')"
/>
, or substitute the scriptlet in your Struts tag (second case), better using the <s:url /> tag to mount the URL:
<s:url action = "tuAction_doFuilureOrder.action"
namespace = "/"
var = "myUrl"
/>
<s:submit type = "button"
disable = "%{loseItemFlg}"
onclick = "dialogOpen('tuAction'), '%{myUrl}')"
/>
they both work.
The <s:url /> usage can (and should) be applied to the first case too:
<s:url action = "tuAction_doFuilureOrder.action"
namespace = "/"
var = "myUrl"
/>
<input type = "button"
disable = "<s:property value="%{loseItemFlg}"/>"
onclick = "dialogOpen('tuAction', '<s:property value="%{#myUrl}"/>')"
/>

Why submitting a form with Ajax it's not setting model data using ModelDriven in Struts 2?

I have following situation in code:
Action class:
#NameSpace("/")
public class MyAction extends ActionSupport implements ModelDriven<Car> {
private Car car = new Cart();
#Override
public Car getModel() {
return car;
}
#Action(value = "pageAction", results = {name = SUCCESS, location = "myPage", type="tiles"})
public String showPage() {
return SUCCESS;
}
#Action(value = "formSubmitAction", results = {name = SUCCESS, location = "results.jsp"})
public String formSubmitAction() {
System.out.println(car);
// everything has default values (nulls)
return SUCCESS;
}
}
View for myPage location:
<s:form
namespace="/"
action="pageAction"
method="post" >
<s:push value="model">
<s:textfield name="color" />
<s:textfield name="manufacturer" />
<sj:submit
href="formSubmitAction"
targets="output" />
</s:push>
</s:form>
<div id="output"></div>
results.jsp:
renders empty content into div#output
<s:property value="%{model}" />
<s:property value="%{model.color}" />
<s:property value="%{model.manufacturer}" />
I wonder why is that happening? Model data is not updated after submit.
I'm using struts2-jquery submit tag.
When I'm using simple form submit without Ajax the model is being updated,
but I want to load data asynchronously with Ajax.
How can I achieve that?
The solution is to add ID to form and to sj:submit tag. But I don't know why submit tag inside form wasn't working properly. The correct code is below:
<s:form
id="formId"
namespace="/"
action="pageAction"
method="post" >
<s:push value="model">
<s:textfield name="color" />
<s:textfield name="manufacturer" />
<sj:submit
formIds="formId"
href="formSubmitAction"
targets="output" />
</s:push>
</s:form>
EDIT
As it turns out you only have to add ID to form, and everything works :)
look at link in the comment below
The modelDriven interceptor pushes a model on top of the valueStack. So you can access model properties directly.
<s:property value="%{color}" />
<s:property value="%{manufacturer}" />

struts 2 action error : retrieves values of form properties

Problem
I am using jsp to submit a form and struts 2 action class takes care of it. If there is some problem, then i am sending the result to same page with an error message.
Along with the error message, i want to display property values that he had provided while submitting the request.
Source code
Form contains few text fields and few file type inputs.
My CreateRequest.jsp file:
<input type="file" name="attachment" id="myFile1" />
<input type="file" name="attachment" id="myFile2" />
<input type="file" name="attachment" id="myFile3" />
<input type="text" name="operationName" id="operation1" />
<input type="text" name="operationName" id="operation2" />
<input type="text" name="operationName" id="operation3" />
My Action class :
public class CreateRequest extends ActionSupport {
private List<File> attachment;
private List<String> attachmentContentType;
private List<String> attachmentFileName;
private List<String> operationName
// contains getter and setter for each property
public string execute(){
// some logic
//returns error if it fails otherwise success
}
}
struts.xml (Action Servlet) file:
<action name="createRequest"
class="action.CreateRequest">
<result name="success">RequestStatus.jsp
</result>
<result name="input" >CreateRequest.jsp</result>
<result name="error" >CreateRequest.jsp</result>
</action>
HELP
How do i get all those values displayed in CreateRequest.jsp page, when the action class returns error.
use ognl value=" %{operationName[0]}" for text box

passing property value using javascript

I am new to struts 2. I have a jsp page which will send a column ID to another jsp page which will send it to the action class where i will get the comments entered by user and return it to my second jsp page to display it as a popup to the user. problem is my javascript is not accepting the value of the column.
//THIS IS WHERE THE PROBLEM IS IN THE JAVA SCRIPT
<display:column title="Commentaire" sortable="true" sortProperty="Commentaire" class="alerte_td_commentaire">
<s:if test="#attr.row.Commentaire != null && #attr.row.Commentaire != ''">
<a href='#' onclick='javascript:var xx = (%{#attr.row.id}).val(); CommenatireToGet(xx);'><img src='/img/icons/ico_comment.png'></a>
</s:if>
</display:column>
//THIS IS MY SECOND JSP PAGE
function CommenatireToGet(value){
$('#divShowCommAcqui').dialog('option', 'position', 'center');
$('#divShowCommAcqui').dialog('open');
var path = buildURL("/valorisation/ajax/CommenatireToGet.do");
$.getJSON(
path,
{idAlerte:value},
function(json){
$('#commentaireAqui').val=getElementbyId(json.hello);
}
)
};
//THIS IS MY ACTION CLASS
public String getComment() throws ServiceException{
jsonData = new LinkedHashMap<String, Object>();
idAlerte= (Integer) getActionSession("idAlerte");
Alerte alerte =svc.retrieve(idAlerte);
if (alerte !=null){
jsonData.put("hello",alerte.getCommentaire());
}
return SUCCESS;
}
//THIS IS MY STRUS TAG
<action name="CommenatireToGet" class="ihm.valorisation.AlerteAction" method="getComment">
<result name="success" type="json">
<param name="root">jsonData</param>
</result>
</action>
You can't use OGNL expressions anywhere in the JSP, only in Stuts2 tag's attributes, even not all of them. So, change
<a href='#' onclick='javascript:var xx = (%{#attr.row.id}).val(); CommenatireToGet(xx);'><img src='/img/icons/ico_comment.png'></a>
to
<a href='#' onclick='CommenatireToGet(<s:property value="%{#attr.row.id}"/>);'><img src='/img/icons/ico_comment.png'></a>

Recieving 'null' values from a jsp page into Struts 2 Action

I have a jsp page and struts 2 Action class . When I submit the form in the jsp , I am getting null values into the action.
The JSP code looks like :
<s:form id="user" name="user" action="initUserAdmin">
<s:textfield name="userName" cssClass="txtbox" size="30" />
<div class="btn"><a href='<s:url action="searchUserAdmin"/>'
title="Search" id="button" class="btn" ><span>Search</span></a></div>
</s:form>
The struts.xml has this part
<action name="*UserAdmin" method="{1}" class="com.mphasis.im.web.action.UserAction">
<result name="init" type="tiles">user</result>
<result name="search" type="tiles">user</result>
<result name="reset" type="tiles">user</result>
<result name="createNew" type="tiles">createNewUser</result>
</action>
And the Action class has this :
public class UserAction extends BaseAction
{
public String userName;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String search()
{
searchProcessed = true;
System.out.println("******** inside search ******");
System.out.println("username = "+ userName);
return TilesConstants.SEARCH;
}
And the output comes as below when I type a string in the text box in jsp page.
******** inside search ******
username = null
What might be the problem ? Am I missing something ?
<a href='<s:url action="searchUserAdmin"/>'
title="Search" id="button" class="btn" >
It's just a href to the URL of action and with no parameter. Therefore, the 'userName' in the action is null.
<s:form id="user" name="user" action="initUserAdmin">
<s:textfield name="userName" cssClass="txtbox" size="30" />
<div class="btn"><a href='javascript:submitme()'
title="Search" id="button" class="btn" ><span>Search</span></a></div>
</s:form>
Javascript
function submitme(){
document.user.submit()
}
Also in the action mapping you provided the action name you are using there is UserAdmin whereas in the form action you are using initUserAdmin.They must be the same

Categories