How to use a variable data as a scope variable in jstl - java

I want to dynamically create variable names in java el.
The problem is that the second line returns sessionScope.saved_activity as a string instead of data.
<c:set var="savedKey" value="sessionScope.saved_${entry.key}" />
<td> <input type="text" name="${entry.key}" value="${savedKey}"> </td>
How can I retrieve the data from a string in el ?

You need to create the sole key name and then use that as a dynamic key of the ${sessionScope} with the brace notation.
<c:set var="savedKeyName" value="saved_${entry.key}" />
<input type="text" name="${entry.key}" value="${sessionScope[savedKeyName]}">

Related

Retrieve an array of parameters from a servlet [duplicate]

I am able to display an ArrayList of beans in a JSP form using JSTL by looping through the list and outputting the bean properties in a HTML input tag.
<c:forEach items="${listOfBeans}" var="bean">
<tr>
<td><input type="text" id="foo" value="${bean.foo}"/></td>
<td><input type="text" id="bar" value="${bean.bar}"/></td>
</tr>
</c:forEach>
How do I code the JSP so that when the page submits then the updated values are in the appropriate item of the the ArrayList?
Given this simplified model:
public class Item {
private Long id;
private String foo;
private String bar;
// ...
}
Here's how you can do it provided ${items} is List<Item>:
<c:forEach items="${items}" var="item">
<tr>
<td>
<input type="hidden" name="id" value="${item.id}" />
<input name="foo_${item.id}" value="${fn:escapeXml(item.foo)}" />
</td>
<td>
<input name="bar_${item.id}" value="${fn:escapeXml(item.bar)}" />
</td>
</tr>
</c:forEach>
(note the importance of fn:escapeXml() as XSS attack prevention)
So, basically, you need to set the item's unique identifier as a hidden input field in each row as shown in above snippet:
<input type="hidden" name="id" value="${item.id}" />
And you should in turn use this id as suffix of name of all input fields in the same row such as:
<input name="foo_${item.id}" ... />
In the servlet, you can collect all values of <input type="hidden" name="id" ...> from all rows by request.getParameterValues(). Just loop over it and then grab the individual inputs by id.
for (String id : request.getParameterValues("id")) {
String foo = request.getParameter("foo_" + id);
String bar = request.getParameter("bar_" + id);
// ...
}
You can also do this all without that id and grab all inputs by name as an array like so name="foo" and request.getParameterValues("foo"), but the ordering of request parameters is not under your control. HTML forms will send it in order, but the enduser can easily manipulate the order.
No need for JavaScript mess here.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
ServletRequest.getParameterMap() returns Map<String, String[]> and ServletRequest.getParameter() returns String?
Send an Array with an HTTP Get

Validate programatically generated form fields on client side and server side

I have a struts2 form that is programatically generated upon request. The element names for all the fields are the same namely idA and paramValue because I am passing the form values as array and looping through it for database inserts. Inserts are now OK, but I am still finding out how to validate the form.
Here's the form:
<s:iterator value="sysParamList" var="sysParam">
<tr>
<td>
<strong><s:property value="paramName" /></strong>
<input type="hidden" name="idA" value="<s:property value="id" />" />
</td>
<td>
<input type="text" name="paramValue" />
</td>
</tr>
</s:iterator>
The properties in my action are declared like
private String[] idA;
private String[] paramValue;
And I pass these in my DAO as-is. The DAO does the looping through the array for database insert.
I can validate forms using jquery.validate IF the form is hard coded in the JSP.

How to get bean values in jsp scriplets and store in a input:text value attribute

<bean:write name="<%=(String) currentItr.next()%>" property="<%=(String) currentItr.next()%>
this creates value (111)
is it a good practice to do the following:
<input type="text" value=<bean:write name="<%=(String) currentItr.next()%>" property="<%=(String) currentItr.next()%>"/>
such that the html generated will look like:
<input type="text" value="111"/>

How to use the index variable of a JSTL forEach loop to access a map entry?

With a forEach loop I'd like to create table cells (for a row) whereas each cell contains an input field of a form. The number of table cells is always fixed (12). That is actually no problem. However, here comes the challenge: the forEach should also enter a variable number of default values into the input fields that have to be obtained from a Map(Long, Double).
This is my (simplified) attempt:
<c:forEach var="number" begin="1" end="12" >
<td>
<input type="text" value="${requestScope.aMapWithData[number]}" />
</td>
</c:forEach>
But this doesn't show any value from the Map in the input fields. I guess the problem is that "number" is of type String and not Long. So I wonder if this problem can be solved without using scriptlets.
What number do you want to show? Is it index number of each map entry?
<c:forEach items="${aMapWithData}" var="item" varStatus="status">
<td>
<c:out value="${status.count}."/>
<input type="text" name="${item.key}" value="${item.value}" />
</td>
</c:forEach>
Try this
<c:forEach items="${aMapWithData}" var="mapEntry">
<c:set var="mapKey" value="${mapEntry.key}"></c:set>
<c:set var="mapValue" value="${mapEntry.value}"></c:set>
</c:forEach>

Struts logic:iterate input field

I currently have the following code and the data is displayed fine.
<logic:iterate name="myList" id="product" indexId="iteration" type="com.mycompany.MyBean">
<tr>
<td> <bean:write name="product" property="weight"/> </td>
<td> <bean:write name="product" property="sku"/> </td>
<td> <bean:write name="product" property="quantity"/> </td>
</tr>
</logic:iterate>
But now I need to make the "quantity" part modifiable. The user should be able to update that field, press submit and when its sent to the server, "myList" should automatically update with the new quantities.
I've tried searching for help on this but all I keep finding is examples on how to display data only, not modify it. Any help would be appreciated.
So this is tricky, because there are many things to get done in order for it to work. First, declare your tags inside the iterator with the html tags, with attribute INDEXED=TRUE and an ID DIFFERENT THAN THE NAME, i also took out the "indexId" attribute to use the simple "index" word for the index:
<logic:iterate name="myList" id="myListI" type="com.mycompany.MyBean">
<tr>
<td> <html:input name="myListI" property="weight" indexed="true"/> </td>
<td> <html:input name="myListI" property="sku" indexed="true"/> </td>
<td> <html:input name="myListI" property="quantity" indexed="true"/> </td>
</tr>
after that, in order for struts to be able to get and set the attributes of your beans, you need to declare EXTRA get and set methods inside your collection object, using the name you wrote in the id of the iterate tag. In this case, you would write 2 extra get and set methods for the "myListI" :
public void setMyListI(int index, myBean value){
this.myList.add(value);
}
public myBean getMyListI(int index){
return this.myList.get(index);
}
I think Th0rndikes answer is mostly correct. My implementation is slightly different, so it might be worth trying this as well.
Form
private List<Parameter> activeParameters;
public List<Parameter> getActiveParameters() {
return activeParameters;
}
public Parameter getParam(int index){
return this.activeParameters.get(index);
}
JSP
<logic:iterate name="MyForm" property="activeParameters" id="param">
<tr>
<td><bean:write name="param" property="prompt"/></td>
<td><html:text name="param" property="value" indexed="true"/></td>
</tr>
</logic:iterate>
In summary, I didn't use Type in the iterate tag, using the property tag instead. In the bean adding a getter with matched the name of the iterate ID in the JSP (param) with an index as a method parameter did the trick.
Take a look at this: http://wiki.apache.org/struts/StrutsCatalogLazyList
Indexed Properties
Struts html tags have an indexed attribute which will generate the
appropriate html to populate a collection of beans when the form is
submitted. The trick is to name the id attribute to the same as the
indexed property.
For example the following jsp...
<logic:iterate name="skillsForm" property="skills" id="skills">
<html:text name="skills" property="skillId" indexed="true"/>
</logic:iterate>
...will generate the following html
<input type="text" name="skills[0].skillId value="..."/>
<input type="text" name="skills[1].skillId value="..."/>
....
<input type="text" name="skills[n].skillId value="..."/>
When the form is submitted BeanUtils will first call the
getSkills(index) method to retrieve the indexed bean followed by
setSkillId(..) on the retrieved bean.
Theoretically, the indexed attribute of the struts html tags could be used for this:
Valid only inside of logic:iterate tag. If true then name of the html tag will be rendered as "id[34].propertyName". Number in brackets will be generated for every iteration and taken from ancestor logic:iterate tag.
But, there is no corresponding indexed attribute on the html:errors tag, which limits its usefulness. Also, the required combination of id, name and property attributes can be rather confusing.
I found it easier to use jsp scriptlets to generate the property name including the iteration index. The following code requires that your form has a string array property "quantity".
<% int idx=0; %>
<logic:iterate ...>
<html:text property='<%= "quantity[" + idx + "]" %>'/>
<html:errors property='<%= "quantity[" + idx + "]" %>'/>
<% i++; %>
</logic:iterate>

Categories