class Role implements Serializable {
// this is my domain class
private static final long serialVersionUID = 1
String authority
Role(String authority) {
this()
this.authority = authority
}
static constraints = {
authority blank: false, unique: true
}
static mapping = {
cache true
}
}
def indexList(){
render(template: "indexList", model:[roleInstanceList: Role.findAll()])
} // this is the method in the controller that renders the view page 'indexList'
<div class="col-md-12 main-header">Role List</div>
//this is my 'view' gsp page to be rendered
<table class="table manage-table">
<thead>
<tr>
**<g:sortableColumn property="authority"
title="${message(code: 'role.authority.label', default: 'authority')}" />**
</tr>
</thead>
<tbody>
<g:each in="${roleInstanceList}" status="i" var="roleInstance">
<tr id="${roleInstance.id}" class="${(i % 2) == 0 ? 'even' : 'odd'}">
<td>
${fieldValue(bean: roleInstance, field: "authority")}
</td>
</tr>
</g:each>
</tbody>
</table>
Here, when I click on Sortable Column 'authority' - sorting is not done and I am getting a page
refresh with the following URL: role/indexList?sort=authority&order=asc
Any help much appreciated.
Thanks and a note to point that I am new to grails framework
You probably want Role.list(params) instead of Role.findAll().
I am having a lot of difficulty with POSTing back a form to the controller, which should contain simply an arraylist of objects that the user may edit.
The form loads up correctly, but when it's posted, it never seems to actually post anything.
Here is my form:
<form action="#" th:action="#{/query/submitQuery}" th:object="${clientList}" method="post">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Select</th>
<th>Client ID</th>
<th>IP Addresss</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr th:each="currentClient, stat : ${clientList}">
<td><input type="checkbox" th:checked="${currentClient.selected}" /></td>
<td th:text="${currentClient.getClientID()}" ></td>
<td th:text="${currentClient.getIpAddress()}"></td>
<td th:text="${currentClient.getDescription()}" ></td>
</tr>
</tbody>
</table>
<button type="submit" value="submit" class="btn btn-success">Submit</button>
</form>
Above works fine, it loads up the list correctly. However, when I POST, it returns a empty object (of size 0). I believe this is due to the lack of th:field, but anyway here is controller POST method:
...
private List<ClientWithSelection> allClientsWithSelection = new ArrayList<ClientWithSelection>();
//GET method
...
model.addAttribute("clientList", allClientsWithSelection)
....
//POST method
#RequestMapping(value="/submitQuery", method = RequestMethod.POST)
public String processQuery(#ModelAttribute(value="clientList") ArrayList clientList, Model model){
//clientList== 0 in size
...
}
I have tried adding a th:field but regardless of what I do, it causes an exception.
I've tried:
...
<tr th:each="currentClient, stat : ${clientList}">
<td><input type="checkbox" th:checked="${currentClient.selected}" th:field="*{}" /></td>
<td th th:field="*{currentClient.selected}" ></td>
...
I cannot access currentClient (compile error), I can't even select clientList, it gives me options like get(), add(), clearAll() etc, so it things it should have an array, however, I cannot pass in an array.
I've also tried using something like th:field=${}, this causes runtime exception
I've tried
th:field = "*{clientList[__currentClient.clientID__]}"
but also compile error.
Any ideas?
UPDATE 1:
Tobias suggested that I need to wrap my list in a wraapper. So that's what I did:
ClientWithSelectionWrapper:
public class ClientWithSelectionListWrapper {
private ArrayList<ClientWithSelection> clientList;
public List<ClientWithSelection> getClientList(){
return clientList;
}
public void setClientList(ArrayList<ClientWithSelection> clients){
this.clientList = clients;
}
}
My page:
<form action="#" th:action="#{/query/submitQuery}" th:object="${wrapper}" method="post">
....
<tr th:each="currentClient, stat : ${wrapper.clientList}">
<td th:text="${stat}"></td>
<td>
<input type="checkbox"
th:name="|clientList[${stat.index}]|"
th:value="${currentClient.getClientID()}"
th:checked="${currentClient.selected}" />
</td>
<td th:text="${currentClient.getClientID()}" ></td>
<td th:text="${currentClient.getIpAddress()}"></td>
<td th:text="${currentClient.getDescription()}" ></td>
</tr>
Above loads fine:
Then my controller:
#RequestMapping(value="/submitQuery", method = RequestMethod.POST)
public String processQuery(#ModelAttribute ClientWithSelectionListWrapper wrapper, Model model){
...
}
The page loads correctly, the data is displayed as expected. If I post the form without any selection I get this:
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'clientList' cannot be found on null
Not sure why it's complaining
(In the GET Method it has: model.addAttribute("wrapper", wrapper);)
If I then make a selection, i.e. tick the first entry:
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='clientWithSelectionListWrapper'. Error count: 1
I'm guessing my POST controller is not getting the clientWithSelectionListWrapper. Not sure why, since I have set the wrapper object to be posted back via the th:object="wrapper" in the FORM header.
UPDATE 2:
I've made some progress! Finally the submitted form is being picked up by the POST method in controller. However, all the properties appear to be null, except for whether the item has been ticked or not. I've made various changes, this is how it is looking:
<form action="#" th:action="#{/query/submitQuery}" th:object="${wrapper}" method="post">
....
<tr th:each="currentClient, stat : ${clientList}">
<td th:text="${stat}"></td>
<td>
<input type="checkbox"
th:name="|clientList[${stat.index}]|"
th:value="${currentClient.getClientID()}"
th:checked="${currentClient.selected}"
th:field="*{clientList[__${stat.index}__].selected}">
</td>
<td th:text="${currentClient.getClientID()}"
th:field="*{clientList[__${stat.index}__].clientID}"
th:value="${currentClient.getClientID()}"
></td>
<td th:text="${currentClient.getIpAddress()}"
th:field="*{clientList[__${stat.index}__].ipAddress}"
th:value="${currentClient.getIpAddress()}"
></td>
<td th:text="${currentClient.getDescription()}"
th:field="*{clientList[__${stat.index}__].description}"
th:value="${currentClient.getDescription()}"
></td>
</tr>
I also added a default param-less constructor to my wrapper class and added a bindingResult param to POST method (not sure if needed).
public String processQuery(#ModelAttribute ClientWithSelectionListWrapper wrapper, BindingResult bindingResult, Model model)
So when an object is being posted, this is how it is looking:
Of course, the systemInfo is supposed to be null (at this stage), but the clientID is always 0, and ipAddress/Description always null. The selected boolean is correct though for all properties. I'm sure I've made a mistake on one of the properties somewhere. Back to investigation.
UPDATE 3:
Ok I've managed to fill up all the values correctly! But I had to change my td to include an <input /> which is not what I wanted... Nonetheless, the values are populating correctly, suggesting spring looks for an input tag perhaps for data mapping?
Here is an example of how I changed the clientID table data:
<td>
<input type="text" readonly="readonly"
th:name="|clientList[${stat.index}]|"
th:value="${currentClient.getClientID()}"
th:field="*{clientList[__${stat.index}__].clientID}"
/>
</td>
Now I need to figure out how to display it as plain data, ideally without any presence of an input box...
You need a wrapper object to hold the submited data, like this one:
public class ClientForm {
private ArrayList<String> clientList;
public ArrayList<String> getClientList() {
return clientList;
}
public void setClientList(ArrayList<String> clientList) {
this.clientList = clientList;
}
}
and use it as the #ModelAttribute in your processQuery method:
#RequestMapping(value="/submitQuery", method = RequestMethod.POST)
public String processQuery(#ModelAttribute ClientForm form, Model model){
System.out.println(form.getClientList());
}
Moreover, the input element needs a name and a value. If you directly build the html, then take into account that the name must be clientList[i], where i is the position of the item in the list:
<tr th:each="currentClient, stat : ${clientList}">
<td><input type="checkbox"
th:name="|clientList[${stat.index}]|"
th:value="${currentClient.getClientID()}"
th:checked="${currentClient.selected}" />
</td>
<td th:text="${currentClient.getClientID()}" ></td>
<td th:text="${currentClient.getIpAddress()}"></td>
<td th:text="${currentClient.getDescription()}" ></td>
</tr>
Note that clientList can contain null at
intermediate positions. Per example, if posted data is:
clientList[1] = 'B'
clientList[3] = 'D'
the resulting ArrayList will be: [null, B, null, D]
UPDATE 1:
In my exmple above, ClientForm is a wrapper for List<String>. But in your case ClientWithSelectionListWrapper contains ArrayList<ClientWithSelection>. Therefor clientList[1] should be clientList[1].clientID and so on with the other properties you want to sent back:
<tr th:each="currentClient, stat : ${wrapper.clientList}">
<td><input type="checkbox" th:name="|clientList[${stat.index}].clientID|"
th:value="${currentClient.getClientID()}" th:checked="${currentClient.selected}" /></td>
<td th:text="${currentClient.getClientID()}"></td>
<td th:text="${currentClient.getIpAddress()}"></td>
<td th:text="${currentClient.getDescription()}"></td>
</tr>
I've built a little demo, so you can test it:
Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ClientWithSelection.java
public class ClientWithSelection {
private Boolean selected;
private String clientID;
private String ipAddress;
private String description;
public ClientWithSelection() {
}
public ClientWithSelection(Boolean selected, String clientID, String ipAddress, String description) {
super();
this.selected = selected;
this.clientID = clientID;
this.ipAddress = ipAddress;
this.description = description;
}
/* Getters and setters ... */
}
ClientWithSelectionListWrapper.java
public class ClientWithSelectionListWrapper {
private ArrayList<ClientWithSelection> clientList;
public ArrayList<ClientWithSelection> getClientList() {
return clientList;
}
public void setClientList(ArrayList<ClientWithSelection> clients) {
this.clientList = clients;
}
}
TestController.java
#Controller
class TestController {
private ArrayList<ClientWithSelection> allClientsWithSelection = new ArrayList<ClientWithSelection>();
public TestController() {
/* Dummy data */
allClientsWithSelection.add(new ClientWithSelection(false, "1", "192.168.0.10", "Client A"));
allClientsWithSelection.add(new ClientWithSelection(false, "2", "192.168.0.11", "Client B"));
allClientsWithSelection.add(new ClientWithSelection(false, "3", "192.168.0.12", "Client C"));
allClientsWithSelection.add(new ClientWithSelection(false, "4", "192.168.0.13", "Client D"));
}
#RequestMapping("/")
String index(Model model) {
ClientWithSelectionListWrapper wrapper = new ClientWithSelectionListWrapper();
wrapper.setClientList(allClientsWithSelection);
model.addAttribute("wrapper", wrapper);
return "test";
}
#RequestMapping(value = "/query/submitQuery", method = RequestMethod.POST)
public String processQuery(#ModelAttribute ClientWithSelectionListWrapper wrapper, Model model) {
System.out.println(wrapper.getClientList() != null ? wrapper.getClientList().size() : "null list");
System.out.println("--");
model.addAttribute("wrapper", wrapper);
return "test";
}
}
test.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="#" th:action="#{/query/submitQuery}" th:object="${wrapper}" method="post">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Select</th>
<th>Client ID</th>
<th>IP Addresss</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr th:each="currentClient, stat : ${wrapper.clientList}">
<td><input type="checkbox" th:name="|clientList[${stat.index}].clientID|"
th:value="${currentClient.getClientID()}" th:checked="${currentClient.selected}" /></td>
<td th:text="${currentClient.getClientID()}"></td>
<td th:text="${currentClient.getIpAddress()}"></td>
<td th:text="${currentClient.getDescription()}"></td>
</tr>
</tbody>
</table>
<button type="submit" value="submit" class="btn btn-success">Submit</button>
</form>
</body>
</html>
UPDATE 1.B:
Below is the same example using th:field and sending back all other attributes as hidden values.
<tbody>
<tr th:each="currentClient, stat : *{clientList}">
<td>
<input type="checkbox" th:field="*{clientList[__${stat.index}__].selected}" />
<input type="hidden" th:field="*{clientList[__${stat.index}__].clientID}" />
<input type="hidden" th:field="*{clientList[__${stat.index}__].ipAddress}" />
<input type="hidden" th:field="*{clientList[__${stat.index}__].description}" />
</td>
<td th:text="${currentClient.getClientID()}"></td>
<td th:text="${currentClient.getIpAddress()}"></td>
<td th:text="${currentClient.getDescription()}"></td>
</tr>
</tbody>
When you want to select objects in thymeleaf, you dont actually need to create a wrapper for the purpose of storing a boolean select field. Using dynamic fields as per the thymeleaf guide with syntax th:field="*{rows[__${rowStat.index}__].variety}" is good for when you want to access an already existing set of objects in a collection. Its not really designed for doing selections by using wrapper objects IMO as it creates unnecessary boilerplate code and is sort of a hack.
Consider this simple example, a Person can select Drinks they like. Note: Constructors, Getters and setters are omitted for clarity. Also, these objects are normally stored in a database but I am using in memory arrays to explain the concept.
public class Person {
private Long id;
private List<Drink> drinks;
}
public class Drink {
private Long id;
private String name;
}
Spring controllers
The main thing here is that we are storing the Person in the Model so we can bind it to the form within th:object.
Secondly, the selectableDrinks are the drinks a person can select on the UI.
#GetMapping("/drinks")
public String getDrinks(Model model) {
Person person = new Person(30L);
// ud normally get these from the database.
List<Drink> selectableDrinks = Arrays.asList(
new Drink(1L, "coke"),
new Drink(2L, "fanta"),
new Drink(3L, "sprite")
);
model.addAttribute("person", person);
model.addAttribute("selectableDrinks", selectableDrinks);
return "templates/drinks";
}
#PostMapping("/drinks")
public String postDrinks(#ModelAttribute("person") Person person) {
// person.drinks will contain only the selected drinks
System.out.println(person);
return "templates/drinks";
}
Template code
Pay close attention to the li loop and how selectableDrinks is used to get all possible drinks that can be selected.
The checkbox th:field really expands to person.drinks since th:object is bound to Person and *{drinks} simply is the shortcut to referring to a property on the Person object. You can think of this as just telling spring/thymeleaf that any selected Drinks are going to be put into the ArrayList at location person.drinks.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" >
<body>
<div class="ui top attached segment">
<div class="ui top attached label">Drink demo</div>
<form class="ui form" th:action="#{/drinks}" method="post" th:object="${person}">
<ul>
<li th:each="drink : ${selectableDrinks}">
<div class="ui checkbox">
<input type="checkbox" th:field="*{drinks}" th:value="${drink.id}">
<label th:text="${drink.name}"></label>
</div>
</li>
</ul>
<div class="field">
<button class="ui button" type="submit">Submit</button>
</div>
</form>
</div>
</body>
</html>
Any way...the secret sauce is using th:value=${drinks.id}. This relies on spring converters. When the form is posted, spring will try recreate a Person and to do this it needs to know how to convert any selected drink.id strings into the actual Drink type. Note: If you did th:value${drinks} the value key in the checkbox html would be the toString() representation of a Drink which is not what you want, hence need to use the id!. If you are following along, all you need to do is create your own converter if one isn't already created.
Without a converter you will receive an error like
Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'drinks'
You can turn on logging in application.properties to see the errors in detail.
logging.level.org.springframework.web=TRACE
This just means spring doesn't know how to convert a string id representing a drink.id into a Drink. The below is an example of a Converter that fixes this issue. Normally you would inject a repository in get access the database.
#Component
public class DrinkConverter implements Converter<String, Drink> {
#Override
public Drink convert(String id) {
System.out.println("Trying to convert id=" + id + " into a drink");
int parsedId = Integer.parseInt(id);
List<Drink> selectableDrinks = Arrays.asList(
new Drink(1L, "coke"),
new Drink(2L, "fanta"),
new Drink(3L, "sprite")
);
int index = parsedId - 1;
return selectableDrinks.get(index);
}
}
If an entity has a corresponding spring data repository, spring automatically creates the converters and will handle fetching the entity when an id is provided (string id seems to be fine too so spring does some additional conversions there by the looks). This is really cool but can be confusing to understand at first.
I've a table which has multiple columns as in my database table. Few of the columns are editable and the values entered by the user should be updated back in the database on click of submit. For this Ive a foreach loop with value as HashMap of list of bean.
Below is my foreach loop:
<c:forEach items="${feeType.value}" var="feeItem" varStatus="feeVar">
<td >[b]<form:checkbox disabled="true" class="editable${ifeeCount}" path="includeFeeValue" value="${feeVar.index}"/> [/b]</td>
<td >${feeItem.feetypeId} </td>
<td >${feeItem.feeValue} </td>
<td >[b]<form:input class="editable${ifeeCount}" disabled="true" path="${feeItem.overridenFee}" value="${feeItem.overridenFee}"/>[/b]</td>
<td><form:errors path="overriddenFee" cssClass="error" /></td>
<td >${feeItem.lastUpdatedBy} </td>
<td >${feeItem.lastUpdatedDate} </td>
<td > ${feeItem.approvedBy}</td>
<td >${feeItem.approvalDate}</td>
<td align="left">[b]<form:input class="editable${ifeeCount}" disabled="true" path="feeComments[${feeVar.index}]"/>[/b]</td>
<td><form:errors path="feeComments" cssClass="error" /></td>
I'm iterating through a map called feeApprovalByFundId which is Map>. How do I get the updated values of the columns like checkbox, input box? I'm able to get in a String or String array but I won't know to which key was that mapped to. (Eg. Fund1 will have 10 fees - I will have under one hashmap key).
I tried iterating like this :
Collection<List<MyBaseBean>> newList = paswFeeMaintForm.getFeeApprovalByFundId().values();
for(List<MyBaseBean> myList: newList){
for(MyBaseBean myBean : myList){
System.out.println("Overriden fee : "+myBean.getOverridenFee());
}
}
The path in the form control binding is a string that represents a property binding expression. When the form is rendered, Spring knows what feeItem is due to the JSTL context in which the form control is being rendered. But on POST, that context is lost, so feeItem doesn't make sense.
Instead, given a form bean like this:
public class FormBean {
private Map<Integer, ChildBean> children = new HashMap<>();
public Map<Integer, ChildBean> getChildren() { return children; }
}
public class ChildBean {
private String name;
private String age;
}
And a controller like this:
#ModelAttribute("formBean")
public FormBean createFormBean() {
FormBean bean = new FormBean();
bean.add(new ChildBean("Joe", 5));
bean.add(new Childbean("Sam", 10));
}
#RequestMapping(...)
public String post(#ModelAttribute("formBean") FormBean formBean) { ... }
#RequestMapping(...)
public String get(#ModelAttribute("formBean") FormBean formBean) { ... }
In the view you would do this:
<form:form modelAttribute="formBean">
<c:forEach items="${formBean.children}" varStatus="s">
<form:input path="children[${s.index}].name" />
<form:input path="children[${s.index}].age" />
</c:forEach>
</form:form>
The rendered form elements would look something like:
<input type="text" name="children[0].name" />
<input type="text" name="children[0].age" />
<input type="text" name="children[1].name" />
<input type="text" name="children[1].age" />
Note that this is the standard indexed property syntax. Now, on the server side, there is enough context to determine which item in the collection should be modified.
For a map, the following no longer applies:
Also note that you don't have to return a list, but can specify the bean method to take an index and a single item, allowing you to define sparse collections (if you haven't constructed the collection ahead of time).
I'm using spring mvc for the first time and I'm trying to display and edit a structure in jsp.
I have a class Snippet, which holds a list of objects of type Sentence:
public class Snippet {
private int id;
private List<Sentence> sentences;
// getters, setters, default constructor
}
public class Sentence {
private int id;
private int scale;
private String text;
// getters, setters, default constructor
}
In my controller I give a new snippet for editing and when user clicks "save" store it to my db, then return another one. Currently the sentences list of the snippet is null:
#RequestMapping("/snippet")
public ModelAndView getSnippet() {
return new ModelAndView("snippet", "snippet", snippetService.getSnippet());
}
#RequestMapping("/save")
public ModelAndView saveSnippet(#ModelAttribute Snippet snippet) {
if(snippet != null && snippet.getSentences() != null && !snippet.getSentences().isEmpty()) {
snippetService.updateSnippet(snippet);
}
return new ModelAndView("snippet", "snippet", snippetService.getSnippet());
}
In my snippet.jsp I'd like to display the snippet sentences with their scale, and on save, pass snippet with sentences and scales to the controller for storage:
<form:form method="post" action="save" modelAttribute="snippet">
...
<c:forEach var="sentence" items="${snippet.sentences}">
<tr>
<td>${sentence.id}</td>
<td>${sentence.text}</td>
<td><input type="range" name="sentence.scale" value="${sentence.scale}"
path="sentence.scale" min="0" max="5" /></td>
</tr>
</c:forEach>
<tr>
<td colspan="4"><input type="submit" value="Save" /></td>
</tr>
I think I have to find the right way to use the path attribute but I can't figure it out.
The JSTL c:forEach tag provides the attribute varStatus, which will expose the loop status to the specified variable. Reference the index of varStatus to obtain the index of the current loop and use that index to specify the index of the collection item you want to bind or display.
<c:forEach var="sentence" items="${snippet.sentences}" varStatus="i">
<tr>
<td>${sentence.id}</td>
<td>${sentence.text}</td>
<td>
<form:input type="range"
name="snippet.sentences[${i.index}].scale"
path="sentences[${i.index}].scale"
min="0" max="5"
/></td>
</tr>
</c:forEach>
I'm having a little fight here, this is my problem: I have a table whose content is taken from a bean that contains 2 string variables and a list of beans which in turn are formed by 2 string variables and a MultipartFile. So, in this scenario I present to the user a table with like this:
The problem comes when I try to implement the "Add image" functionality: a new row in the table is shown but after submit the values the bean that I receive in the controller put the new values into the last bean in the list, i.e. if in the new input for "Bean 2 - field 1" I put "new_value_5" in the controller I receive "value 5, new_value_5" into "field 1" of the last bean in the list, I don't receive a new instance of the bean, I just get all the values into the last bean of the list.
This is my code in the jsp page:
<form:form action="myaction.html" method="post" modelAttribute="main_bean" enctype="multipart/form-data">
<table>
<tr>
<td>Bean 1 - field 1: <form:input path="bean1_field1"/></td>
</tr>
<tr>
<td>Bean 1 - field 2: <form:input path="bean1_field2"/></td>
</tr>
<tr>
<td>Images:
<table id="imgTable">
<tbody>
<c:forEach var="bean_2" items="${main_bean.list_of_bean_2}" varStatus="imgStatus">
<tr>
<td>
<img src="image/${main_bean.id}/${bean_2.pathImage}" class="imagen" width="100px;" height="100px;" id="idImage">
<div id="divFile" style="display:none;"><!-- When the user wants to add a new image I enable this input-->
<form:input type="file" path="${bean_2.image}" name="imagen" id="imgFile"/>
</div>
</td>
<td>
Bean 2 - field 1: <form:input path="list_of_bean_2[${imgStatus.index}].field1" id="field1Id"/>
<form:input type="hidden" path="list_of_bean_2[${imgStatus.index}].id"/>
</td>
<td>
Bean 2 - field 2: <form:input path="list_of_bean_2[${imgStatus.index}].field2" id="field2Id"/>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
<td>
<input type="button" value="Add image" id="addImgBtn" class="addImgBtn">
</td>
</tr>
<tr>
<td><input type="submit" value="Confirm changes" > </td>
<td><input type="button" value="Cancel changes" > </td>
</tr>
</table>
</form:form>
And the structure of the beans:
public class Bean1 {
private List<Bean2> imagesCampaign;
private String field1;
private String field2;
//getters and setters
}
public class Bean2 {
private MultipartFile image;
private String field1;
private String field2;
//getters and setters
}
I didn't specified the code in the controller because I think is not necessary, but if you want it just let me know.
I will really appreciate if somebody could give me a clue about what's going on here. Thanks in advance.
EDIT: I tried access to the n+1 index (list_of_bean_2[${imgStatus.index + 1}]) but got a ConcurrentModificationException
Anybody please a little help here???
Finally I managed myself to solve this problem, if someone knows a better solution I would be grateful but in the meantime here is my solution. Instead of having a button to do all the work I created 2: the first one will just add a row for the new image, and the second one will submit the data added, so, this is my javascript:
$(".addImgBtn").click(function() {
$('#imgTable tbody>tr:last').clone(true).insertAfter('#imgTable tbody>tr:last');
$("#imgTable tbody>tr:last #field1").val('');
$("#imgTable tbody>tr:last #field2").val('');
$("#imgTable tbody>tr:last #divFile").show();
$(".addImgBtn").attr("disabled", "true");
return false;
});
The previous function will add a new row to the table, and it will disable the "Add image" button.
$(".confirmImgBtn").click(function(eve) {
var field1 = $("#imgTable tbody>tr:last #field1").val();
var field2 = $("#imgTable tbody>tr:last #field2").val();
var form = $('#confirmImgForm');
var newfile = $("#imgTable tbody>tr:last #imgFile")[0].files[0];
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(newfile);
}
if (formdata) {
formdata.append("image", newfile);
formdata.append("field1",field1);
formdata.append("field2",field2);
}
if (formdata) {
jQuery.ajax({
url: form.attr('action'),
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
alert('succeed!!');
}
});
}
});
The last function will submit the values to the controller: I read the values for the field1, field2, the form (just to get the url) and finally the image, and when I submit everything to the controller I receive an instance of my bean, which contains 2 string variables (for filed1 and field2) and a org.springframework.web.multipart.MultipartFile for the image.