3

Good day. I got a form on the client side. And in that form i got a number of rows. Each row contains 3 fields (date, id and amount of money). Client can add rows (with the help of JavaScript) so server side doesn`t know how many rows will it be.

I need to map this form with the class, representing this data.

public class RowStruct
{
    private Long id;
    private Double amount;
    private Date date;

}
public class FormStruct
{
    private ArrayList<RowStruct> arrData;
{

So i need data from my form to be mapped with FormStruct object.

@RequestMapping("/send")
public ModelAndView getList(HttpServletRequest req,FormStruct formStruct)
{
    ModelAndView model = new ModelAndView();

}

Is it possible and how do i do it?

3 Answers 3

12

you have to use an index on the clientside/html.

<input name="arrData[0].id" />
<input name="arrData[0].amount" />
<input name="arrData[0].date" />

Every time you add a row you have to increase the index. Unless you don't remove a row it will work like this.

I suppose you allow your clients to delete rows, so this unavoidably creates gaps between indexes. But you don't have to fix this on clientside, after the model has reached the controller you can filter your arrData for NULL references.

@RequestMapping("/send")
public ModelAndView getList(HttpServletRequest req,FormStruct formStruct)
{
    Iterator<RowStruct> it = formStruct.getArrData().iterator();
    while (it.hasNext()) {
        if (it.next() == null)
            it.remove();
    }
    ModelAndView model = new ModelAndView();

}
Sign up to request clarification or add additional context in comments.

1 Comment

After lots of answers you saved my day with your dot "." :)
1

Yes, it's possible.

In the html you can use indexing:

<input id='arrData[0].id' ...

This way you can build the bindings dynamically on the client side

On the server side you need annotate the variable:

public ModelAndView getList(HttpServletRequest req, 
                            @RequestParam FormStruct formStruct)

1 Comment

Will Spring boot also validate each object's field individually?
0

You can ask client to send data in terms of JSON, and you can use JSON De/Serializer to convert it to Java objects

3 Comments

Well. Thats a solution. And how do i create a JSON from my form? Is it a way to do it automaticcaly, using just form fields names, or i need to fetch my form`s rows and add them in my JSON manually?
That's a solution, BUT it's not necessary since spring is able to bind to collections!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.