How to populate entity object values on Spring Form using jquery/ajax? - ajax

I have the Spring form
<form:form method="POST" action="/HelloWeb/addStudent" id="myForm">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
i can submit this form to controller using
$.post('{controller path}', $('#myForm').serialize());
now i want to populate entity object using jquery/Ajax on the this form and object will be returned from controller.
kindly guide me?
here is controller that call new page and populate object data on form...
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public ModelAndView addStudent(#ModelAttribute("SpringWeb")Student student, ModelMap model)
{
Student stud =new Student();
//here will be my code to use student object....
return new ModelAndView("ViewStudent", "SpringWeb",stud);
}
but this method load new page ...instead of calling new i want do this logic on same page

The form: tags are interpreted on the server side, and generate regular HTML tags on the client side. Since jQuery is only running on the client side, it won't be able to find things using the form: tags. Try running the page and viewing the HTML source, then base your jQuery selectors on what you see there.

Related

Neither BindingResult nor plain target object for bean name 'user' available as request attribute error

I am new on spring. I am just trying to create my own CRUD OneToMany project. I have user and course table in my database. Course table has user_id foreign key references user(id).
When user successfully logged into the page, homePage.jsp comes and user courses are listed. When we click "Add Course" button in homePage.jsp, course-form.jsp file comes and we should add course.
The problem is, when I try to add course, I lost my user modelAttribute because in this time another attribute is on process with spring mvc.
When addedCourse form action performed these error occurs,
Cannot invoke "com.veg.entity.User.addCourse(com.veg.entity.Course)" because "user" is null
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
My Controller,
#PostMapping("/showFormForAdd")
public String showFormForAdd(#ModelAttribute("user") User theUser, Model theModel) {
Course theCourse = new Course();
theCourse.setUser(theUser);
theModel.addAttribute("course", theCourse);
theModel.addAttribute("user", theUser);
return "course-form";
}
#PostMapping("addedCourse")
public String addedCourse(#ModelAttribute("course") Course theCourse, Model theModel) {
User user = theCourse.getUser();
userService.save(user, theCourse);
theModel.addAttribute("user", user);
return "homePage";
}
homePage.jsp
<p>Welcome ${user.username}</p>
<span>
<form:form action="showFormForAdd" modelAttribute="user" method="POST">
<form:hidden path="username"/>
<form:hidden path="password"/>
<input type="submit" value="Add Course" class="add-course"/>
</form:form>
</span>
<table>
<tbody>
<tr>
<th>Course id</th>
<th>Course title</th>
</tr>
<c:forEach var="temp" items="${user.courses}">
<tr>
<td> ${temp.id} </td>
<td> ${temp.title} </td>
</tr>
</c:forEach>
</tbody>
</table>
course-form.jsp
<p>Welcome ${user.username}</p>
<span>
<form:form action="loggedUser" modelAttribute="user" method="POST">
<form:hidden path="username"/>
<form:hidden path="password"/>
<input type="submit" value="Back to Course List" class="add-course"/>
</form:form>
</span>
<!-- In the below I lost my user modelAttribute because I should use course attribute -->
<form:form action="addedCourse" modelAttribute="course" method="POST">
<table>
<tbody>
<tr>
<td> Title </td>
<td> <form:input path="title"/> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Course" class="add-course"/>
</td>
</tr>
</tbody>
</table>
</form:form>
I have #Transactional in my service, #Repository in my DAO and there is no problem with sessionFactory.

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

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).

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>

Convert Spring checkboxes to Spring submit buttons

Below Spring form submits data to a Spring controller and works as expected.
How can I convert the checkboxes to buttons ? So instead of three checkboxes : 'isTest1,isTest3,isTest3' three buttons are displayed.
This then means instead of having one submit button I have three submit buttons with each button.
Here is my form currently :
<form:form method="post" modelAttribute="searchobj" action="redirect">
<table>
<tr>
<td><form:input path="param" /></td>
<td><input type="submit" value="Search"/></td>
</tr>
</table>
<table>
<td>isTest1</td>
<td><form:checkbox path="isTest1" /></td>
<td>isTest2</td>
<td><form:checkbox path="isTest2" /></td>
<td>isTest3</td>
<td><form:checkbox path="isTest3" /></td>
</tr>
</table>
</center>
</form:form>
I've tried linking the form directly to the submit button so instead of
<td><form:checkbox path="isTest1" /></td>
use
<td><input type="submit" value="isTest1"/></td>
but I dont how to access the value in the controller ?
I used :
<form:input type="submit" path="myPath" value="Tester"/>

Resources