struts2 get property with dynamic value in jsp - java

I have a problem with struts property, pl check my sample code.
in struts action class i have a property that is name2,
SampleAction.java
public class SampleAction extends ActionSupport
{
private String name2;// setter and getter is also there
}
if i use like below i ll get the value
<s:property value="name2"/>
I wan to get the name2 value in jsp in dynamic way,
but here i need pass the value 2 in dynamic way some thing like below..
<s:set name="nameNumber" value="2" />
<s:property value="name%{#nameNumber}"/>
How can i achieve that.
Thanks in Advance,
Prabhakar Manthena

Related

Parameter passed to JSP via struts to JSP variable

Im a Java newbie, I have this code working which obtains the brandCode parameter and places in a hidden input named "brandCode"
<html:form method="get" action="/catalogindexsearch.do" styleId="sortAndNavigationForm">
<input type="hidden" name="formAction" value="searchDisplay" />
<html:hidden property="brandCode" />
</html:form>
But I wish to use the parameter elsewhere in my JSP i.e.
<h1>Brand Code: ${brandCode}</h1>
So my question is how can I create a Java variable from the html:form URL parameter?
In JSTL you can access a form property by form name
<h1>Brand Code: ${formName.brandCode}</h1>
Give it an ID like this:
<html:hidden property="brandCode" id="brandcode" />
then access the value by:
var brandCode = $("#brandcode").val();
or if you're not using jQuery:
var brandCode = document.getElementById("brandcode").value;
If you're trying to use the value of a property from your action class, you had it right - It's
${brandcode}
where brandcode is a property in your action class with getters and setters:
private String brandcode;
public String getBrandCode() {
}
you get the point.
What I was after in the end was this ${param.brandCode} or this ${param["brandCode"]}.

In Struts2, dynamically generate form element name using a member value

My requirement: In Struts 2, dynamically generate form element name by using member value.
I had tried with: <s:textarea name="employee_<s:property value='employeeNumber'/>"/>
Resulting code in web browser: <textarea name="employee_<s:property value='employeeNumber'/>"></textarea>
My expectation in web browser code: <textarea name="employee_101"></textarea>. 101 as an employeeNumber is only used for demonstration only.
Please help, thanks!
In Struts2 you can always use OGNL expression in the Struts tag's attribute. Just provide the value from the value stack. You should know that the action bean is on top of it, and having a getter for employeeNumber should return desired value 101.
<s:textarea name="employee_%{employeeNumber}"/>
Also be aware of Struts doesn't allow nested tags in the attributes in favor of OGNL.
try this,it working fine.
MyAction.class
private int property_value;
public int getProperty_value() {
return 6;
}
public void setProperty_value(int property_value) {
this.property_value = property_value;
}
result.jsp
<s:set var="xyz" value="property_value" />
<s:textarea name="emap_%{#xyz}" />

Reading contents from application map dynamically IN JSP page. - struts 2.0

I am using ApplicationAware in my struts 2.0 action class. So, i placed an entry in then application map as
application.put("animalDTO", animalDTO);
animalDTO:
public class AnimalDTO {
private String name_N1;
private String name_N2;
private String name_N3;
private String name_N4;
// getters and setters
}
Now before going to my jsp page i am populating the values in each of the variables.
In JSP page: i am using iterator to get N1, N2 till N4.
Now i need to create s:textfield and populate these variables content DYNAMICALLY.
ie.
<s:iterator value="application.nameList" var="nameList">
<s:textfield theme="simple" value="%{application.animalDTO.name_#nameList}" />
</s:iterator>
Here, i am not getting any values populated.
If i hard code as -> value="%{application.animalDTO.**name_N1**}"
Then all the text-fields will be populated with value of name_N1, but that not what i need. I need for fetch the values dynamically.
Can anyone help me with this OGNL requirement?
Thanks in advance
=====================
I tried this also, i created string variable which is of the required ognl format, but i dont know how to make the string as a lookup to valuestack. This is what i did:
<s:iterator value="application.nameList" var="nameList">
<s:set var="varUrl" value="%{'application.animalDTO.name_' + #nameList}" />
<s:property value="varUrl" />
<s:textfield name="NAME__%{#nameList}" theme="simple" id="NAME-%{#nameList}" value="%{varUrl}" />
</s:iterator>
but instead the text box is getting values like:
application.animalDTO.name_1
application.animalDTO.name_2
application.animalDTO.name_3
application.animalDTO.name_4
what is need is the values corresponding to these variables.
Any idea how to convert this string as an object/key to lookup into valuestack.
Finally i got the solution. I tried many trail and error methods. And finally hit the answers. We can dynamically read the property values by doing:
<s:iterator value="application.nameList" var="nameList">
<s:textfield theme="simple" value="%{application.animalDTO['name_' + #nameList]}" />
</s:iterator>
I tried %{application.animalDTO['name_' + #nameList]} and it worked. :-)

Parsing Struts tag using s:property

In one of our challenging application, I am generating few struts tag dynamically in Action class
Once I generated the struts tag, I want it to get it parsed through s:property
in my JSP:
<s:property value='generateElement("ABC")' escape='false' />
in my Java Action
public String generateElement(String element){
return "<s:select id='aaaa' list=\"{'1':'1','2':'2'}\" >";
}
in the end I want to generate Selection box.
How do I achieve this.
You can't execute JSP code after the JSP has been compiled. So there's no use in returning a JSP tag in your method. Instead, generateElement should return the objects that you need in your select, and then reference that property in a <s:select> tag that is already in your JSP.

Do Spring property editors only work on forms?

I'm working on a Spring application that simply searches a set of data for things that match some criteria. There are two main views: one is a simple form that lets the user configure search criteria, while the other displays the results as a table.
One of the search fields is a closed set of options (about 10). Lower down in the code, I want to handle this as an enum class. The web form includes a drop-down that allows the user to select an option from this set. I've used a form:select to do this, populated with a set of strings that describe the values.
To keep the presentation and business logic separate, the enum class musn't have any knowledge of these strings, so I've created a Property Editor to convert between the two. When I load the form, the select control is set to the string associated with the enum value I gave it; when the form is submitted, the string is converted back to my enum type. This is all working fine.
For the results page (which isn't a form), I simply add the data to be displayed to a ModelMap. At the moment, I have to explicitly convert my enum type to a string before I add it to the map. What I'd like to do is just add the enum to the map and have the property editor convert it for me in the background, like it does for the form. I can't work out how though. Is it possible to do this? Maybe I'm missing something really obvious?
You can use Spring Tablib
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
And use transform markup
<!--If you have a command which command name is account-->
<!--Default command name used in Spring is called command-->
<spring:bind path="account.balance">${status.value}</spring:bind>
Or
<spring:bind path="account.balance">
<spring:transform value="${account.balance}"/>
</spring:bind>
Or
<!--Suppose account.balance is a BigDecimal which has a PropertyEditor registered-->
<spring:bind path="account.balance">
<spring:transform value="${otherCommand.anotherBigDecimalProperty}"/>
</spring:bind>
About value attribute
The value can either be a plain value to transform (a hard-coded String value in a JSP or a JSP expression), or a JSP EL expression to be evaluated (transforming the result of the expression). Like all of Spring's JSP tags, this tag is capable of parsing EL expressions itself, on any JSP version.
Its API
Provides transformation of variables to String, using an appropriate custom PropertyEditor from BindTag (can only be used inside BindTag)
If you use MultiActionController i advice you to use a Dummy Command class as bellow
public class Command {
public BigDecimal bigDecimal;
public Date date;
/**
* Other kind of property which needs a PropertyEditor
*/
// getter's and setter's
}
Inside your MultiActionController
public class AccountController extends MultiActionController {
#Autowired
private Repository<Account, Integer> accountRepository;
public AccountController() {
/**
* You can externalize this WebBindingInitializer if you want
*
* Here it goes as a anonymous inner class
*/
setWebBindingInitializer(new WebBindingInitializer() {
public void initBinder(WebDataBinder dataBinder, WebRequest request) {
binder.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, numberFormat, true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
}
});
}
public ModelAndView(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView()
.addAllObjects(
createBinder(request, new Command())
.getBindingResult().getModel())
.addObject(accountRepository.findById(Integer.valueOf(request.getParameter("accountId"))));
}
}
Inside your JSP
<c:if test="{not empty account}">
<!--If you need a BigDecimal PropertyEditor-->
<spring:bind path="command.bigDecimal">
<spring:transform value="${account.balance}"/>
</spring:bind>
<!--If you need a Date PropertyEditor-->
<spring:bind path="command.date">
<spring:transform value="${account.joinedDate}"/>
</spring:bind>
</c:if>
It is useful when your Target command does not provide a PropertyEditor which needs to be used in another command.

Categories

Resources