Selva
Selva

Reputation: 1670

How to receive dynamically generated input value in spring as bean

In my project i dynamically generate the text box in table like below

project Name Date1 Date2 Date3 Date4 Date5 Activity 
java                                        Development Addnew
C++                                         Development Addnew 

i display tables for one week.if user clicks addnew i generate the dynamic text box below the row where user clicked addnew button.

My problem is how to get all the textbox value in my spring controller as bean class.Because i am not sure abut how many text boxes are come in page load and submit.

Any Idea will be greatly appreciated!!!

Upvotes: 3

Views: 2080

Answers (2)

Adam
Adam

Reputation: 36743

There aren't enough specifics in your question for a specific answer. However the general approach I would recommend.

  • If you have a framework like Backbone or Angular, investigate use of its collection facilities.
  • Write JavaScript that builds JSON array from all your textfields
  • Define a POJO in Java that mirrors each entry in your array.
  • Ensure you're using Jackson - this maps JSON to Java objects for you before your controller is called
  • Define an method in your controller that takes a list of POJO, e.g. create(List values) with a URL like /times/{ employeeId} using PUT
  • For reading out of the database, add method in your controller that returns a list of POJO, e.g. List values get(long employeeId) with a URL like /times/{ employeeId} using GET
  • Alternatively if you need the form to be 'live', i.e. 'Add new' causes row in database instantly use a REST interface with a create, update and DELETE using POST, PUT and DELETE respectively

I assume you'll need to update the list later, so I'd recommend a structure with an ID which can be used for CREATE and UPDATE operations, not just a plain list of Strings, this will also allow more fields later.

public void Foo {
  private String project;
  private String name;
  private long id;
  // getters + setters
}

JSON for a create

[{"project":"java","name":"Development",id:0}, {"project":"C++","name":"Development",id:0}]

JSON for a later update, i.e. with IDs round-tripped

[{"project":"java","name":"Development",id:100}, {"project":"C++","name":"Development",id:101}]

Upvotes: 2

Santhosh
Santhosh

Reputation: 8217

Go with the traditional getParameter() method. I assume your text box will have unique names while generated using jquery.

In the controller,

   List<String> requestParameterNames = Collections.list((Enumeration<String>) request.getParameterNames());

for (String parameterName : requestParameterNames) {
    String attributeName = parameterName;
    String attributeValue = request.getParameter(parameterName);
    // will have the text box values 

}

Upvotes: 2

Related Questions