Transferring collection object from one jsp to another - java

I get the data from the database and store it in some collection object in one jsp(say One.jsp). I want this collection object to be available in another jsp(say Two.jsp). It might contain large data. So, I have used java bean for that in the following way.
public class BeanClass implements Serializable{
private HashMap<String,List<String>> myMap;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public HashMap<String,List<String>> getMyMap() {
return myMap;
}
public void setData(HashMap<String,List<String>> myMap) {
this.myMap = myMap;
}
}
I am setting bean in One.jsp in the following way.
<jsp:useBean id="dataObject" class="com.mypack.BeanClass" scope="session"/>
<jsp:setProperty name="dataObject" property="myMap"/>
<%
dataObject.setData(myMapObj);
%>
But I get the following error:
Can't find a method to write property 'dataMap' of type 'java.util.HashMap' in a bean of type 'com.mypack.BeanClass'
Somewhere I found stating that we can't do the set for other things unless it is a string. Is there anyway that I can workaround it to make it work even for collection objects? So that I don't need to rollback lot of things that I have done. If not can someone please suggest how to transfer the collection object from one jsp to another? Example with snippet is appreciated.
Or is it that I am missing some extra configuration to make beans work?
Note: I might have used redirect() method, but here the navigation from One.jsp to Two.jsp is done by clicking on hyperlink(href)
EDIT:
Thanks to Alfreema. His solution worked after I had changed to setMyMap, but in Two.jsp I am facing issue. I try to display only some part of map like below. But it displays everything that is there in Map as if it shows when we use out.println(myMap); and it displays table at the very end of the page after printing the content of whole map.
Two.jsp:
<jsp:include page="header.jsp"/>
<jsp:useBean id="dataObject" class="com.mypack.BeanClass" scope="session"/>
<jsp:getProperty name="dataObject" property="myMap"/>
<%! HashMap<String,List<String>> gottenMap = null; %>
<%
gottenMap = dataObject.getMyMap();
%>
<table>
<tbody>
<%
String selectedPart = request.getParameter("part");
List<String> list = gottenMap.get(selectedPart);
for(int i=0; i<list.size(); i++)
{
%>
<tr>
<td colspan='2'><strong>
<%= list.get(i) %>
</strong></td>
</tr>
<%
}
%>
</tbody>
</table>
I am confused why it does like that without coding for printing the whole collection.

Change this:
<jsp:useBean id="dataObject" class="com.mypack.BeanClass" scope="session"/>
<jsp:setProperty name="dataObject" property="myMap"/>
<%
dataObject.setData(myMapObj);
%>
To this:
<jsp:useBean id="dataObject" class="com.mypack.BeanClass" scope="session"/>
<jsp:setProperty name="dataObject" property="data" value="${myMapObj}"/>
Your setter is called "setData(...)", not "setMyMap(...)". JSP is going to see property="data" and call setData(...).
So that will fix you up, but you didn't show us where you are setting myMapObj. We have to assume that you are setting that up correctly elsewhere and have made it available to the tag via a pageContext.setAttribute("myMapObj", myMapObj); call.
Side note: I recommend you rename the setData(..) method to setMyMap(...) to make it consistent with the getter getMyMap(...). If you do that, then you will need to change the property="..." back to "myMap", just like you had it.

Related

using an attribute of an arraylist in my jsp with struts-bean.tld

I have an issue using an attribute of an arraylist in my jsp.
The arraylist in my ActionForm :
private ArrayList<Account> accounts = new ArrayList<Account>();
The class declaration of the Account object in the Arraylist :
public class Account implements Serializable, Cloneable {
private String bic;
public String getBic() {
return bic;
}
public void setBic(final String newBic) {
bic = newBic;
}
}
The call in my jsp :
<bean:write name="BankAccountsActionForm"
property="accounts.get(0).bic" />
The console error :
javax.servlet.jsp.JspException: No getter method for property accounts.get(0).bic of bean BankAccountsActionForm
Do you have a solution or another way to do this?
I have a terrible alternative using a property accountbic1 directly in the form. But it induces lots of work behind to re affect all the temporary attributes to the real ArrayList.
If you have a collection of items in Struts 1.x, then use the <logic:iterate> tag.
Add the struts-logic.tld taglig on top of your JSP as follows:
<%# taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
Then, using <logic:present> and <logic:iterate> you can iterate your ArrayList as follows:
<logic:present name="accounts">
<logic:iterate id="account" name="accounts">
<bean:write name="account.bic" />
</logic:iterate>
</logic:present>
If you want to iterate a collection and access a particular index, use the indexId on <logic:iterate> like so:
<logic:present name="accounts">
<logic:iterate id="account" name="accounts" indexId="index">
<logic:equal name="index" value="0">
<bean:write name="account.bic" />
</logic:equal>
</logic:iterate>
</logic:present>
The same can be done using JSTL:
<logic:present name="accounts">
<logic:iterate id="account" name="accounts" indexId="index">
<c:if test="${index == 0}">
<bean:write name="account.bic" />
</c:if>
</logic:iterate>
</logic:present>
Make sure that Account class has a getter/setter method for attribute bic.
This is simply the error of getter and setter method. recode your getter and setter according to POJO standard as shown below:
Remove final from setter method and change your setter and getter method name as per POJO standard as shown below :
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
try some thing like:
<bean:write name="BankAccountsActionForm" property="accounts.get(1).bic" />
As it is a ArrayList not Array.
Make sure you have getter setter for accounts in in action class ** BankAccountsActionForm **
public List getAccounts ();
public void setAccounts(List acc);
Change your setter and getter method name as per POJO standard as shown below :
public String getBic() {
return bic;
}
public void setBic(final String newBic)
{ bic = newBic; }
It will work fine
remove final from setter method and try again and write it as follows
public void setBic(String bic )
{ this.bic = bic ; }

Retrieve bean value from list of bean objects using JSP EL

Below is the request attribute set in struts action
ArrayList<HistoryTeardownHeader> list = new ArrayList<HistoryTeardownHeader>();
// add values to list
request.setAttribute("tdbList",list);
Below i have shown how i am getting the list.I am not able to get the value weldtype from this line of code
<c:forEach var="post" items="${requestScope.tdbList}">
<c:out value="${ post.weldType}"></c:out>
<html:hidden property="currentWeld" value="${post.weldType}"/>
</c:forEach>
The below bean is declared in the HistoryTeardownHeader class.
private String weldType;
public String getWeldType() {
return weldType;
}
public void setWeldType(String weldType) {
this.weldType = weldType;
}
Sorry Guys!
The weldType property didnt fetch the value from DB correctly so it didnt reflect correctly.
So the EL code given above is actually correct and working fine!

Bind Collection to Form - why is it not working?

Could someone please help me find out why my attempt to bind Collection to the form in Spring MVC is not working?
Here is how my object looks like -
public class TestObj {
private Integer testNumber;
private String home;
private String destination;
}
Here is my form object that contains list of above object -
public class TestForm {
private List<TestObj> testList;
//contains getter and setter for testList
}
In my controller, I have implemented formBackingObject method -
public class MyController extends SimpleFormController {
public MyController() {
setCommandClass(TestForm.class);
setCommandName("testForm");
}
protected Object formBackingObject(HttpServletRequest request) throws Exception {
if (isFormSubmission(request)) {
testForm = (TestForm) super.formBackingObject(request);
//THIS ALWAYS RETURNS NULL ON FORM SUBMISSION
List<TestObj> testList = testForm.getTestList();
} else {
//load initial data using hibernate. TestObj is hibernate domain object.
List<TestObj> testList = myService.findTestList();
testForm = new TestForm(testList);
}
return testForm;
}
Here is my JSP snippet -
<form:form commandName="testForm" method="post">
<c:forEach items="${testForm.testList}" var="testvar" varStatus="testRow">
<tr>
<td>
<form:hidden path="testList[${testRow.index}].home" />
<c:out value="${testvar.home}" />
</td>
<td>
<form:input path="testList[${testRow.index}].destination" />
</td>
</tr>
</c:forEach>
<tr><td><input type="submit"></td></tr>
</form:form>
While the first time I load the data shows up fine on the form, when I press submit button the control goes to the formBackingObject method and the isFormSubmission returns true. However, when I get the command object using super.formBackingObject(request), it returns the form object with the testList value as null. I am unable to figure out why this simple case is not working?
I will really appreciate any help in getting this to work.
Are you using Spring 3? If so, you should take a look at this post.
With respect to list processing and object binding, take a look at this post.
Try using the following code. May be that can solve your problem.
private List<TestObj> operationParameterses = LazyList.decorate(new ArrayList<TestObj>(), FactoryUtils.instantiateFactory(TestObj.class));
It won't return you all null list.
Hope that helps you.
Cheers.
I guess my understanding of formBackingObject method must be wrong. I removed that method from the implementation, used referenceData for initial form load and onSubmit to process it on submit. This works fine and does get collection in the form back as expected.
Thanks all for the help though.

How to make spring checkboxes checked by default?

I'm using Spring 3.1.0.RELEASE. I have this field in my command object ...
public Set<EventFeed> getUserEventFeeds() {
return this.userEventFeeds;
}
On my Spring JSP page, I want to display a checkbox list of all possible event feeds, and then have checked checkboxes if the user has one in his set. I want to have some special HTML formatting around each checkbox, so I'm trying ...
<form:form method="Post" action="eventfeeds.jsp" commandName="user">
...
<c:forEach var="eventFeed" items="${eventFeeds}">
<tr>
<td><form:checkbox path="userEventFeeds" value="${eventFeed}"/></td>
<td>${eventFeed.title}</td>
</tr>
</c:forEach>
...
However, the items aren't getting checked by default if one is in the set. How do I do this? Here is the binder I'm using in my controller class ...
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(EventFeed.class, new EventFeedEditor());
}
private class EventFeedEditor extends PropertyEditorSupport {
#Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(eventFeedsDao.findById(Integer.valueOf(text)));
}
#Override
public String getAsText() {
return ((EventFeed) getValue()).getId().toString();
}
}
#Dave, there is something called form:checkBoxes. You can try with that.
<form:checkboxes path="userEventFeeds" items="${eventFeeds}" itemLabel="id" itemValue="value"/>
My assumption here is you should have "id" and "value" defined in the EventFeed class.
I just tried this by having a String[] availableList and String[] selectedList. It works like charm. You can give a try as well.
Interestingly this works:
<form:checkbox path="services" value="${type}" checked="checked"/>
You can do this by placing selected default property true in your class
class User {
boolean userEventFeeds = true;
}
I've tried both form:checkboxes and form:checkbox with the same data and the first works, the second doesn't. (Same release of Spring you have)
It looks like there was a bug which, despite their claim, seems to be still there.
For my usecase (reacting on stuff in a list that has nothing to do with the object being filled), this code worked:
(Please be aware that this is a last-resort kind of code, other solutions are most likely better suited.)
<%# taglib prefix="jstl" uri="http://java.sun.com/jsp/jstl/core" %>
<jstl:forEach var="listObject" items="${someList}">
<jstl:if test="${listObject.active}">
<form:checkbox path="active" checked="checked"/>
</jstl:if>
<jstl:if test="${!listObject.active}">
<form:checkbox path="active"/>
</jstl:if>
</jstl:forEach>

In JSP EL enum value always empty [duplicate]

This question already has answers here:
How to reference constants in EL?
(12 answers)
Closed 6 years ago.
When trying to get an EL condition working I found that enum values are completely ignored. This seems to me contrary to the spec.
<c:out value='${com.foobar.data.BookingStatus.FAILED}' />
<c:out value='${BookingStatus.FAILED}' />
<c:out value='${com.foobar.data.BookingStatus.failed}' />
<c:out value='${BookingStatus.failed}' />
<c:if test="${empty BookingStatus.FAILED }">empty</c:if>
To my surprise these all evaluate to empty. Why is the Enum class not recognized?
This is happening in a current stable Tomcat instance.
Can this be a classpath issue? The Enum is used successfully in controller code but nowhere else in JSPs. It is supplied in a jar in the lib directory of the deployment.
UPDATE:
My intention is to compare a supplied Integer to an Enum's property like this:
<c:when test='${bookingInformation.bookingStatus eq BookingStatus.FAILED.code}'>
FOOBARFAIL
</c:when>
Unfortunately the value being checked can't be changed and will remain an Integer. The Enum looks as follow (simplified):
public enum BookingStatus {
COMPLETED(0), FAILED(1);
private final int code;
private BookingStatus(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
I want to avoid to hard code the Integer value of FAIL etc. and use the enum instead for the comparison.
That's because EL in its current version does not support accessing enums nor calling enum constants. This support is only available per EL 3.0.
It's unclear what your intent is, but it's good to know that you can compare enum properties as a String in EL. They are namely resolved as a String.
Assuming that you've a bean which look like this:
public class Booking {
public enum Status { NEW, PROGRESS, SUCCESS, FAILED }
private Status status;
public Status getStatus() {
return status;
}
}
Then you could test the Status.FAILED condition as follows:
<c:if test="${booking.status == 'FAILED'}">
Booking status is FAILED.
</c:if>
See also:
How to reference constants in EL?
As BalusC indicated, you cannot access enums using EL, however, you can do this:
<c:set var="enumFailed" value="<%=BookingStatus.FAILED%>"/>
<c:if test="${enumFailed.code == bookingInformation.bookingStatus}">
...
</c:if>
It would be ideal if bookingInformation.bookingStatus was an enum and not an int, but if re-factoring your app is out of the question due to its legacy nature, then my above example should help. You'd need a <c:set/> for each value of the enum (appears to just be two in your example).
You have to import the enum class in your jsp page. As far as you import it then you can refer to it. I wrote an example below.
My enum is the WebSettingType.
public enum WebSettingType {
SMTP_HOSTNAME("smtp_hostname"),
SMTP_PORT("smtp_port"),
SMTP_USERNAME("smtp_username");
private final String value;
private WebSettingType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
I have the websettings.jsp page that is uses a tag page etc.
<%#page import="my.package.WebSettingType"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:admin>
<jsp:attribute name="css">
</jsp:attribute>
<jsp:attribute name="content">
<input type="text" name="${WebSettingType.SMTP_HOSTNAME.getValue()}"/>
</jsp:attribute>
</t:admin>

Categories