Struts 2 String to Double Conversion on ValueStack - struts2

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.

Related

Formatting POJO inside Grails/GSP select element

I have the following POJO/POGO:
class Person {
String firstName
String lastName
int age
// ... lots of other fields
}
And a Grails 2.3.6 controller:
class PeopleController {
List<Person> people = new ArrayList<Person>()
def populatePeople() {
// Add lots of people to the 'people' list.
}
def doSomething() {
populatePeople()
render(
view: "people",
model:[
people: people,
]
)
}
}
And then in the GSP:
<div id="peopleSelector">
<g:select name="people" from="${people}" />
</div>
When I run my app I get the <select> element with com.me.myapp.domain.Person#398r4d99-looking values as <option>s. This is obviously Grails not deserializing my Person instances into pretty print form.
I want peoples' first and last names to appear as the select options. Hence, if one of the Person instances in the people list is:
Person smeeb = new Person(firstName: "Smeeb", lastNname: "McGuillocuty")
Then I would expect "Smeeb McGuillocuty" as a select option in the final HTML. How can I accomplish this?
Add the following method to your Person class:
#Override public String toString() {
"$firstName $lastName"
}
And, somewhat unrelated to the actual question, you may have to add an identifier to your option rows to uniquely identify the person. Assuming the Person class has an id property:
<g:select name="people" from="${people}" optionKey="id" />
so that you get the following HTML:
<select name="people" id="people">
<option value="123">Smeeb McGuillocuty</option>
:
Useful link to official doc: http://grails.org/doc/latest/ref/Tags/select.html:
"..The default behaviour is to call toString() on each element in the from attribute.."
If you can't/won't "sacrifice" toString() for rendering in HTML you can also tell the g:select how to render the options. Either by providing the name of a property in optionValue (e.g. optionValue="fullName" and then provide a String getFullName() method (watch out for transients, if you pass a GORM object)) or by providing it directly in the GSP:
<g:select name="person" optionKey="theId" optionValue='${{"$it.lastName, $it.firstName"}}' from="${people}" />

TextBox(HtmlHelper, String) - is view model also searched for a value?

Pro Asp.Net MVC 4 (pg 535):
The string argument is used to search the view data, ViewBag and view
model to find a corresponding data item that can be used as the basic
for the input element. So, for example, if you call
#Html.TextBox("DataValue"), the MVC Framework tries to find some
item of data that corresponds with the key DataValue. The following
locations are checked: • ViewBag.DataValue • #Model.DataValue
Book states that an overload of a Html.TextBox which takes a single string argument checks both ViewData and view model to obtain the value for display. But after experimenting a little, it seems it only checks ViewData for a value, but not also a view model.
Thus, in the output generated from Html.TextBox the value attribute is set to an empty string:
public class Person
{
public string FirstName = "Leila";
}
*.cshtml:
#model HelperMethods.Models.Person
...
#Html.TextBox("FirstName")
Output:
...
<input id="FirstName" name="FirstName" type="text" value="" />
So is the book wrong and TextBox(HtmlHelper, String) checks only ViewData or does it also check a view model?
UPDATE:
public class Person
{
public string FirstName = "Leila";
}
public class HomeController : Controller
{
public ActionResult Index()
{
return View((object)new Person());
}
}
Index.cshtml:
#model Mvc4.Controllers.Person
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
#Html.TextBox("FirstName")
</body>
</html>
Much appreciated
Just did a quick test and it seems that it has to be a property and not a field.
So this should work:
public class Person
{
public string FirstName { get; set; }
}

Pass a parameter with struts 2 action

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..

Struts2 Iterator property value (not working)

I am trying to use the struts iterator to write some data from a List. Student is a class I have defined.
The s:property when used with the value attribute does not seem to work at all.
I have the following code in the JSP:
<s:iterator value="students" var="student">
<h2><s:property /></h2>
<h2><s:property value="firstName" /></h2>
<h2><s:property value="student.firstName" /></h2>
<h2><s:property value="top.firstName" /></h2>
<h2><s:property value="[0].firstName" /></h2>
<h2><s:property value="#firstName" /></h2>
</s:iterator>
On the first property tag works. It prints the toString() of the Student object. All other property tags do not print anything at all.
The toString() method of Student class is as follows:
public String toString() {
return firstName + " " + lastName + " " + Integer.valueOf(age);
}
The Student class has the getFirstName() method as follows:
String getFirstName() {
return firstName;
}
I am using Struts 2.1.6
There are no exceptions in the log files.
When viewing source of html, I just see the empty h2 tags.
I wonder what is the issue here. Any help is appreciated.
Your getFirstName() method only has package-level access. It should be public to be accessible from the JSP.
change it to
public String getFirstName()
and you're set.
As you are using "var" attribute in iterator tag you have to refer the value from the object like
<s:iterator value="students" var="student">
<h2><s:property value="#student.firstName" /></h2>
</s:iterator>
You can write the same code without using var attribute like below
<s:iterator value="students">
<h2><s:property value="firstName" /></h2>
</s:iterator>
Both will works same.

Map multiple objects in to action class in struts2

I have jsp page with multiple item objects. and gives action to Shop_shopCart.action.
inside action class there are cart object with multiple item objects. How it is possible to directly mapping from jsp to action class with multiple list objects.
Demo classes are given below.
<s:form action="Shop_shopCart.action">
// multiple items in cart object
</form>
class ShoppingAction extends ActionSupport{
Cart cart = new Cart();
//getters and setters
//action methods
String shopCart( ) {
// do some
}
}
class Cart{
List<Item> items = new ArrayList<Item>();
//getters and setters
}
class Item{
String name;
int id;
//getters and setters
}
See the type conversion collection and map support docs.
Nutshell: array or map notation (square brackets with an index or key value inside them) is the easiest way to submit a collection of objects in a form.
this example should help
<s:form action="saveaction" theme="css_xhtml">
<s:textfield name="carlist[0].cartid" label="Cart Id"/>
<s:textfield name="carlist[0].items[0].id" label="Item id"/>
<s:textfield name="carlist[0].items[0].name" label="Item Name"/>
<s:textfield name="carlist[1].cartid" label="Cart Id"/>
<s:textfield name="carlist[1].items[0].id" label="Item id"/>
<s:textfield name="carlist[1].items[0].name" label="Item Name"/>
<s:submit value="Click me to submit Cart List"/>
</s:form>

Resources