Spring MVC: Neither BindingResult nor plain target object for bean name 'marks' available as request attribute. Tried all solutions - spring

I tried all the solutions but I keep getting this error. Moreover if i don't use form:form in jsp file and use a simple HTML, I get the desired output.
Controller Class
#Controller
public class controller_class {
/*
* #RequestMapping(path = "/index", method = RequestMethod.GET) public
* ModelAndView mar() { return new ModelAndView("index","command",new marks());
* }
*/
#RequestMapping("/index")
public ModelAndView showComments() {
return new ModelAndView("marks","command",new marks());
}
#RequestMapping(value = "/addMarks", method = RequestMethod.POST)
public ModelAndView stud(#ModelAttribute("marks") marks m) {
ModelAndView mv = new ModelAndView("result");
int k = m.calculate();
mv.addObject("tot_marks", k);
return mv;
}
}
index.jsp
<form:form method = "POST" modelAttribute="marks" action = "/springmvc_qa3/addMarks">
<table>
<tr>
<td><form:label path = "sci_marks">Name</form:label></td>
<td><form:input path = "sci_marks" /></td>
</tr>
<tr>
<td><form:label path = "maths_marks">Age</form:label></td>
<td><form:input path = "maths_marks" /></td>
</tr>
<tr>
<td><form:label path = "eng_marks">id</form:label></td>
<td><form:input path = "eng_marks" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
Correct Output if I use this instead
<form method="POST" action="/springmvc_qa3/addMarks" >
<table>
<tr>
<td><label >Science Marks</label></td>
<td><input type="text" name="sci_marks" /></td>
</tr>
<tr>
<td><label >Mathematics Marks</label></td>
<td><input type="text" name="maths_marks" /></td>
</tr>
<tr>
<td><label >English Marks</label></td>
<td><input type="text" name="eng_marks" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
What is the reason that I can't get the right output using the first method?

add the following to your controller class:
#ModelAttribute("marks")
public Marks nameOfMethodDoesntMatter(){
return new Marks();
}
make sure your Marks class has getters, setters and default constructor.
consider calling your class MarksDTO or something similar to convey its meaning better (DTO = data transfer object).

Related

How to send table data from HTML form submit via ajax call to Spring MVC controller

Say i have a HTML table in a format similar to this
<form> <table id="a">
<thead>
<th>Name</th>
<th>Series</th>
<th>Value</th>
</thead>
<tbody id="b">
<tr><td>Enhancer</td><td>Enhancement</td><td>50</td></tr>
<tr><td>Plans</td><td>Plan</td><td>50</td></tr>
</tbody>
</table>
<input type="submit" value="Send" action="SomeControllerAction" /></form>
which has two rows under the headings "Name","Series" and "Value" .
I need to send this data via a form submit to a Spring Controller with Ajax where i can get or set the values for each row iteratively in a Model.
I am not sure how to achieve this . That is how to send the data in a table to a spring controller method and get the values .
Help with code segments!
Thanks
Although the previous answer is correct, I would suggest to introduce a class that contains three fields : name, series and value.
This class should have a meaningful name.
Here I named it MyObject because I don't know what you app is about.
MyObject :
public class MyObject {
private String name, series;
private Integer value;
// Getters and setters
}
Controller (the return type might be different)
#PostMapping("/series")
#ResponseBody
public List<MyObject> postSeries(#RequestBody List<MyObject> myObjects) {
myObjects.forEach(System.out::println);
// Handle myObjects
return myObjects;
}
JSP
<table id="tableMyObjects">
<thead id="a">
<tr>
<th>Name</th>
<th>Series</th>
<th>Value</th>
</tr>
</thead>
<tbody id="b">
<tr>
<td><input type="text" name="name" /></td>
<td><input type="text" name="series" /></td>
<td><input type="text" name="value" /></td>
</tr>
<tr>
<td><input type="text" name="name" /></td>
<td><input type="text" name="series" /></td>
<td><input type="text" name="value" /></td>
</tr>
</tbody>
</table>
<button id="postButton">Post myObjects</button>
jQuery
$('#postButton').click(function() {
var myObjects = [];
$('#b tr').each(function(index, item) {
var $item = $(item);
myObjects.push({
name: $item.find("td input[name='name']").val(),
series: $item.find("td input[name='series']").val(),
value: $item.find("td input[name='value']").val(),
});
});
$.ajax({
url: '/series',
method: 'POST',
contentType : 'application/json; charset=utf-8',
data: JSON.stringify(myObjects)
})
.done(function(myObjects) {
// handle success
})
.fail(function() {
// handle fail
});
});
Using javascript/jquery you can do that easily.
Generate a input type hidden text field while iterating the table content like below with the same name.
<tbody id="b">
<tr>
<td>
<input type="hidden" name="Name" value="Enhancer" />
Enhancer
</td>
<td>
<input type="hidden" name="Series" value="Enhancement" />
Enhancement
</td>
<td>
<input type="hidden" name="Value" value="50" />
50
</td>
</tr>
</tbody>
and then get all the hidden fields values by name like below.
$("[name='Name']").val();
$("[name='Series']").val();
$("[name='Value']").val();
and then in controller accept those parameters as an array like below.
#RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(#RequestParam(value = "Name") String[] Name,
#RequestParam(value = "Series") String[] Series,
#RequestParam(value = "Value") String[] Value,
BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest){
//code goes here
}
NOTE : You have to write javascript code to set the hidden field values for multiple rows something like this Call javascript function with if JSTL

Handling multiple modelattributes of same type in the same controller method

i have following scenario :
#ModelAttribute("persons")
public void addAttributes(Model model) {
Person person = new Person()
;
person.setAge(26);
person.setFirstName("mars");
model.addAttribute("persons", person);
}
#RequestMapping(value="/process-person")
public ModelAndView processPerson(#ModelAttribute Person person,#ModelAttribute ("persons")Person persons,ModelAndView modelAndView ) {
//
//ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("person-result-page");
modelAndView.getModel().remove("personObj");
modelAndView.addObject("pers", person);
----> modelAndView.addObject("pers2", persons);// persons holds the myname1 provided in input box
modelAndView.addObject("personObj", person);
return modelAndView;
}
As shown in the --> i want this variable -persons to hold the value obtained from addAttributes() method but it is taking the same values that i input from the jsp page :
<form:form method="POST" commandName="person-entity" action="process-person.html">
<table>
<tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
<td></td>
<td></td>
</tr>
</table>
</form:form>
<br/>
i saw few similar questions but none of them resolved this problem . Here i want values from addAttribute method to placed inside "persons" object, but it is taking the same value as that of "person" being provided from the form.jsp.
please help me out

java.lang.IllegalArgumentException: Attribute 'items' must be an array, a Collection or a Map

i am trying to make simple spring mvc application, using jdbctemplate,but when i try to open registration page i got this error- java.lang.IllegalArgumentException: Attribute 'items' must be an array, a Collection or a Map.
last time i used this thing in another applicaton, it worked fine,but this time it is not working :(
here is my controller code and register.jsp
#RequestMapping("/register")
public ModelAndView registerEmployee(#ModelAttribute Employee employee) {
List<String> cityList = new ArrayList<String>();
cityList.add("kashipur");
cityList.add("moradabad");
cityList.add("delhi");
cityList.add("noida");
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
Map<String,List<String>> map = new HashMap<String,List<String>>();
map.put("cityList",cityList);
map.put("genderList",genderList);
return new ModelAndView("register","map",map);
}
register.jsp is
<div>
<form:form method="post" action="/insert" modelAttribute="employee">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobuttons path="gender" items="${map.genderList}" /></td>
</tr>
<tr>
<td>City :</td>
<td><form:select path="city" items="${map.cityList}" /></td>
<tr>
<tr>
<td>Email :</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Phone :</td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td><input type="submit" value="Save" /></td>
</tr>
<tr>
<td colspan="2"><a href="getList">Click Here to See User
List</a></td>
</tr>
</table>
</form:form>
</div>
Try to change this List<String> cityList
to this ArrayList<String> cityList
same here
Map<String,List<String>> map = new HashMap<String,List<String>>();
Also try to access map element like this map['cityList']
You don't need to qualify with ${map.
Simply write
return new ModelAndView("register", map);
and in the JSP:
<td><form:radiobuttons path="gender" items="${genderList}" /></td>
and
<td><form:select path="city" items="${cityList}" /></td>

What should be the value of #ModelAttribute when handling POST in Spring MVC?

I'm learning Spring MVC with the tutorial of the site here
My question is basically in the code fragment bellow.
#RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact")
Contact contact, BindingResult result) {
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "redirect:contacts.html";
}
What should the value of #ModelAttribute be when just handling a POST request from a form submit?
Or in other words, what exactly does the "contact" value refers to in this situation?
The posted form is defined as follows:
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="lastname">Telephone</form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>

can someone explain how the controller class works

I am working on spring samples.I have a controller class named UserController2 as follows
#Controller
public class UserController2 extends MultiActionController {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response, User user) throws Exception {
userDAO.saveUser(user);
return new ModelAndView("redirect:User.htm");
}
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
modelMap.addAttribute("userList", userDAO.listUser());
modelMap.addAttribute("User", new User());
return new ModelAndView("userForm", modelMap);
}
}
and i have a jsp page called userForm.jsp
<form:form method="POST" action="add.htm" commandName="User" modelAttribute="User">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="password">Name</form:label></td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td><form:label path="gender">Name</form:label></td>
<td><form:input path="gender" /></td>
</tr>
<tr>
<td><form:label path="gender">Name</form:label></td>
<td><form:input path="gender" /></td>
</tr>
<tr>
<td><form:label path="country">Name</form:label></td>
<td><form:input path="country" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
what actually does the below codes returns
return new ModelAndView("userForm", modelMap);
and
return new ModelAndView("redirect:User.htm");
I am getting the following error
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'User' available as request attribute
I searched but i cannot find a proper explanation for modelandview..
When using the modelAttribute make user that:1. Your method parameter user is annotated with #ModelAttribute("user")2. A method parameter of type BindingResult is declared.
Also, the annotation parameter value is case sensitive, and should exactly match the value of the modelAttribute you declared in userForm.jsp.

Resources