JSP - Saving a collection - java

[Warning] I'm new to JSP/Struts/JSTL. This is probably a newbie question :)
I have a form that contains a collection:
public class ServiceForm extends AbstractForm
{
private List<SrvDO> allSrv = new ArrayList<SrvDO> ();
}
I can see the object data correctly in my form using the JSP. The page displays 5 input box with the data from the database correctly:
<c:forEach items="${serviceForm.allSrv}" var="srv">
<html:text name="srv" property="nbDays"/>
</c:forEach>
<html:submit/>
But when I press the submit button, the form does not contains the updated data for "nbDays". I still see the same data as it was shown before the update. What am I missing that says to struts: for each srv, update the "nbDays" data?

Found the answer on the spring forum:
Your form:input tag doesn't and
shouldn't know anything about the fact
that it is used inside another tag.
That is why you need to include the
index.
So the solution is:
<html:text property="allSrv[${srvSta.index}].nbDays"/>

Related

Collect user input in Servlet and return at the same point to continue program: Java

I have a web application in Java that performs title matching.
The Servlet is the controller and in one of the methods of the Servlet, I am comparing two list of titles. The first list is in a HashMap and the second is from a query ResultSet.
What I want to do is to automatically match those with same title and give the user the option to confirm the ones with some similarities (business logic). Basically, I need to get user input and then return at the same point to continue.
I tried JOptionPane dialog box and it didn't work.
Now I am trying to forward to another HTML page to get user input and then return to the Servlet.
Below is the Servlet code:
while (Querylist.next()) {
String title = Querylist.getString(1).trim().toLowerCase();
if (MyMap.containsKey(title))
{
// confirm match
} else
{
//some title2 is like title
request.setAttribute("Title1", title);
request.setAttribute("Title2", title2);
RequestDispatcher view = request.getRequestDispatcher("TitleMatch.jsp");
view.forward(request, response);
ResultMatch= request.getParameter("ResultMatch");
if (ResultMatch.equals("YES"))
{
// confirm match
}
}
}
HTML Page:
<B> <%= request.getAttribute("Title1")%></B>
<B> <%= request.getAttribute("Title2")%></B>
<FORM method="get" action="DataMerge">
<input type = "radio" name="MatchResult" value="YES" /> YES
<input type = "radio" name="MatchResult" value="NO" checked/>NO
<button type = "submit" formaction="DataMerge" > <b>CONFIRM</b>
</FORM>
EDIT: the loop works and I'm having a java.lang.IllegalStateException Exception.
Does anyone can help to figure out how to do that efficiently in plain Java?
I searched all over SO and haven't found something similar. Thanks in advance.
You might want to reconsider your approach as there are number of fundamental problems with the code you have written. For example:
The while loop test it not correct. Assuming that you are using an Iterator then the test should be list.hasNext();
The if test is nested and incorrect. You cannot use the identifier Map as it is the name of the class, you should use the name of the map object.
If the loop worked the view.forward(request, response); would result in an java.lang.IllegalStateException exception, on the second cycle, as its not possible to resend a response.
I suggest that instead of trying to send each title pair one at a time, that you display them all (or some if there are too many) on one JSP with a yes button next to each pair and as the user clicks the yes button an AJAX call is made to another servlet that updates the database (or an array to latter be used to update the database).
There are some good tutorial about using AJAX and JSP here of SOF and in YouTube.

How to bind an object inside the list collection of the command object in Spring MVC

My command object have a list of objects. I want to bind a text field to the attribute of the object inside that list. Is it possible to do in Spring MVC?
Command object class
public class SubDevisonDto {
private String devId;
private List subDevisions;
Subdevision object class mentioned in the list
public class SubDivison implements Serializable{
private String subDivisonName;
private String createdBy;
private String createdDate;
private String developerID;
private List users;
I want text box to set the value for subDivisonName field.
I have written the Spring MVC tags like this.
<spring:bind path="subdivisondto.subDevisions[0].subDivisonName">
<span class="formw">
<input name="subDivisonName" type="text" style="width:350px;" />
</span>
</spring:bind>
Just for test purpose I have given it as 0. If it's working I can make it to a variable. my requirement is, I should let the user to dynamically add subdevision objects. So, initially when page is loading I will just show one text box. I will give a button for him to add if he want to add more. I will dynamically generate text boxes when he clicks the add button. After that I have to submit the form with the list.
This jsp code gives me an error. It says:
org.springframework.beans.NullValueInNestedPathException
Is there anyway for me to do this in jsp code?
I found the answer for my question. But, it's not the solution for my requirement as I need to implement a dynamic list. but I found a solution for this question.
As I understood, first time we have to send data from back end to bind input elements. I didn't find a way to bind form elements which takes input without sending a list data from beck end. But when we send data and bind the elements, we can take input from those elements. So, I think to bind the element in a situation like this we need to send data first time. Correct me if this statement is wrong. Because, that would be a more good solution for me.
We need to use the lazy list and jsp code is bit modified.
Your command class object should be created as below mentioned.
import org.apache.commons.collections.list.LazyList;
import org.apache.commons.collections.FactoryUtils;
public class SubDevisonDto {
private String devId;
private List subDevisions =
LazyList.decorate(
new ArrayList(),
FactoryUtils.instantiateFactory(SubDivison.class));
JSP code should look like below.
<c:forEach items="${subs.subDevisions}" var="obj" varStatus="gridRow">
Binding an input element text box
<spring:bind path="subdivisondto.subDevisions[${gridRow.index}].subDivisonName">
<span class="formw"><input name="<c:out value="${status.expression}"/>" type="text" style="width:350px;" />
binding an input element check box. This input element makes a list.
<spring:bind path="subs.subDevisions[${gridRow.index}].users">
<c:forEach items="${obj.users}" var="dependenttwo" varStatus="dependentRowtwo">
<li>
<input name="<c:out value="${status.expression}"/>" type="checkbox" class="users" value="<c:out value="${dependenttwo}"/>"/>
<c:out value="${dependenttwo}"/>
</li>
</c:forEach>
</spring:bind>
`subs` is a map key name. the value for this key `subs` is a list of my DTO objects which named as `SubDevisonDto `
This code works fine for me.
Thanks the support given.
In dto :
private List<SubDivision> SubDivisions = new AutoPopulatingList<SubDivision>(new SubDivisionFactory());
and factory would be something like:
public class SubDivisionFactory implements AutoPopulatingList.ElementFactory<SubDivision> {
public String createElement(int index) {
SubDivision subDivision = new SubDivision();
return subDivision;
}
}
using AutopopulatingList from spring. And your jsp will look the same, you can iterate over as many as you want.

How to update a the contents of a list displayed on JSP using Struts2?

I'm using Struts2 to display the contents of a list of objects on a JSP.
The flow of events is as following:
GetDataAction.java -> fetches values from
the database, fills in the ArrayList
named tableList. On success, the
displayData.jsp is shown.
displayData.jsp -> uses the s:iterate tag to display the values of objects
in the tableList.
The user changes some values in the
displayData.jsp and presses on the
Update button. On the click of
Update button, the
UpdateDataAction.java is called.
Now my problem is; How do I use the same tableList in UpdateDataAction.java to get the modified values?
I tried declaring an ArrayList with the same name 'tableList' (along with getters and setters), in UpdateDataAction.java but it throws a NullPointerException.
Please suggest.
IMO the way you are updating is not a good idea.Either you should link every row to a seperate edit page or use ajax.There are many plugins available to update table values using ajax,If you need i can provide you the links
Back to your way of doing it,i guess you are doing it as follows
<s:form action="UpdateDataActionName">
<s:iterator value="tableList">
<s:textfield name="objectName.propertyName1" value="%(propertyName1)">
<s:textfield name="objectName.propertyName2" value="%(propertyName2)">
<s:textfield name="objectName.propertyName3" value="%(propertyName3)">
</s:iterator>
<s:submit value="Update"/>
</s:form>
Now declare a list in your UpdateDataAction,of type <objectNameoftableListType> i.e. the same object type which the tabeList is representing.The name of the list must be objectName.Try to Iteate and check if you are getting the right values as submitted from the jsp.

Need to display data on a jsp page using struts 1.3

I am trying to read data from a table and display it to the user .
Can anybody tell how to do it using struts 1.3 ?
Write an class extending Struts' Action class. This class pulls the data from Database as a List. Pass this data as request attribute, request.setAttribute("myList", list). Return "success".
In your struts-config.xml, map this Action class to a JSP on "success". The request will be forwarded to the JSP.
In the JSP, get the list from request by request.getAttribute("myList"). Iterate through the list and print the List.
You need to study this: http://struts.apache.org/1.x/userGuide/index.html
(Edit: Just noticed this is a 2 year old question)
Don't use the struts tags unless you NEED to. This can be accomplished with jstl/el.
So on your Action class you would have something like this:
List<Map<?, ?>> listOfHashMaps = new ArrayList<Map<?, ?>>();
request.setAttribute("listOfHashMaps", listOfHashMaps);
In your jsp:
<c:forEach var="hashMap" items="listOfHashMaps">
${hashMap[someInteger]} <%-- To get the value associated with 'key' --%>
</c:forEach>
You can also access the keys/values with:
${hashMap.key}
${hashMap.value}
Respectively.

Spring mvc: controller returns [][], usable in jsp with foreach, but how to bind?

I'm building a spring mvc application.
Now the problem I have is the following.
I have a controller which adds a DayInfo[][] to my ModelMap.
(DayInfo has an id, a title (String) and Text(also String).
Now the problem I have is that I have no problem displaying this DayInfo[][] with <foreach> tags in my jsp.
However I'm outputting the Title property as an input box(type text), and I'd like to be able to update this value (and thus saving it to be a database but that shouldn't be a problem). However I'm having trouble with binding this value to the input box so that it is actually returned to the controller.
If anyone has some advice it would be welcome.
I have never done this with multidimensional arrays but it should be something like this (though I haven't tried it, it's just to give you an idea). In the JSP you should set the name of the input with each index, something like this:
<c:forEach var="row" items="${days}" varStatus="statusRow">
<c:forEach var="day" items="${row}" varStatus="statusCol">
<input type="text" name="days[${statusRow.index}][${statusCol.index}].title" value="${day.title}"/>
</c:forEach>
</c:forEach>
and in the controller you have to prepare days variable so the size of the array is the same as the one you get from the JSP. So you can use #ModelAttribute method to prepare the array (this method will be executed before the #RequestMapping method).
#ModelAttribute("days")
public getDays(){
DayInfo[][] days;
//Here you have to instantiate the days to prepare it so it can be filled
//You can load for example the data from the database
return days;
}
#RequestMapping("/yourURL")
public String getFormData(#ModelAttribute("days")DayInfo[][] days){
//Here in days you should have the data from the form overriding
// the one from the database
}
Hope this helps and sorry if there is any error, though I'm writing withoug trying it.

Categories

Resources