patternjavaMinor
Spring MVC dynamically adding form elements
Viewed 0 times
springdynamicallymvcelementsaddingform
Problem
I made a simple form with an option of adding one text field dynamically on mouse click. And I will be grateful for suggestions on how I may improve the code.
`
Getting Started: Handing Form Submission
Form
Id:
Name:
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('
' + document.getElementById('p_new').value + ' ').appendTo(addDiv);
//alert(i);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
@Controller
public class MyController {
public ArrayList fieldArrayList;
@RequestMapping(value="/create", method= RequestMethod.GET)
public String myForm(Model model, @ModelAttribute NewField newField) {
fieldArrayList = new ArrayList<>();
fieldArrayList.add(newField);
model.addAttribute("dataForm", new DataForm());
return "create";
}
@RequestMapping(value="/create", method=RequestMethod.POST)
public String formSubmit(Model model, HttpServletRequest hsr, @ModelAttribute DataForm dataForm) {
if (hsr.getParameterValues("lastField") != null) {
String[] lastF = null;
lastF = hsr.getParameterValues("lastField");
List d = Arrays.asList(lastF);
int count = d.size() + 1;
for (int i = 2; i < count+1; i++) {
NewField newField = new NewField();
String s1 = hsr.getParameter("p_new_" + String.valueOf(i));
String s2 = hsr.getParameter("l_" + String.valueOf(i));
newField.setStr1(s2);
newField.setStr2(s1);
fieldArrayList.add(newField);
}
}
model.addAttribute("dataForm", dataForm);
model.addAttribute("fieldArrayList", fieldArrayList);
return "view";
}`
Getting Started: Handing Form Submission
Form
Id:
Name:
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('
' + document.getElementById('p_new').value + ' ').appendTo(addDiv);
//alert(i);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
Solution
- Use interface
Listinstead of concrete class for thefieldArrayList
field.
- Make the
fieldArrayListfield private.
@RequestMapping(value="/create", method= RequestMethod.GET). Requests using GET should only retrieve data, not create.
- Extract the calls of
hsr.getParameterValuesandhsr.getParametermethods in separate methods.
- Don't use meaningless variable names such as
d,s1,s2.
- Format code with your IDE. For example, in IDEA you can use the
Ctrl+Alt+Lhotkey.
- Extract attribute and parameter names in constants.
@RequestMapping(value="/create", method=RequestMethod.POST)can be replaced with@PostMapping("/create").
Context
StackExchange Code Review Q#145900, answer score: 3
Revisions (0)
No revisions yet.