I have jsp that show all posts in blog
<body>
<table>
<c:forEach var="post" items="${posts}">
<tr>
<td>${post.id}</td>
<td>${post.text}</td>
<td>Show author</td>
</tr>
</c:forEach>
</table>
<div>
JSON XML
</div>
</body>
I have controller to handle it
#Controller
public class PostsController {
#Autowired
private PostDAO postDao;
#RequestMapping("/posts")
public String showAllPosts(ModelMap model) {
List<Post> posts = postDao.findAll();
model.addAttribute("posts", posts);
return "posts";
}
#RequestMapping("/posts/get")
public List<Post> getAllPosts() {
List<Post> posts = postDao.findAll();
return posts;
}
}
Now I want to add form to save new post.
I add form in my jsp
<form:form method="POST" action="/posts/add" modelAttribute="post">
<table>
<tr>
<td><form:label path="id">Id:</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="text">Text:</form:label></td>
<td><form:input path="text" /></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
Also I add to controller.
#RequestMapping( value = "/posts/add", method = RequestMethod.POST)
public String saveAdd(#ModelAttribute("post") Post post, ModelMap model) {
model.addAttribute("posts", postDao.addPost(post));
return "posts";
}
Domain model Post.java
public class Post {
private int id;
private String author;
private String text;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
But I get
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'post' available as request attribute
Because your JSP contains the new form for adding a new post, it will need the model attribute post to be present when you go to /posts.
#RequestMapping("/posts")
public String showAllPosts(ModelMap model) {
List<Post> posts = postDao.findAll();
model.addAttribute("post", new Post()); // Add empty form backing object
model.addAttribute("posts", posts);
return "posts";
}
You could even split out model creation to a separate method if you find you're having to create the model in multiple places. This will ensure that its always available.
#ModelAttribute("post")
public Post createModel() {
return new Post();
}
From Controller:
#RequestMapping(value = "createcustomer",method = RequestMethod.GET)
public String customer(Model model)
{
Customer cus=new Customer();
cus.setCustomerNumber("Test");
model.addAttribute("customer",cus);
return "createcustomer";
}
In View:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<div class="cl">
<form:form commandName="customer" method="POST">
<p>Name: <c:out value="${customer.CustomerNumber}"></c:out></p>
</form:form>
<div>
Output:
Name: Test
Related
I am new to springboot and thymeleaf and I'm trying to understand the form handling methods that interact with the code. Below you will find my html documents linked to a Users class. I am trying to change them to link to a customer class amongst other things, but anytime I change the th:object=${users} to match the new entity 'customerentity' it gives me the error below. What more do I have to do to get the bean(?) to register my new attribute? Any help or links to other answers is greatly appreciated.
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customerentity' available as request attribute
Here is my entity class
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.lang.NonNull;
#Entity
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NonNull
private String name;
#NonNull
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
// standard constructors / setters / getters / toString
}
The controller class
#Controller
public class UserController {
//set up a UserRepositoty variable
#Autowired
private UserRepository userRepository;
//create an UserRepository instance - instantiation (new) is done by Spring
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
//Mapping for the /index URL when initiated through Tomcat
#RequestMapping({"/index"})
public String showUserList(Model model) {
model.addAttribute("customers", userRepository.findAll());
return "index";
}
//Mapping for the /signup URL - calls the add-user HTML, to add a user
#RequestMapping({"/signup"})
public String showSignUpForm(Users user) {
return "add-user";
}
//Mapping for the /signup URL - to add a user
#RequestMapping({"/adduser"})
public String addUser(#Validated Users users, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-user";
}
userRepository.save(users);
return "redirect:/index";
}
//Mapping for the /edit/user URL to edit a user
#GetMapping("/edit/{id}")
public String showUpdateForm(#PathVariable("id") long id, Model model) {
Users user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
model.addAttribute("customer", user);
return "update-user";
}
//Mapping for the /update/id URL to update a user
#PostMapping("/update/{id}")
public String updateUser(#PathVariable("id") long id, #Validated Users user,
BindingResult result, Model model) {
if (result.hasErrors()) {
user.setId(id);
return "update-user";
}
userRepository.save(user);
return "redirect:/index";
}
//Mapping for the /delete/id URL to delete a user
#GetMapping("/delete/{id}")
public String deleteUser(#PathVariable("id") long id, Model model) {
Users user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
userRepository.delete(user);
return "redirect:/index";
}
}
The html documents
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Add User</title>
</head>
<body>
<form action="#" th:action="#{/adduser}" th:object="${users}" method="post">
<label for="name">Name</label>
<input type="text" th:field="*{name}" id="name" placeholder="Name">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
<label for="email">Email</label>
<input type="text" th:field="*{email}" id="email" placeholder="Email">
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
<input type="submit" value="Add User">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Add User</title>
</head>
<body>
<div th:switch="${users}">
<h2 th:case="null">No users yet!</h2>
<div th:case="*">
<h2>Users</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
<td><a th:href="#{/edit/{id}(id=${user.id})}">Edit</a></td>
<td><a th:href="#{/delete/{id}(id=${user.id})}">Delete</a></td>
</tr>
</tbody>
</table>
</div>
<p>Add a new user</p>
</div>
</body>
</html>
i'm new to spring-boot. In my system there are two models named subject,course(two databases with the same names and connected by the foreign key course_id).I need to make it possible to select course name in a dropdown list in the addSubject thymeleaf form. Can someone please tell me how to do this
Subject.DAO file
#Service
public class SubjectDAO {
#Autowired
SubjectRepository subjectRepository;
//to save a subject
public Subject save(Subject subject){
return subjectRepository.save(subject);
}
//to search all subjects
public List<Subject> findAll(){
return subjectRepository.findAll();
}
//get a subject by id
public Subject findById(Long id){
return subjectRepository.findById(id).orElse(null);
}
//delete a subject
public void delete(Long id){
subjectRepository.deleteById(id);
}
}
Course.DAO file
#Service
public class CourseDAO {
#Autowired
CourseRepository courseRepository;
//to save a course
public Course save(Course course){
return courseRepository.save(course);
}
//to search all courses
public List<Course> findAll(){
return courseRepository.findAll();
}
//get a course by id
public Course findById(Long id){
return courseRepository.findById(id).orElse(null);
}
//delete a course
public void delete(Long id){
courseRepository.deleteById(id);
}
}
Subject Controller
#Controller
public class SubjectController {
#Autowired
private SubjectDAO subjectDAO;
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
return "subject";
}
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
return "addSubject";
}
#RequestMapping(value="/subject/save",method= RequestMethod.POST)
public String saveCourse(#ModelAttribute("subject") Subject subject){
subjectDAO.save(subject);
return "redirect:/subject";
}
#RequestMapping("/subject/edit/{id}")
public ModelAndView updateSubjcet(#PathVariable(name="id")Long id){
ModelAndView mav=new ModelAndView(("updateSubject"));
Subject subject=subjectDAO.findById(id);
mav.addObject("subject",subject);
return mav;
}
#RequestMapping("/subject/delete/{id}")
public String deleteProduct(#PathVariable(name="id") Long id){
subjectDAO.delete(id);
return "redirect:/subject";
}
}
Subject html file
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Adding a Subject</title>
</head>
<body>
<div align="center">
<h1>Add a new Subject</h1>
<br/>
<form action="#" th:action="#{/subject/save}" th:object="${subject}" method="post">
<table border="0" cell[adding="10">
<tr>
<td>Subject code:</td>
<td><input type="text" th:field="*{course_code}" /></td>
</tr>
<tr>
<td>Subject Name:</td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>Course:</td>
<td>
<select>
<option value=""></option>
</select>
Z
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">Save</button></td>
</tr>
</table>
</form>
</div>
</body>
</html>
So you want to load Course combo inside subject html
You need to modify subject controller
#RequestMapping("/subject")
public String viewHomePage(Model model){
List<Subject> subjectDetails= subjectDAO.findAll();
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("subjectDetails",subjectDetails);
model.addAttribute("courses",courseDetail);
return "subject";
}
In HTML
<tr>
<td>Course:</td>
<td>
<select th:field="*{course_code}">
<option value="">Choose..</option>
<option th:each="course: ${courses}" th:value="${course.id}" th:text="${course.name}" />
</select>
</td>
</tr>
<tr>
Edit 1:
I think you are loading addSubject.html
In that case you need to modify addSubject controller
#RequestMapping("/subject/new")
public String addSubject(Model model){
Subject subject =new Subject();
model.addAttribute("subject",subject);
List<Course> courseDetail= courseDAO.findAll();
model.addAttribute("courses",courseDetail);
return "addSubject";
}
Edit 2:
As per your code in Git I can see
#Autowired
private SubjectDAO subjectDAO;
private CourseDAO courseDAO;
It should be
#Autowired
private SubjectDAO subjectDAO;
#Autowired
private CourseDAO courseDAO;
First add all courses to the ModelMap
model.addAttribute("cources",courseDao.findAll());
Then use th:each attribute to populate select options
<select th:field="*{course}">
<option value="">Choose..</option>
<option th:each="c: ${cources}" th:value="${c.id}" th:text="${c.name}" />
</select>
I am working on a spring mvc project. I have a view where I list all objects of type Person. The list is successfully displayed with all attributes. However, as I now need to pass the individual object back to the controller upon selection by the user, I have enclosed my list in form tag so that I could bind it with modelAttribute and send the object back to controller. When I try to include a form:hidden field to bind an attribute, I get the following error:
ERROR o.s.w.s.tags.form.HiddenInputTag - Invalid property 'uid' of bean class [java.util.ArrayList]: Bean property 'uid' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.springframework.beans.NotReadablePropertyException: Invalid property 'uid' of bean class [java.util.ArrayList]: Bean property 'uid' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
All setters and getters exist for the Person object and the attributes successfully get displayed if I don't include the form:hidden
Model:
public class Person {
Integer id;
String uid;
String fullname;
String firstname;
String lastname;
String fathername;
String email;
String status;
List<String> environments;
List<String> institutions;
public boolean isNew() {
return (this.id == null);
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFathername() {
return fathername;
}
public void setFathername(String fathername) {
this.fathername = fathername;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<String> getEnvironments() {
return environments;
}
public void setEnvironments(List<String> environments) {
this.environments = environments;
}
public List<String> getInstitutions() {
return institutions;
}
public void setInstitutions(List<String> institutions) {
this.institutions = institutions;
}
}
Controller:
#RequestMapping(value = "/persons/search", method = RequestMethod.POST)
public String listPersons(#RequestParam("searchString") String searchStr, Model model) {
logger.debug("listPersons()");
userService.initialize();
myPersons = userService.searchPersons(searchStr);
model.addAttribute("persons", myPersons);
return "users/listPersons";
}
View (listPersons.jsp)
<%# page session="false"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html lang="en">
<jsp:include page="../fragments/header.jsp" />
<body>
<div class="container">
<c:if test="${not empty msg}">
<div class="alert alert-${css} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>${msg}</strong>
</div>
</c:if>
<h1>All Persons</h1>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>UID</th>
<th>Full Name</th>
<th>Email</th>
<th>Institutions</th>
<th>Environments</th>
<th>Action</th>
</tr>
</thead>
<spring:url value="/persons/cards" var="showPersonCardsUrl" />
<form:form method="post" action="${showPersonCardsUrl}" modelAttribute="persons">
<c:forEach var="person" items="${persons}" varStatus="status">
<tr>
<td>
${person.id}
</td>
<td>${person.uid}</td>
<form:hidden path="uid" />
<td>${person.fullname}</td>
<td>${person.email}</td>
<td><c:forEach var="institution" items="${person.institutions}" varStatus="loop">
${institution}
<c:if test="${not loop.last}">,</c:if>
</c:forEach>
</td>
<td><c:forEach var="environment" items="${person.environments}" varStatus="loop">
${environment}
<c:if test="${not loop.last}">,</c:if>
</c:forEach>
</td>
<td>
<spring:url value="/persons/${person.uid}" var="showPersonUrl" />
<spring:url value="/persons/${person.uid}/delete" var="deletePersonUrl" />
<spring:url value="/persons/${person.uid}/update" var="updatePersonUrl" />
<spring:url value="/persons/${person.uid}/cards" var="showPersonCardsUrl" />
<button class="btn btn-info" onclick="location.href='${showPersonUrl}'">Query</button>
<button class="btn btn-primary" onclick="location.href='${updatePersonUrl}'">Update</button>
<button class="btn btn-danger" onclick="this.disabled=true;post('${deletePersonUrl}')">Delete</button>
<button class="btn btn-info" type="submit">Cards</button>
</td>
</tr>
</c:forEach>
</form:form>
</table>
</div>
<jsp:include page="../fragments/footer.jsp" />
</body>
</html>
Instead of
<form:hidden path="uid" />
I have also tried
<form:hidden path="persons.person.uid"/>
and also this
<form:hidden path="users[${status.index}].uid"/>
but nothing works. I need to pass the person object back to the controller with its uid so that I can do further processing. What could I be doing wrong in this?
The hidden form tag will try to resolve the path from withing the modelAttribute in the from tag it's inside, for example, your modelAttribute is persons, so the hidden form will try to access persons.uid
and if you use persons.person.uid it will resolve to persons.persons.person.uid
and so on.
In your case, I suggest using a regular input:
<input type="hidden" name="persons[${status.index}]" value="${person.uid}"/>
With this, when the form is submitted it will send an array named persons with uid values inside each.
If you still insist on using <form:hidden> then you need to revisit how you build your form.
I created a simple web application with SpringMVC and Hibernate. Everything works fine, my employees are added to database (using MySQL) but page don't show the list of them:
Also logger don't show any output message when I'm adding the object when it should show something like: "Employee add successfully, Employee details: ..."
Here's the page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<html>
<head>
<title>Employee Page</title>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-4eph{background-color:#f9f9f9}
</style>
</head>
<body>
<h1>
Add a Employee
</h1>
<c:url var="addAction" value="/employee/add" ></c:url>
<form:form action="${addAction}" commandName="employee">
<table>
<c:if test="${!empty employee.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty employee.name}">
<input type="submit"
value="<spring:message text="Edit Employee"/>" />
</c:if>
<c:if test="${empty employee.name}">
<input type="submit"
value="<spring:message text="Add Employee"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>List of Employees</h3>
<c:if test="${!empty listEmployees}">
<table class="tg">
<tr>
<th width="80">Employee ID</th>
<th width="120">Employee Name</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${listEmployee}" var="employee">
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td><a href="<c:url value='/edit/${employee.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${employee.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
#Qualifier(value = "employeeDAO")
public class EmployeeDAOImpl implements EmployeeDAO {
private static final Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addEmployee(Employee e) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(e);
logger.info("Employee saved successfully, Employee details: " + e);
}
#Override
public void updateEmployee(Employee e) {
Session session = this.sessionFactory.getCurrentSession();
session.update(e);
logger.info("Employee updated successfully, Employee details: " + e);
}
#SuppressWarnings("uncheked")
#Override
public List<Employee> listEmployee() {
Session session = this.sessionFactory.getCurrentSession();
List<Employee> employeeList = session.createQuery("FROM Employee").list();
for (Employee e: employeeList){
logger.info("Employee List::" + e);
}
return employeeList;
}
#Override
public Employee getEmployeeById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Employee e = (Employee) session.load(Employee.class, new Integer(id));
logger.info("Employee loaded successfully, Employee details: " + e);
return null;
}
#Override
public void removeEmployee(int id) {
Session session = this.sessionFactory.getCurrentSession();
Employee e = (Employee) session.load(Employee.class, new Integer(id));
if(e != null){
session.delete(e);
}
logger.info("Employee delete successfully, Employee details: " + e);
}
}
My Service class:
#Service
#Qualifier(value = "employeeService")
public class EmployeeServiceImpl implements EmployeeService{
public EmployeeServiceImpl() {
}
private EmployeeDAO employeeDAO;
public EmployeeServiceImpl(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
#Override
#Transactional
public void addEmployee(Employee e) {
this.employeeDAO.addEmployee(e);
}
#Override
#Transactional
public void updateEmployee(Employee e) {
this.employeeDAO.updateEmployee(e);
}
#Override
#Transactional
public List<Employee> listEmployee() {
return this.employeeDAO.listEmployee();
}
#Override
#Transactional
public Employee getEmployeeById(int id) {
return this.employeeDAO.getEmployeeById(id);
}
#Override
#Transactional
public void removeEmployee(int id) {
this.employeeDAO.removeEmployee(id);
}
public void setEmployeeDAO(EmployeeDAOImpl employeeDAO) {
this.employeeDAO = employeeDAO;
}
}
Here I create the mapping:
#Entity
#Table(name = "Employee")
public class Employee {
#Column(name = "Name")
private String name;
#Id
#Column(name = "Employee ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int employeeID;
public Employee(String name) {
this.name = name;
}
public Employee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int employeeID) {
this.employeeID = employeeID;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", employeeID=" + employeeID +
'}';
}
}
Controller class:
#Controller
public class EmployeeController {
private EmployeeService employeeService;
#Autowired(required = true)
#Qualifier("employeeService")
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
#RequestMapping(value = "/employee", method = RequestMethod.GET)
public String employeeList(Model model) {
model.addAttribute("employee", new Employee());
model.addAttribute("listEmployee", this.employeeService.listEmployee());
return "employee";
}
//For add and update person both
#RequestMapping(value = "/employee/add", method = RequestMethod.GET)
public String addEmployee(#ModelAttribute("person") Employee e){
if (e.getEmployeeID() == 0){
//new employee, add it
this.employeeService.addEmployee(e);
}else {
//existing employee, call update
this.employeeService.updateEmployee(e);
}
return "redirect:/employee";
}
#RequestMapping(value = "employees/remove/{id}")
public String removeEmployee(#PathVariable("id") int id){
this.employeeService.removeEmployee(id);
return "redirect:/employees";
}
#RequestMapping(value = "/employees/edit{id}")
public String editEmployee(#PathVariable("id") int id, Model model){
model.addAttribute("employee", this.employeeService.getEmployeeById(id));
model.addAttribute("listEmployees", this.employeeService.listEmployee());
return "employee";
}
}
In JSP Page your checking condition listEmployees , but in Controller You have added as model attribute listEmployee. remove last character s from listEmployees in Jsp. It should work. Otherwise everything is fine.
<c:if test="${!empty listEmployees}">
In Controller
model.addAttribute("listEmployee", this.employeeService.listEmployee());
change
<c:forEach items="${listEmployee}" var="employee">
to
<c:forEach items="${listEmployees}" var="employee">
I want to send data from form to PostgreSQL. When I send data by form, hibernate save (by save() method) blank record .. I did it manually (for test) without using form and then everything is ok.
Spitter.class (entity for user)
#Entity
#Table(name="spitter")
public class Spitter implements Serializable {
private static final long serialVersionUID = 829803238866007413L;
#Id
//#SequenceGenerator(name = "hibernate_sequence")
#GeneratedValue(strategy=GenerationType.AUTO) #Column(name="spitter_id")
private Long id;
#Column(unique=true) #Size(min=3, max=20) #Pattern(regexp = "^[a-zA-Z0-9]+$", message="Nie poprawna nazwa uzytkownika.")
private String username;
#Size(min=5, max=15, message="Haslo musi miec minimum 5 znakow.")
private String password;
#Size(min=3, max=25, message="Blad w imieniu i nazwisku.")
private String fullName;
#OneToMany(mappedBy="spitter")
private List<Spittle> spittles;
#Email(message="Nie poprawny adres email.")
private String email;
private boolean updateByEmail;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public List<Spittle> getSpittles() {
return spittles;
}
public void setSpittles(List<Spittle> spittles) {
this.spittles = spittles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setUpdateByEmail(boolean updateByEmail) {
this.updateByEmail = updateByEmail;
}
public boolean isUpdateByEmail() {
return updateByEmail;
}
#Override
public boolean equals(Object obj) {
Spitter other = (Spitter) obj;
return other.fullName.equals(fullName) && other.username.equals(username) && other.password.equals(password);
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
SpitterController.class
createSpitterProfile - shows form (edit.jsp) and sends model object (spitter) to form
addSpitterFromForm - receives binding data from form and save it to database and redirects to simply user profile
showSpitterProfile - there is of course null model object exception
#Controller
#RequestMapping("/spitters")
public class SpitterController {
private final SpitterService spitterService;
#Inject //#Autowired
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
//...
#RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
#RequestMapping(value="/{username}", method = RequestMethod.GET)
public String showSpitterProfile(#PathVariable String username, Model model) {
model.addAttribute(spitterService.getSpitter(username));
return "spitters/view";
}
edit.jsp (registration form for new user (Spitter))
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<div>
<h2>New account test</h2>
<sf:form method="POST" modelAttribute="spitter"
enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<th><sf:label path="fullName">Full name:</sf:label></th>
<td><sf:input path="fullName" size="15" /><br/>
<sf:errors path="fullName" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="username">Username:</sf:label></th>
<td><sf:input path="username" size="15" maxlength="15" />
<small id="username_msg">No spaces, please.</small><br/>
<sf:errors path="username" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="password">Password:</sf:label></th>
<td><sf:password path="password" size="30"
showPassword="true"/>
<small>6 characters or more (be tricky!)</small><br/>
<sf:errors path="password" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="email">Email Address:</sf:label></th>
<td><sf:input path="email" size="30"/>
<small>In case you forget something</small><br/>
<sf:errors path="email" cssClass="error" />
</td>
</tr>
<tr>
<th></th>
<td>
<sf:checkbox path="updateByEmail"/>
<sf:label path="updateByEmail">Send me email updates!</sf:label>
</td>
</tr>
<tr>
<th></th>
<td>
<input name="commit" type="submit"
value="I accept. Create my account." />
</td>
</tr>
</table>
</fieldset>
</sf:form>
</div>
and blank saved record to Postgres..
Try adding #modelattribute in this method .It fill fetch the required model object.
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(**#ModelAttribute("spitter")** #Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
and just to check if it is getting the values from form,syso some values like syso(spitter.getUserName) to check if values are coming.
ALso, I believe that you are making a constructor and passing service to it ,so there is no need of #Inject
#Inject //#Autowired///Why are you injecting it if it is a constructor?
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
You have enctype="multipart/form-data in your FORM,
Check that you have something like that in your App-servlet.xml:
<bean id="multipartResolver" class=
"org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxUploadSize="500000" />