Steve
Steve

Reputation: 4701

Refer to html elements by class in spring mvc controller

I know how to refer to HTML elements by name with request.getParameter("foo"); But I have various groups of elements within a form that each have a seperate 'class' attribute. Is there any way to refer to these by their class names? My controller is in the form below:

@Controller
@MultipartConfig()
public class FooController {
    //get parameters
    return "view";
}

My HTML input elements are in the form below:

<input class="bar" type="checkbox" name="elementName" />

Basically I want to say in my controller, "give me all the elements of class 'bar'". Is it possible?

Upvotes: 0

Views: 2269

Answers (3)

atrain
atrain

Reputation: 9255

As per the above, no. But: if you use Spring Forms with its taglib and a backing form class, Spring will automagically bind the form elements to the form class members. Your handler method then changes to:

@Controller
public class MyController {
   @RequestMapping("/foo/somevalue.do")
   public String FooController (
       @ModelAttribute("myForm") MyFormBean formBean
       ){
       return "view"; // name of the JSP
   }
}

The form bean:

class MyFormBean

private String elementName
//getters and setters

Your JSP:

<form:input path="elementName" />

Upvotes: 0

agxs
agxs

Reputation: 414

No, a Controller doesn't actually know about the contents of the view.

Parameters such as

request.getParameter("foo")

comes from the HTTP request and not from reading the HTML page. The "foo" part comes from the "name" attribute of the form element when the form is submitted.

Instead, you could use some JavaScript to get a list of elements that match particular CSS classes and then dynamically edit your form submit to GET/POST the contents of these elements to your controller.

Upvotes: 1

matt b
matt b

Reputation: 139961

No it is not possible, because when the user POSTs data to your webapp, the HTML element classnames are not sent - only the name and values of the input elements.

Upvotes: 0

Related Questions