I know this is a question which has been asked before. I did look at those questions but I was still not able to resolve my problem and thus writing in on stackoverflow. I am trying to bind the form parameters from my form addArticles.jsp to the controller. On the controller when I do a system.out.println I only get the categoryId and do not get the categoryName. I am not sure what I am doing is incorrect and pretty amused.
addArticles.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Article</title>
</head>
<body>
<center>
<h2>Create New Article</h2>
<form:form action="/one2one/articles/save.do" method="POST" modelAttribute="command">
<table>
<tr>
<td><form:label path="id">Article ID</form:label></td>
<td><form:input path="id" value="${article.id}"></form:input></td>
</tr>
<tr>
<td><form:label path="title">Article Title</form:label></td>
<td><form:input path="title" value="${article.title}"></form:input></td>
</tr>
<tr>
<td><form:label path="description">Article Description:</form:label></td>
<td><form:input path="description" value="${article.description}" cssStyle="width: 150px;"></form:input></td>
</tr>
<tr>
<td><form:label path="category.categoryId">Category Type</form:label></td>
<td><form:select path="category.categoryId" cssStyle="width: 150px;">
<option value="-1">Select a type</option>
<c:forEach items="${categories}" var="category">
<option <c:if test="${category.categoryName eq article.category.categoryName}">selected="selected"</c:if>
value="${category.categoryId}">${category.categoryName}</option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td><form:label path="keywords">Article Keywords:</form:label></td>
<td><form:input path="keywords" value="${article.keywords}"></form:input></td>
</tr>
<tr>
<td><form:label path="content">Article Content:</form:label></td>
<td><form:input path="content" value="${article.content}"></form:input></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="SAVE"/></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
ArticlesController.java
package com.java.bricks.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.java.bricks.model.Article;
import com.java.bricks.model.Category;
import com.java.bricks.service.ArticleService;
import com.java.bricks.service.CategoryService;
#Controller("articlesController")
#RequestMapping(value="/articles")
public class ArticlesController {
#Autowired
private ArticleService articleService;
#Autowired
private CategoryService categoryService;
#RequestMapping(value="/list", method=RequestMethod.GET)
public ModelAndView listArticles(#ModelAttribute("command") Article article, BindingResult bindingResult){
Map<String,Object> model = new HashMap<String,Object>();
model.put("articles", articleService.listArticles());
return new ModelAndView("articlesList",model);
}
#RequestMapping(value="/add",method=RequestMethod.GET)
public ModelAndView addArticle(#ModelAttribute("command") Article article, BindingResult bindingResult) {
Map<String,Object> model = new HashMap<String,Object>();
model.put("articles", articleService.listArticles());
model.put("categories", categoryService.listCategories());
return new ModelAndView("addArticle",model);
}
#RequestMapping(value="/save",method=RequestMethod.POST)
public ModelAndView saveArticle(#ModelAttribute("command") Article article, BindingResult bindingResult) {
Map<String,Object> model = new HashMap<String,Object>();
System.out.println("----------------------");
System.out.println(article.getCategory());
System.out.println(article.getCategory().getCategoryName());
System.out.println(article.getCategory().getCategoryId());
articleService.addArticle(article);
model.put("articles",articleService.listArticles());
return new ModelAndView("addArticle",model);
}
}
when I click save the first 4 lines of the SOP statements are
System.out.println(article.getCategory());
output: Category [categoryId=29, categoryName=null]
System.out.println(article.getCategory().getCategoryName());
null
System.out.println(article.getCategory().getCategoryId())
29
I am not sure why the categoryName is not populated in the controller.
Article.java
package com.java.bricks.model;
public class Article {
private Long id;
private String title;
private String description;
private String keywords;
private String content;
private Category category;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
You aren't going to get the category name in the form's content because the category's name is being used a the label for the option. Only the value gets bound. This is your binding path="category.categoryId". You aren't binding anything to path="category.categoryName" so it's going to be null.
So in your controller you have to get the category by its ID. If you want to do some automatic custom conversion, that is a separate question.
Here's a nice article on entity conversion.
Related
I'm trying to insert a new user to the database , which contains a foreign key to userRole . i populated a roles dropdown list in jsp from the database , inserted in a form in which I'll add a new user . i'm really blocked for days now ... user also has a primary key.
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: jpa.project.model.DemUser.idRole
Role entity :
#Entity
#Table(name="DEM_ROLE")
#NamedQuery(name="DemRole.findAll", query="SELECT d FROM DemRole d")
public class DemRole implements Serializable {
private static final long serialVersionUID = 1L;
private long idRole;
private String libRole;
private String librole;
public DemRole() {
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID_ROLE", unique=true, nullable=false)
public long getIdRole() {
return this.idRole;
}
public void setIdRole(long idRole) {
this.idRole = idRole;
}
#Column(name="LIB_ROLE", nullable=false, length=50)
public String getLibRole() {
return this.libRole;
}
public void setLibRole(String libRole) {
this.libRole = libRole;
}
#Column(length=255)
public String getLibrole() {
return this.librole;
}
public void setLibrole(String librole) {
this.librole = librole;
}
}
User Entity :
#Entity
#Table(name="DEM_USER")
#NamedQuery(name="DemUser.findAll", query="SELECT d FROM DemUser d")
public class DemUser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID_USER", unique=true, nullable=false)
private long idUser;
#Column(name="NAME_USER", nullable=false, length=50)
private String nameUser;
#Column(nullable=false, length=20)
private String password;
//uni-directional many-to-one association to DemRole
#ManyToOne(cascade={CascadeType.ALL},fetch = FetchType.LAZY)
#JoinColumn(name="ID_ROLE", nullable=false)
private DemRole idRole;
public DemUser() {
}
public long getIdUser() {
return this.idUser;
}
public void setIdUser(long idUser) {
this.idUser = idUser;
}
public String getNameUser() {
return this.nameUser;
}
public void setNameUser(String nameUser) {
this.nameUser = nameUser;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public DemRole getIdRole() {
return this.idRole;
}
public void setIdRole(DemRole idRole) {
this.idRole = idRole;
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
Controller :
#RequestMapping(value = "/",method = RequestMethod.GET)
public ModelAndView home(ModelAndView model,HttpServletRequest request) throws IOException {
List<DemUser> listUsers = service.getAllUsers();
model.addObject("listUsers", listUsers);
List<DemRole> listRoles = service.getRoles();
request.setAttribute("listRoles", listRoles);
/*List<DemRole> listRoles = service.getRoles();
model.addObject("listRoles", listRoles); */
DemUser user = new DemUser();
model.addObject("DemUser", user);
model.setViewName("manageusers");
return model;
}
#RequestMapping(value = "/actionadduser", method = RequestMethod.POST)
public String actionadduser(ModelAndView model,#ModelAttribute DemRole role ,#ModelAttribute DemUser user,BindingResult result) {
service.addUser(user);
return "redirect:/";
}
JSP :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="left">
This is manage users
<table border="1">
<h1>users</h1>
<tr><td> Names : </td> </tr>
<c:forEach var="user" items="${listUsers}">
<tr>
<td>${user.nameUser}</td>
</tr>
</c:forEach>
</table>
</div>
<div align="right">
<h1>New user</h1>
<form:form action="actionadduser" method="post" modelAttribute="DemUser">
<table>
<form:hidden path="idUser" />
<form:hidden path="password" value="password" />
<tr>
<td>Name:</td>
<td><form:input path="nameUser" /></td>
</tr>
<tr>
<td>Roles :</td>
<td>
<form:select path="idRole">
<form:options items="${listRoles}" itemValue="idRole" itemLabel="libRole"></form:options>
</form:select></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
There are couple of points,
As roles already exist before adding a new User, So you don't need to have any type of cascading in #ManyToOne mapping, you can remove cascading at all.
//uni-directional many-to-one association to DemRole
#ManyToOne
#JoinColumn(name="ID_ROLE", nullable=false)
private DemRole idRole;
I can see in your POST method, you are receiving DemRole and DemUser and calling the service class to persist the user, but I can't see anywhere that you are populating the received role object into received user object. As User is having Role object, so before saving user object, you need to have something like this,
#RequestMapping(value = "/actionadduser", method = RequestMethod.POST)
public String actionadduser(ModelAndView model,#ModelAttribute DemRole role ,#ModelAttribute DemUser user,BindingResult result) {
// set role object to user object
user.setIdRole(role); // setter for DemRole object.
service.addUser(user);
return "redirect:/";
}
Hope this helps, please let me know if any more clarifications are needed.
I want to insert into two tables from jsp using spring mvc4 and hibernate.
Here is my two model class.
1)Employee.java
package com.websystique.springmvc.model;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
import com.websystique.springmvc.model.UserLogin;;
#Entity
#Table(name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Size(min=3, max=50)
#Column(name = "NAME", nullable = false)
private String name;
#NotNull
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(name = "JOINING_DATE", nullable = false)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate joiningDate;
#NotNull
#Column(name = "SALARY", nullable = false)
private int salary;
#NotEmpty
#Column(name = "SSN", unique=true, nullable = false)
private String ssn;
#Column(name="emp_id",nullable=true)
private String emp_id;
public UserLogin getUserlogin() {
return userlogin;
}
public void setUserlogin(UserLogin userlogin) {
this.userlogin = userlogin;
}
public String getEmp_id() {
return emp_id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
#OneToOne(targetEntity=UserLogin.class,cascade=CascadeType.ALL)
#JoinColumn(name="emp_id",referencedColumnName="emp_id",insertable=false, updatable=false)
private UserLogin userlogin;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(LocalDate joiningDate) {
this.joiningDate = joiningDate;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Employee))
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (ssn == null) {
if (other.ssn != null)
return false;
} else if (!ssn.equals(other.ssn))
return false;
return true;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", joiningDate="
+ joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";
}
}
2)UserLogin.java
package com.websystique.springmvc.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name="users")
public class UserLogin implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name="emp_id", unique=true, nullable=true)
private String emp_id;
#Column(name="user_name",nullable=false)
private String user_name;
#Column(name="password",nullable=false)
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And here is my jsp page(registration.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form:form method="POST" modelAttribute="employee">
<form:input type="hidden" path="id" id="id"/>
<table>
<tr>
<td><label for="name">Name: </label> </td>
<td><form:input path="name" id="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="user_name">User Name: </label> </td>
<td><form:input path="user_name" id="user_name"/></td>
<td><form:errors path="user_name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="pwd">Password: </label> </td>
<td><form:input type="password" path="password" id="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td><label for="joiningDate">Joining Date: </label> </td>
<td><form:input path="joiningDate" id="joiningDate"/></td>
<td><form:errors path="joiningDate" cssClass="error"/></td>
</tr>
<tr>
<td><label for="salary">Salary: </label> </td>
<td><form:input path="salary" id="salary"/></td>
<td><form:errors path="salary" cssClass="error"/></td>
</tr>
<tr>
<td><label for="ssn">SSN: </label> </td>
<td><form:input path="ssn" id="ssn"/></td>
<td><form:errors path="ssn" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update"/>
</c:when>
<c:otherwise>
<input type="submit" value="Register"/>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to List of All Employees
</body>
</html>
Here is my controller
#RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Employee employee,#Valid UserLogin userLogin, BindingResult result,
ModelMap model) {
System.out.println("inside controller");
System.out.println("result>>>> "+result);
if (result.hasErrors()) {
System.out.println("inside controller1111111111");
return "registration";
}
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
System.out.println("inside controller1111111111222222222222222222222");
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
String emp="Emp-"+employee.getId()+"-"+employee.getName();
System.out.println("emp>>> "+emp);
employee.setEmp_id(emp);
service.saveEmployee(employee);
userservice.saveUser(userLogin);
model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
return "success";
}
So I want to save user_name and password into login table and rest of the data want to save into another table. Is there anyone who can help me how to insert data into two tables. I searched a lot but did not get fruitful result. Any link for this problem is also appreciated. Thanks in advance
You can use entity inheritance. Check this http://www.thoughts-on-java.org/complete-guide-inheritance-strategies-jpa-hibernate/
. Select strategy which fits your reqirements.
I am getting an exception while creating a form using spring forms tag library
"Neither BindingResult nor plain target object for bean name 'command' available as request attribute"
The jsp page is index.jsp
<%# include file="views/static_include.jsp" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login to AVA Corp</title>
</head>
<body>
<form:form method="POST" commandName="user" action="login.jsp">
<table>
<tbody><tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
</td>
<td></td>
<td></td>
</tr>
</tbody></table>
</form:form>
</body>
</html>
The bean class is:
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1949001721422434327L;
private String firstName;
private Integer age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
The controller class is
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView initForm(Model model) {
return new ModelAndView("index", "user", new Employee());
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(#ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", employee);
return "UserFormSuccess";
}
}
I found that the issue was with the controller method with method type = "get". The value of the request method needs to be the URL mapping of the page on which the form resides e.g. index.jsp in our case so the controller class will be
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView initForm(Model model) {
return new ModelAndView("index", "user", new Employee());
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(#ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", employee);
return "UserFormSuccess";
}
}
In spring mvc, when creating a ModelAndView there's a method called addObject(Object attributeName) single parameter, and I don't understand how to make use of it. I also see model.addAllObjects(Map<String, ?> object).
How can I get that map in jsp? Or what is the purpose of those methods? I only know how to make use of model.addObject("car", new Car()) because is like defining servlet parameters. I found this information in spring but I don't really understand it.
Spring addObject and addAllObjects
please check the example below. i have shed how to use addObject(Object attributeValue) as well as addAllObjects(Map<String, ?> modelMap).
Car.java
public class Car {
private String regNo;
private String model;
private String year;
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
PageContent.java
public class PageContent {
private String headerName;
public String getHeaderName() {
return headerName;
}
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
}
Controller Method
#RequestMapping(value = "/showCars", method = RequestMethod.GET)
public ModelAndView showApp() {
ModelAndView modelAndView = new ModelAndView();
//adding a single attribute for the modelMap
PageContent pageContent = new PageContent();
pageContent.setHeaderName("All Cars - From Controller");
modelAndView.addObject(pageContent);
List<Car> carList = new ArrayList<>();
Car car1 = new Car();
car1.setModel("Toyota");
car1.setRegNo("223456");
car1.setYear("2005");
Car car2 = new Car();
car2.setModel("Mazda");
car2.setRegNo("24244");
car2.setYear("2015");
Car car3 = new Car();
car3.setModel("Nissan");
car3.setRegNo("4465757");
car3.setYear("2013");
carList.add(car1);
carList.add(car2);
carList.add(car3);
Map<String,Object> allObjectsMap = new HashMap<String,Object>();
allObjectsMap.put("allCarObjects", carList);
//adding a set of objects for the model map
modelAndView.addAllObjects(allObjectsMap);
modelAndView.setViewName("CarView");
return modelAndView;
}
CarView.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>ModelAttribute Example</title>
</head>
<body>
<h1>${pageContent.headerName}</h1>
<table>
<tr>
<th>Model</th>
<th>Registration No</th>
<th>Year of Manufacture</th>
</tr>
<c:forEach var="car" items="${allCarObjects}">
<tr>
<td><c:out value="${car.model}" /></td>
<td><c:out value="${car.regNo}" /></td>
<td><c:out value="${car.year}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Hope this will helpful for you!
well,the first method addObject which would invoked when forward happend and brings the data to jsp.Then you can iterate the data in your jsp with jstl or something else.The method addAllObjects is just a multiple type of addObject,just like map's method put and putAll.
HI hava a problem while creating a CRUD operation in browser
`HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: org.apache.jasper.JasperException: org.springframework.beans.NotReadablePropertyException: Invalid property 'standard' of bean class [com.raistudies.domain.User]: Bean property 'standard' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:548)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:456)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
here I have all part of the spring mvc + mybatis operations file
//controller
package com.raistudies.controllers;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.raistudies.domain.User;
import com.raistudies.persistence.UserService;
import com.raistudies.validator.RegistrationValidator;
#Controller
#RequestMapping(value="/registration")
public class RegistrationController {
private RegistrationValidator validator = null;
private UserService userService = null;
#Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
public RegistrationValidator getValidator() {
return validator;
}
#Autowired
public void setValidator(RegistrationValidator validator) {
this.validator = validator;
}
#RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
List<User> users = userService.getAllUser();
model.addAttribute("users", users);
User user = new User();
user.setId(UUID.randomUUID().toString());
model.addAttribute("user", user);
return "registration";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView add(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.saveUser(user);
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
#RequestMapping(value="/update", method=RequestMethod.POST)
public ModelAndView update(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.updateUser(user);
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
#RequestMapping(value="/delete", method=RequestMethod.POST)
public ModelAndView delete(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.deleteUser(user.getId());
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
}
persistance is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.raistudies.persistence.UserService">
<resultMap id="result" type="user">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="studentClass" column="class"/>
<result property="roll" column="roll"/>
<!-- <result property="sex" column="sex"/>-->
</resultMap>
<select id="getAllUser" resultMap="result">
SELECT id,name,class,roll
FROM user;
</select>
<insert id="saveUser" parameterType="user">
INSERT INTO user (id,name,standard,age,sex)
VALUE (#{id},#{name},#{standard},#{age})
</insert>
<update id="updateUser" parameterType="user">
UPDATE user
SET
name = #{name},
standard = #{standard},
age = #{age},
sex = #{sex}
where id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user
WHERE id = #{id}
</delete>
</mapper>
I have to do create delete update add operation but it is going to be error just like above while running my project......please help me
after changing the jsp code as per the variable that the java bean class(class containing geter or setter method) has.Then it will solve the problem.
*especially what I mean is you have to change the path in jsp <tr><td>Class : </td><td><form:input path="standard" /></td></tr>*as per the bean variable
previous jsp file (at error time)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# page session="true" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World with Spring 3 MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<script type="text/javascript" src='<c:url value="/resources/common.js"/>'></script>
<script type="text/javascript" src='<c:url value="/resources/registration.js"/>'></script>
<script type="text/javascript">
var projectUrl = '<c:url value="/"/>';
if(projectUrl.indexOf(";", 0) != -1){
projectUrl = projectUrl.substring(0, projectUrl.indexOf(";", 0));
}
</script>
</head>
<body>
<fieldset>
<legend>Registration Form</legend>
<center>
<form:form commandName="user" action="/SpringMVCMyBatisCRUDExample/app/registration/add" name="userForm">
<form:hidden path="id"/>
<table>
<tr><td colspan="2" align="left"><form:errors path="*" cssStyle="color : red;"/></td></tr>
<tr><td>Name : </td><td><form:input path="name" /></td></tr>
<tr><td>Class : </td><td><form:input path="standard" /></td></tr>
<tr><td>RollNo: </td><td><form:input path="roll" /></td></tr>
<tr><td colspan="2"><input type="submit" value="Save Changes"/>
<input type="reset" name="newUser" value="New User" onclick="setAddForm();" disabled="disabled"/>
<input type="submit" name="deleteUser" value="Delete User" onclick="setDeleteForm();" disabled="disabled"/></td></tr>
</table>
</form:form>
</center>
</fieldset>
<c:if test="${!empty users}">
<br />
<center>
<table width="90%">
<tr style="background-color: gray;">
<th>Name</th>
<th>Class</th>
<th>RollNo</th>
</tr>
<c:forEach items="${users}" var="user">
<tr style="background-color: silver;" id="${user.id}" onclick="setUpdateForm('${user.id}');">
<td><c:out value="${user.name}"/></td>
<td><c:out value="${user.studentClass}"/></td>
<td><c:out value="${user.roll}"/></td>
</tr>
</c:forEach>
</table>
</center>
<br />
</c:if>
</body>
my java bean class
package com.raistudies.domain;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 3647233284813657927L;
private String id;
private String name = null;
private String studentClass = null;
private String roll;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentClass() {
return studentClass;
}
public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
#Override
public String toString() {
return "User [name=" + name + ", class="+ studentClass+ ", roll=" + roll + "]";
}
}
previously I had standard variable in java bean class(model class) but I have to change it to studentClass so not to be error we must change the jsp path that is
<tr><td>Class : </td><td><form:input path="standard" /></td></tr>.......
to
<tr><td>Class : </td><td><form:input path="studentClass" /></td></tr>