"Neither BindingResult nor plain target object for bean name 'command' available as request attribute" - spring

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";
}
}

Related

not-null property references a null value while adding new user with foreign key

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.

Add student without avatar

I created a project where you can add a student with an avatar and without an avatar. The problem is that when I add a student without an avatar, there is still a tag. How can I remove the tag. Now I will add an image and a couple of classes. I kind of wrote everything correctly, I don’t know where the error might be
#Controller
public class AvatarController {
#Value("${storage.location}")
private String storageLocation;
private StudentService studentService;
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
#Autowired
public AvatarController(StudentService studentService) {
this.studentService = studentService;
}
#GetMapping(value = "/avatar")
public void getAvatar(HttpServletResponse response, #Param("avatar") String avatar) {
if (avatar == null || avatar.isEmpty()) {
return;
}
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
try (FileInputStream input = new FileInputStream(studentService.loadAvatarByFileName(avatar))){
IOUtils.copy(input, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
#RequestMapping(value = "/image", method = RequestMethod.GET)
public void image(#RequestParam String url, HttpServletResponse response) throws IOException {
InputStream in = new FileInputStream(url);
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
IOUtils.copy(in, response.getOutputStream());
}
}
Student Service Impl
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Value("${storage.location}")
private String storageLocation;
private StudentRepository repository;
public StudentServiceImpl() {
}
#Autowired
public StudentServiceImpl(StudentRepository repository) {
super();
this.repository = repository;
}
#Override
public List<Student> getAllStudents() {
List<Student> list = new ArrayList<Student>();
repository.findAll().forEach(e -> list.add(e));
return list;
}
#Override
public Student getStudentById(Long id) {
Student student = repository.findById(id).get();
return student;
}
#Override
public boolean saveStudent(Student student) {
try {
repository.save(student);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
public boolean deleteStudentById(Long id) {
try {
repository.deleteById(id);
return true;
} catch (Exception ex) {
return false;
}
}
#Override
public File loadAvatarByFileName(String filename) {
return new File(storageLocation + "/" + filename);
}
#Override
public File saveAvatarImage(MultipartFile avatarImage) throws IOException {
File newFile = File.createTempFile(
avatarImage.getName(),
"." + avatarImage.getOriginalFilename().split("\\.")[1],
new File(storageLocation));
avatarImage.transferTo(newFile);
return newFile;
}
#Override
public Student updateStudent(String name, String surname, MultipartFile avatar, Student targetStudent)
throws IOException {
if (name != null && !name.equals(targetStudent.getName())) {
targetStudent.setName(name);
}
if (surname != null && !surname.equals(targetStudent.getSurname())) {
targetStudent.setSurname(surname);
}
File newAvatar;
if (!avatar.getOriginalFilename().isEmpty()) {
if (targetStudent.getAvatar() != null) {
Files.deleteIfExists(Paths.get(storageLocation + File.separator + targetStudent.getAvatar()));
}
newAvatar = saveAvatarImage(avatar);
assert newAvatar != null;
targetStudent.setAvatar(newAvatar.getName());
}
boolean isSaved = saveStudent(targetStudent);
if (!isSaved) {
throw new IOException();
}
return targetStudent;
}
}
Student Controller
#Controller
public class StudentController {
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
private StudentService studentService;
public StudentController() {
}
#Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/allStudentsAdmin", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#Secured("ROLE_USER")
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudent");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudent")
public String saveNewStudent(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/allStudents";
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("editStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
#PostMapping(value = "/editStudent")
public String saveEditedUser(
#RequestParam("id") Long id,
#RequestParam("name") String name,
#RequestParam("surname") String surname,
#RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/error";
}
return "redirect:/allStudents";
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/allStudents");
return mv;
}
}
AllStudent JSP
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!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=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<style><%#include file="/css/style.css"%></style>
<title>Все студенты</title>
</head>
<body>
<br>
<br>
<br>
<br>
<div class="it">
<h3>Список всех студентов</h3>
${message}
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${studentList}">
<tr>
<th scope="row">1</th>
<td>${student.name}</td>
<td>${student.surname}</td>
<td><c:choose>
<c:when test="${student.avatar ne null}">
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;" />
</td>
</c:when>
</c:choose></td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/editStudent/${student.id}">
<button type="button" class="btn btn-primary">Edit</button>
</a>
</sec:authorize>
</td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
<button type="button" class="btn btn-primary">Delete</button>
</a>
</sec:authorize>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
#user404 answer ok but need some change
<c:choose>
<c:when test="${student.avatar ne null}">
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;" />
</td>
</c:when>
<c:otherwise>
<td></td>
</c:otherwise>
</c:choose>
despription : When avater is null or empty then add a empty cell on
our html table other wise add image with full src path
You have to check the condition if your student.avatar holds avatar or null and based on that, show your image or not. Coz, that image tag for empty avatar your see because of img tag. You can use if-else condition in jstl or like this.
try this:
<c:choose>
<c:when test="${student.avatar ne null}">
<td>
<img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}"
style="max-height: 200px; max-width: 200px;" />
</td>
</c:when>
<c:otherwise>
<td></td>
</c:otherwise>
</c:choose>

What is the purpose of spring model addObject(Object attributeName)?

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.

CRUD using spring and mybatis

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>

Spring Framework <form:errors/> tag not showing errors

I know there are many similar questions here, but none of them solved my problem.
I'm using Spring 4.0.3 and Hibernate Validator 5.1.0.
The problem occurs when I try to omit the path attribute of the <form:errors/> tag, so:
<form:errors path="contato.nome" /> works
<form:errors path="*" /> works
<form:errors /> doesn't work
I don't know why it happens. Spring javadocs (org.springframework.web.servlet.tags.form.ErrorsTag) says it should work like that:
Field only - set path to the field name (or path)
Object errors only - omit path
All errors - set path to *
Can you help me, please?
The interested code is in the 'edicao.jsp' and in the method 'confirmarEdicao' of the ContatoController.java. Sorry if my english is bad.
ContatoController.java
#Controller
#RequestMapping("/contatos")
public class ContatoController {
#Autowired
private ContatoService contatoService;
#Autowired
private MessageSource messageSource;
#RequestMapping(value = "/confirmarEdicao", method = RequestMethod.POST)
public String confirmarEdicao(#Valid Contato contato, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "contatos/edicao";
}
contatoService.save(contato);
return "redirect:/contatos";
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView form(HttpServletRequest request) {
String message = messageSource.getMessage("teste", null, new Locale("pt", "BR"));
System.out.println(message);
return new ModelAndView("contatos/listagem")
.addObject("contatos", contatoService.list());
}
#RequestMapping("/remover/{id}")
public String remover(Contato contato) {
contatoService.delete(contato);
return "redirect:/contatos";
}
#RequestMapping("/editar/{id}")
public ModelAndView formEdicao(Contato contato) {
contato = contatoService.find(contato.getId());
return new ModelAndView("contatos/edicao")
.addObject(contato);
}
#RequestMapping(value = "/cadastrar")
public String formCadastro() {
return "contatos/cadastro";
}
#RequestMapping(value = "/confirmarCadastro", method = RequestMethod.POST)
public String confirmarCadastro(#Valid Contato contato, BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasFieldErrors()) {
return "contatos/cadastro";
}
contatoService.save(contato);
redirectAttributes.addFlashAttribute("mensagem", "Contato cadastrado com sucesso.");
return "redirect:/contatos";
}
#ResponseBody
#RequestMapping(value = "/pesquisar/{nome}", method = RequestMethod.GET,
produces="application/json")
public List<Contato> pesquisar(#PathVariable String nome) {
return contatoService.findByName(nome);
}
}
edicao.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=UTF-8">
<title>Editar contato</title>
</head>
<body>
<c:set var="context">${pageContext.request.contextPath}</c:set>
<script type="text/javascript">var context = "${context}";</script>
<script src="${context}/resources/js/jquery-2.1.0.min.js"></script>
<script src="${context}/resources/js/contatos/edicao.js"></script>
<form:form commandName="contato" action="${context}/contatos/confirmarEdicao" method="post">
<form:errors/>
<table>
<form:hidden path="id"/>
<tr>
<td>Nome:</td>
<td><form:input path="nome" /></td>
</tr>
<tr>
<td>Telefone:</td>
<td><form:input path="telefone"/></td>
</tr>
<tr>
<td><input type="button" value="Voltar" id="btn_voltar"/><input type="submit" value="Salvar"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Contato.java
package com.handson.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class Contato {
private Long id;
#Size(min = 3, message = "Nome deve ter no mínimo 3 caracteres")
#NotEmpty(message = "O nome deve ser preenchido")
private String nome;
private String telefone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Contato withId(Long id) {
setId(id);
return this;
}
public Contato withTelefone(String telefone) {
setTelefone(telefone);
return this;
}
public Contato withNome(String nome) {
setNome(nome);
return this;
}
#Override
public String toString() {
return "Contato [id=" + id + ", nome=" + nome + ", telefone="
+ telefone + "]";
}
}
There are some keywords which should be defined:
path - EL-like path to an object or to a field of an object (e.g. foo, foo.bar or foo.bar.baz)
nested path - current path context stored as nestedPath request attribute (new paths are relative to this path)
object error - error connected with object itself (e.g. path is equal to foo)
field error - error connected with object field (e.g. path is foo.bar)
The tag <form:form commandName="foo"> defines nested path as nestedPath=foo. When you write <form:errors path="bar"> it tries to find errors defined for path foo.bar.
Lets say that you have errors connected with foo (object error), foo.bar and foo.bar.baz (nested field error). What this means:
if you enter <form:errors>, only errors bound to foo path are displayed => 1 message
if you enter <form:errors path="bar">, only errors bound to foo.bar path are displayed => 1 message
if you enter <form:errors path="*">, errors bound to foo and its child paths are displayed => 3 messages
if you enter <form:errors path="bar.*">, only child errors for foo.bar are diplayed => 1 message
if you enter <form:errors path="bar*">, errors bound to foo.bar and its child paths are diplayed => 2 messages
Checking on Errors class JavaDoc might give you additional insight.

Resources