Pass a parameter with struts 2 action - struts2

How can I pass a parameter with struts 2 action?.
Here is my code.
<s:form>
<s:select name="menuItem" list="menuItems" listKey="menuItemID"
listValue="menuItemName" headerKey="" headerValue="--MenuItems--"
cssClass="selectbox_bg2" id="select"
onchange="handleChange(this.value)" />
<s:textfield name="select_value" id="select_value" />
</s:form>
<script type="text/javascript">
function handleChange(value) {
window.location = "callMyAction?ValueToSubmit=" + value;
}
</script>
My Question is How can I get this parameter(value) in my action class.
and passing a parameter to return jsp page.
Thanks..

1 Just create "valueToSubmit" variable in your action class with public getter and setter
public MyAction extends ActionSupport {
private BigDecimal valueToSubmit;
public String execute{
... some code.....
}
public BigDecimal getValueTOoubmit(){
return valueToSubmit;
}
public void setValueToSubmit(BigDecimal valueToSubmit){
this.valueToSubmit = valueToSubmit;
}
}
Struts2 ParametersInterceptor will get the parameter value from request and set it to action parameer automaticly.
2 To read this parameter in the action result jsp page just use some struts tags
<s:property value="valueToSubmit"/>,
<s:textfield name="valueToSubmit"/>,
etc..

Related

set action class parameters in Struts2

I'm trying to set parameter value bulkID from form in ftl file to action class, but unable to set. Following is the code:
struts.xml file
<action name="bulk" class="com.action.BulkChangeMainAction">
<result name="input" type="freemarker">/resources/templates/bulk-changes.ftl</result>
</action>
BulkChangeMainAction.java
public class BulkChangeMainAction {
private int bulkID;
public int getBulkID() {
return bulkID;
}
public void setBulkID(int bulkID) {
this.bulkID = bulkID;
}
public String input() {
return INPUT;
}
}
bulk-changes.ftl
<form id='filter-form' action="<#s.url action='bulk' method='input'/>" method="post" name="filterForm">
<input type="text" id="bulkID" name="bulkID"/>
<input type="submit" value="Go"/>
</form>
Try using the struts2 form tag and sth like the following (I assume input is the action you want to call?):
<s:form action="bulk.input.action" method="post">
<s:textfield name="bulkId" label="Bulk Id" />
<s:submit value="Confirm" />
</s:form>
Here is a nice complete example too:
http://www.codejava.net/frameworks/struts/handling-form-data-in-struts2
if you need to keep the current format you have, please try changing int to String or Integer and see if it works.

Struts 2 String to Double Conversion on ValueStack

I am new to Struts2 and following "Struts2 in Action". I have one question
My book says if you are using data-type different then String , you need to tell compiler that its no longer String and define property file named DataTransferTest-conversion.properties with Element-weights=java.lang.Double in case of List (i.e you are using Double type in your List).
However , when i did this practically , i didn't specified my property file. Still , its working. I don't know!! Why?
I am attaching my code layers. Please look
Action Class
public class ListExampleAction extends ActionSupport implements ModelDriven<ListExample> {
ListExample example = new ListExample();
private List<ListExample> listExample;
private Double x;
//Getters Setters//
#Action(value="/ListExample", results={
#Result(name="success",location="/listExampleDisplay.jsp"),
})
public String execute() throws Exception {
return "success";
}
Display Action Class( just to return jsp)
public class DisplayListExampleAction extends ActionSupport{
#Action(value="/ListExampleAction", results={
#Result(name="success",location="/listExample.jsp"),
})
public String execute() throws Exception {
return "success";
}
}
List Example Class for List Type
public class ListExample{
private String firstName;
private Double age;
//getter/setters//
}
listExample.jsp
<html>
<head></head>
<body>
<h1>Struts </h1>
<form action="ListExample">
// For List
<s:textfield name="listExample.firstName" label="User 1 Name"></s:textfield>
<s:textfield name="listExample.age" label="User 1 Age"></s:textfield>
// For x varaible in Action Class
<s:textfield name="x" label="x"></s:textfield>
<s:submit></s:submit>
</form>
</body>
</html>
listExampleDisplay.jsp
<html>
<head></head>
<body>
<h1>Struts</h1>
// For List
Users List =
<s:iterator value="listExample">
<s:property value="firstName" />
<s:property value="age" />
</s:iterator>
<br>
// For x varaible in Action Class
<s:property value="x"/>
</body>
</html>
Output:
UserAge =21
User Name = Saurabh
x = 21.0
Because the book is really old and covers only Struts 2.0.
Back then many types did require a conversion specification.
Later versions improved their ability to automatically convert between types through introspection.
IIRC that earlier book also didn't cover the annotations covered by some later books.

Unable to populate data from form fields into the action class data members in struts2

I created a jsp page which has a form , I am trying to populate the data members of the action classfrom this form, after submitting the form the control is being moved to the action class but the action class data members are not populated.
my jsp page looks like this.
<s:actionerror />
<s:form action = "retrieve" method="post">
<s:textfield name = "form1" value = "form1" />
<s:textfield name="cid"/>
<s:submit type = "submit" name = "sub" value="submit"/>
</s:form>
my action class looks like this.
public class CustomerUpdate extends ActionSupport {
private String form1 ;
private String cid ;
public String execute() {
System.out.println(form1) ;
System.out.println(cid) ;
}
Here after submission of form I expect form1 variable in action class should have the value as "form1" but it is still null.
can anyone help where am I going wrong?
Thanks in advance.....
I am not sure if you have configuration file that maps action class to your jsp file.
normally configuration file is an xml file in your src folder. example:
<struts>
<package name="default" extends="struts-default">
<action name="retrieve" class="CustomerUpdate">
<result>/xxx.jsp</result>
</action>
</package>
</struts>
Since your execute method is of return type string, return some string. Based on string returned from execute method you can redirect. otherwise change it to void.
If you already have properly configured action class with your jsp, then for using member variables, code in jsp might look like:
<form action = "retrieve" method="post">
<s:textfield name = "form1" value = "${form1}" />
<s:textfield name="${cid}"/>
<s:submit type = "submit" name = "sub" value="submit"/>
</form>
and also since member variable are private:
system.out.println(getForm1);
system.out.println(getCid);
Hope that helps
At first place, your code will not compile.
As i assume that struts.xml file contains below lines,
<action name="retrieve" class="CustomerUpdate" method="execute">
<result name="success">/success.jsp</result>
</action>
Update the CustomerUpdate as below and check the program.
public class CustomerUpdate extends ActionSupport {
private String form1 ;
private String cid ;
public String execute() {
System.out.println(form1) ;
System.out.println(cid) ;
return "success";
}
//getter & setter for form1 & cid
}
please try out the above code sample and i think it will work.

how to understad a form is submitted in struts actions

In struts2 actions the injection is used for setting the property values of an action class, so the properties are updated by form fields on the form submission. To discover which form is submitted I create a method calling isFormSubmitted() and in there I check a redundant property created only for this motive. The property is updated in a hidden field. But I find this workout so dirty! I think that there must be a better way to solve this problem.
What I do is:
<s:form name="form1">
<s:hidden name="submit" value="10" />
...other fields go here
</s:form>
in the action class I have getSubmit, setSubmit methods and the following method:
public boolean isFormSubmitted(){
return (submit == 10);
}
Your can call different action methods in your action, not only "execute" method. Just put the parameter with the name like "method:actionMethodName" in your request. Here is example:
public class MyAction extends ActionSupport {
public String execute() {
// Base code
return SUCCESS;
}
public String one() {
// Code one
return SUCCESS;
}
public String two() {
// Code two
return SUCCESS;
}
}
And here is jsp:
<s:form action="MyAction">
<input type="submit" value="Call execute"/>
<input type="submit" name="method:one" value="Call method one"/>
<input type="submit" name="method:two" value="Call method two"/>
</s:>
Or you can do it like this:
<s:form action="MyAction" name="form0">
<!-- call execute-->
</s:>
<s:form action="MyAction" name="form1">
<!-- call method one-->
<input type="hidden" name="method:one"/>
</s:>
<s:form action="MyAction" name="form2">
<!-- call method two-->
<input type="hidden" name="method:two"/>
</s:>
You should use <s:form> tag action attribute to submit to specific action.
<s:form action="action1">
...
</s:form>
<s:form action="action2">
...
</s:form>
See the <s:form> tag documentation: http://struts.apache.org/2.x/docs/form.html.
Update
Then just use separate actions for loading and saving the user.
you should do the submission of the form something like this.
<s:form name="form1">
<s:hidden name="submit" value="10" />
</s:form>
create a java script function
function onclick()
{
document.form1.submit();
}
then create getters & setters in action for hidden field
and in execute method
public String execute()
{
setSubmit(10);
return SUCCESS;
}
Update :
or
<s:a href="your_action"></a>

Struts 2 Populate select drop list

Hi i want to populate the select drop down list with some value. I use Struts 2, Tiles and JSP. I initialize my list in the Action class but i am still getting the following error :
Caused by: tag 'select', field 'list', name 'anneeResultat': The requested list key 'anneesResultatsList' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
Here is my code in Action class:
private AnneeResultat anneeResultat;
private Map<String, String> anneesResultatsList = new HashMap<String, String>();
public Map<String,String> getAnneesResultatsList() {
this.anneesResultatsList.put("2005","2005");
this.anneesResultatsList.put("2006","2006");
this.anneesResultatsList.put("2007","2007");
this.anneesResultatsList.put("2008","2008");
this.anneesResultatsList.put("2009","2009");
this.anneesResultatsList.put("2010","2010");
this.anneesResultatsList.put("2011","2011");
return this.anneesResultatsList;
}
public void setAnneesResultatsList(Map<String,String> anneesResultatsList) {
this.anneesResultatsList = anneesResultatsList;
}
return SUCCESS;
}
My struts.xml file contains :
<action name="ChoixAxes" class="fr.si2m.occ.web.actions.ChoixAxesAction"
method="execute">
<result type="tiles">choixAxes.tiles</result>
</action>
My jsp is here:
<s:set name="theme" value="'xhtml'" scope="page" />
<s:form action="ChoisirAxes" name="choices" id="choices">
<s:select name="anneeResultat" label="Année de résultats" list="anneesResultatsList"></s:select>
<s:radio label="Listes nominatives" name="listesNominatives" list="#{'1':'Oui','2':'Non'}" value="2" />
<s:submit value="Calculer provisions" name="calculerProvisions"/>
<s:reset value="Annuler" />
<input type="button" value="Critères sauvegardés" id="criteresSauvegardes"/>
</s:form>
Some one could help me please ?
I have this problem since yersterday.
Prepare interceptor calls prepare() on actions which implement
Preparable. This interceptor is very useful for any situation where
you need to ensure some logic runs before the actual execute method
runs.
Your action should extend Preparable interceptor and override prepare() method, give the pre populated data.
Struts2 Prepare Interceptor
Put AnneesResultatsList in session
Map session=ActionContext.getScession();session.put("list",AnneesResultatsList );
<pre>
s:select name="anneeResultat" label="Année de résultats" list="%{#session.list}""></s:select>
</pre>
actually it is,
Map session = ActionContext.getcontext().getsession();
session.put("key",list);
<s:select list="%{#session.key}">

Resources