Spring MVC : unable to display drop down - spring

I am not getting the drop down value in Profession. Actually I am getting exception
javax.servlet.ServletException: Type [java.lang.String] is not valid for option items
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspService(org.apache.jsp.WEB_002dINF.views.Registration_jsp:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
root cause
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:142)
org.springframework.web.servlet.tags.form.SelectTag.writeTagContent(SelectTag.java:223)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_select_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:283)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_form_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:144)
I understand something wrong with select tag .
please help
RegisterController
package net.codejava.spring.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.codejava.spring.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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;
#Controller
#RequestMapping(value = "/register")
public class RegisterController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView initForm() {
User user = new User();
user.setUsername("Anukul");
ModelAndView mav = new ModelAndView("Registration");
//=== default user name======
//model.addAttribute("userNameDefault", "Enter Name");
mav.addObject("userNameDefault", "Enter Name");
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
mav.addObject("user",user);
//==== user added to model =========
return mav;
}
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
}
Registration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/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=UTF-8">
<title>Registration</title>
</head>
<body>
<div align="center">
<h1>reached here</h1>
<form:form action="register" method="POST" commandName="user">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Birthday (mm/dd/yyyy):</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${ProffesionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
User.java
package net.codejava.spring.model;
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
}
----------------

does this works for you
<form:select id="profession" path="profession">
<form:options items="${ProffesionList}"/>
</form:select>
or try with this
<form:select id="profession" path="profession">
<c:forEach var="prof" items="${ProffesionList}">
<form:option value="${prof.key}" label="${prof.value}" />
</c:forEach>
</form:select>
Controller
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
or add #ModelATtribute
#ModelAttribute("ProffesionList")
public Map<String,String> getProfessions(){
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
return profDropDown;
}

Related

How to update two tables by using spring boot?

DemoModel
package com.example.demo.model;
import java.util.Date;
import javax.persistence.CascadeType;
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.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
#Entity(name="demomodel")
public class DemoModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotNull
#Size(min=3, max=20)
private String fname;
private String lname;
#Min(message="Age should be 18 atleast ",value=18)
private Integer age;
#Pattern(message = "Invalid email id",regexp = "^[A-Za-z0-9+_.-]+#(.+)$")
private String email;
private String course;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private Date dob;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="add_id")
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address
package com.example.demo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotNull
#Size(min=2, max=30)
private String city;
private String state;
//#OneToOne(mappedBy="address",cascade = CascadeType.ALL)
//#JoinColumn(name="id")
#OneToOne(mappedBy="address")
private DemoModel demo;
public DemoModel getDemo() {
return demo;
}
public void setDemo(DemoModel demo) {
this.demo = demo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
DemoController
package com.example.demo.controller;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.demo.model.Address;
import com.example.demo.model.DemoModel;
import com.example.demo.repository.AddressRepo;
import com.example.demo.repository.DemoRepo;
import com.example.demo.service.DemoService;
//#RestController
#Controller
public class DemoController {
private static final Logger logger = LoggerFactory.getLogger(DemoController.class);
#Autowired
DemoRepo demoRepo;
#Autowired
AddressRepo addRepo;
#Autowired
DemoService demoService;
#RequestMapping(value="/", method=RequestMethod.GET)
public String demoApp(DemoModel demoModel,Address address) {
return "home";
}
#RequestMapping(value="/formsubmit",method=RequestMethod.POST)
public String demoForm(#Valid DemoModel demoModel,BindingResult result, #Valid Address address,BindingResult res) {
if(result.hasErrors()) {
logger.warn("in first binding");
return "home";
}
else if(res.hasErrors()) {
logger.warn("in second binding");
return "home";
}
else
{
demoModel.setAddress(address);
demoRepo.save(demoModel);
//addRepo.save(address);
//mv.addObject("demoModel", demoModel);
//addRepo.save(address);
//mv.setViewName("redirect:/dashboard");
return "redirect:/dashboard";
}
}
#RequestMapping(value="/dashboard",method=RequestMethod.GET)
public String dashform(Model model){
model.addAttribute("demoModel", demoService.dashform());
return "dashboard";
}
#RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
public String delete(#PathVariable("id") int id) {
demoRepo.deleteById(id);
return "redirect:/dashboard";
}
#RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
public String edit(#PathVariable("id") int id,ModelMap modelMap,DemoModel demoModel,Address address) {
modelMap.put("demoModel", demoService.find(id));
return "edit";
}
#RequestMapping(value = "edit", method = RequestMethod.POST)
public String edit(#ModelAttribute("demoModel") DemoModel demoModel,#ModelAttribute("address") Address address,ModelMap modelMap) {
DemoModel dm=demoService.find(demoModel.getId());
dm.setFname(demoModel.getFname());
dm.setLname(demoModel.getLname());
dm.setCourse(demoModel.getCourse());
dm.setEmail(demoModel.getEmail());
dm.setAge(demoModel.getAge());
dm.setDob(demoModel.getDob());
//dm.setAddress(address);
demoRepo.save(dm);
return "edit";
}
}
DemoRepository
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.DemoModel;
public interface DemoRepo extends CrudRepository<DemoModel, Integer> {
}
AddressRepository
package com.example.demo.repository;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.Address;
public interface AddressRepo extends CrudRepository<Address, Integer> {
}
DemoService
package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.model.DemoModel;
import com.example.demo.repository.DemoRepo;
#Service
public class DemoService{
#Autowired
DemoRepo demoRepo;
private List<DemoModel> demoModels;
public List <DemoModel> dashform(){
demoModels=new ArrayList<DemoModel>();
for(DemoModel demoModel:demoRepo.findAll() ) {
demoModels.add(demoModel);
}
return demoModels;
}
public DemoModel find(int id) {
// TODO Auto-generated method stub
return demoRepo.findById(id).orElse(null);
}
}
edit.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><!--
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/source/styles.css" /> -->
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Data Received</h1>
<form action="#" th:action="#{/edit}" method="post">
<div th:object="${demoModel}" >
<table th:each="demoModel: ${demoModel}">
<tr>
<td>Id:</td>
<td><input type="text" th:field="*{id}" th:placeholder="#{demoModel.id}"/></td>
<!-- <td th:if="${#fields.hasErrors('fname')}" th:errors="*{fname}">first
name Error</td> -->
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" th:field="*{fname}" th:placeholder="#{demoModel.fname}"/></td>
<!-- <td th:if="${#fields.hasErrors('fname')}" th:errors="*{fname}">first
name Error</td> -->
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" th:field="*{lname}" th:placeholder="#{demoModel.lname}"/></td>
<!-- <td th:if="${#fields.hasErrors('lname')}" th:errors="*{lname}">Last
name Error</td> -->
</tr>
<tr>
<td>Email:</td>
<td><input type="text" th:field="*{email}" th:placeholder="#{demoModel.email}"/></td>
<!-- <td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email
Error</td> -->
</tr>
<tr>
<td>Course:</td>
<td><input type="text" th:field="*{course}" th:placeholder="#{demoModel.course}"/></td>
<!-- <td th:if="${#fields.hasErrors('course')}" th:errors="*{course}">course
Error</td> -->
</tr>
<tr>
<td>DOB:</td>
<td><input type="date" th:field="*{dob}" th:placeholder="#{demoModel.dob}"/></td>
<!-- <td th:if="${#fields.hasErrors('dob')}" th:errors="*{dob}">age
Error</td> -->
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" th:placeholder="#{demoModel.age}"/></td>
<!-- <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">age
Error</td> -->
</tr>
</table>
</div>
<div th:object="${address}">
<table th:each="demoModel: ${demoModel}">
<tr>
<td>State:</td>
<td><input type="text" th:field="*{state}" th:placeholder="#{demoModel.address.state}"/></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" th:field="*{city}" th:placeholder="#{demoModel.address.city}"/></td>
</tr>
</table>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
dashboard.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<link rel="stylesheet" href="/source/styles.css" /><!--
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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.3.7/js/bootstrap.min.js"></script> -->
</head>
<body>
<h1>Data Received</h1>
<table>
<tr >
<th rowspan=2>Id</th>
<th rowspan=2>First Name</th>
<th rowspan=2>Last Name</th>
<th rowspan=2>Email</th>
<th rowspan=2>Age</th>
<th rowspan=2>Date of Birth</th>
<th rowspan=2>Course</th>
<th colspan=2>Address</th>
<th rowspan=2>Action</th>
</tr>
<tr>
<th>City</th>
<th>State</th>
</tr>
<tr th:each="demoModel: ${demoModel}">
<td th:text="${demoModel.id}">Id</td>
<td th:text="${demoModel.fname}">First Name</td>
<td th:text="${demoModel.lname}">Last Name</td>
<td th:text="${demoModel.email}">Email</td>
<td th:text="${demoModel.age}">Age</td>
<td th:text="${demoModel.dob}">DOB</td>
<td th:text="${demoModel.course}">Course</td>
<td th:text="${demoModel.address.city}">City</td>
<td th:text="${demoModel.address.state}">State</td>
<td> <a class="btn" th:href="#{/delete/{id}/(id=${demoModel.id})}"> <span class="glyphicon glyphicon-trash"></span> </a>
<a class="btn" th:href="#{/edit/{id}/(id=${demoModel.id})}"> <span class="glyphicon glyphicon-edit"></span> </a>
</td>
</tr>
</table>
<h2> Go to form </h2>
</body>
Dashboard
Edit
So, the question is how to update two tables? When I click on edit then it is redirected to the edit page where I see the details of demoModel object but the details of address object is not displayed. I don't know whether this issue prevent me to update both the tables or there is another problem in controller for updating data.
While I access the edit page without the intention of updating the details of both the tables demoModel and address is being fetched efficiently for a particular ID.
My Intention of Updating both the table is failed here.
Please, experts go through all the codes above and suggest me a better solution how can I update both the OneToOne mapped table.
You don't see address because it's not loaded.
modelMap.put("demoModel", demoService.find(id));
Here you are passing only DemoModel and you need also to load Address. In Your DemoModel should define
#OneToOne(mappedBy="address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name="add_id")
private Address address;
Now also in your edit Address object should be present

Required String parameter 'username' is not present when trying to set session attribute

I'm trying to set username as Http session attribute when user loging in but it gives me an error
Required String parameter 'username' is not present
This is my controller class, getLoginForm method. Here I'm trying to get username string from input and puting it to httpSession (because i will need this username to use in other requests).
package com.vandh.app.controller;
import javax.servlet.http.HttpSession;
#Controller
#SessionAttributes("username")
public class LoginController {
#RequestMapping(value = { "/", "/home" })
public String getUserDefault() {
return "home";
}
#RequestMapping("/login")
public ModelAndView getLoginForm(#ModelAttribute Users users,
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout,
#RequestParam(value="username") String username,
HttpSession httpSession) {
String message = "";
if (error != null) {
message = "Incorrect username or password !";
} else if (logout != null) {
message = "Logout successful !";
}
else
if(error==null)
{
httpSession.setAttribute("username", username);
}
return new ModelAndView("login", "message", message);
}
#RequestMapping("/admin**")
public String getAdminProfile() {
return "admin";
}
#RequestMapping("/403")
public ModelAndView getAccessDenied() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
String username = "";
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
username = userDetail.getUsername();
}
return new ModelAndView("403", "username", username);
}
}
Here is my DAO class of finding users in DB (MySQL)
#Repository("loginDao")
public class LoginDaoImpl implements LoginDao {
#Autowired
SessionFactory sessionFactory;
//public String userLogIn; // checking username in auth. process
Session session = null;
Transaction tx = null;
#Override
public Users findByUserName(String username ) {
String login = username;
session = sessionFactory.openSession();
tx = session.getTransaction();
session.beginTransaction();
Users user = (Users) session.load(Users.class, new String(username));
tx.commit();
return user;
}
}
And this is my login.jsp page
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login </title>
</head>
<body>
<br /> <br /> <br />
<div style="border: 1px solid black; width: 300px; padding-top: 10px;">
<br /> Please enter your username and password to login ! <br /> <span
style="color: red">${message}</span> <br />
<form:form method="post" action="j_spring_security_check"
modelAttribute="users">
<table>
<tr>
<td>Username:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:input path="password" type="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" /></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>

LocalDate in Spring form

This is my Entity
#Entity
public class User implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String mobNum;
private String email;
String gender;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
LocalDate bdate;
public LocalDate getDate() {
return bdate;
}
public void setDate(LocalDate bdate) {
this.bdate = bdate;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public User() {
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMobNum() {
return this.mobNum;
}
public void setMobNum(String mobNum) {
this.mobNum = mobNum;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
and here is my Spring-Form
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form:form action="add_student_data.htm" method="POST" commandName="user">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
<td><font color="red" /><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="bdate" >Date Of Birth</form:label></td>
<td><form:input path="bdate"/></td>
<td><font color="red" /><form:errors path="bdate" cssClass="bdate" /></td>
</tr>
<tr>
<td><form:label path="gender" >Gender</form:label></td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td><form:label path="mobNum">Mob Num</form:label></td>
<td><form:input path="mobNum"/></td>
<td><font color="red" /><form:errors path="mobNum" ccssClass="error"/></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email"/></td>
<td><font color="red" /><form:errors path="email" cssClass="error" /></td>
</tr>
</table>
<input type="submit" value="submit">
</form:form>
</body>
</html>
when i want to open this fom error is occured like
"org.apache.jasper.JasperException: org.springframework.beans.NotReadablePropertyException: Invalid property 'dateOfBirth' of bean class [com.domain.User]: Bean property 'dateOfBirth' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?"
I am using joda.org.time.LocalDate in User entity.What is the cause of the problem?
Your getter/setter method name and variable name in JSP do not match, change the following methods from:
public LocalDate getDate() {
return bdate;
}
public void setDate(LocalDate bdate) {
this.bdate = bdate;
}
to
public LocalDate getBdate() {
return bdate;
}
public void setBdate(LocalDate bdate) {
this.bdate = bdate;
}

customizing date format using spring

i m encountering the date problem in UI using spring , when i fetch query from database the data format is shown in my UI is 1987-02-12 00:00:00.0 when i submit the values null is going in database . I have used the
return getJdbcTemplate().update(
QUERY_CREATE_PROJECT,
new Object[] { employeeProject.getEmployeeNumber(),
employeeProject.getProjectCode(),
employeeProject.getStartDate(),
employeeProject.getEndDate(),
employeeProject.getProjectRole() }) != 0 ? true : false;
} method of spring , my reqiurement is to show date in format (dd/MM/yyyy) and insert the date in same format .How to convert the format of date in our custom date plz help me and also tell me where to use customization of date , should i customize date in controller layer ,DAO layer or in service layer
my controller method of creating is
package com.nousinfo.tutorial.controllers;
import java.util.Map;
import javax.validation.Valid;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.nousinfo.tutorial.model.ProjectForm;
import com.nousinfo.tutorial.service.impl.ProjectServiceImpl;
import com.nousinfo.tutorial.service.model.EmployeeProjectBO;
/**
*
* #author ankurj
*
*/
#Controller
#RequestMapping("projectController")
public class ProjectController {
private ProjectServiceImpl projectServiceImpl;
public ProjectServiceImpl getProjectServiceImpl() {
return projectServiceImpl;
}
public void setProjectServiceImpl(ProjectServiceImpl projectServiceImpl) {
this.projectServiceImpl = projectServiceImpl;
}
/**
* Used to set the view
* #param id
* #return
* #throws Exception
*/
#RequestMapping(value = "/projectForm", method = RequestMethod.GET)
public ModelAndView view(#RequestParam("id") int id) throws Exception {
ModelAndView modelAndView = new ModelAndView();
System.out.println(id);
ProjectForm projectForm = new ProjectForm();
projectForm.setEmployeeNumber(id);
modelAndView.addObject("projectForm", projectForm);
modelAndView.setViewName("projectForm");
return modelAndView;
}
/**
* Create the project for an employee
* #param projectForm
* #param bindingResult
* #param model
* #return
* #throws Exception
*/
#RequestMapping(value = "/createProject", method = RequestMethod.POST)
public String createEmployee(#Valid ProjectForm projectForm,
BindingResult bindingResult, Map<String, ProjectForm> model)
throws Exception {
String form = null;
if (bindingResult.hasErrors()) {
return "projectForm";
}
model.put("projectForm", projectForm);
projectForm.setUpdateStatus("A");
if (projectForm.getUpdateStatus().charAt(0) == 'A') {
boolean flag = projectServiceImpl
.actionDecider(convertprojectFormToprojectBO(projectForm));
if (flag == false)
form = "DBError";
else
form = "Success";
}
return form;
}
/**
* This method update the existing detail of project
* #param projectForm
* #param bindingResult
* #return
*/
#RequestMapping(value = "/updateProject", method = RequestMethod.POST)
public String updateDepartment(
#ModelAttribute("projectForm") ProjectForm projectForm,
BindingResult bindingResult) {
String form = null;
projectForm.setUpdateStatus("M");
if (projectForm.getUpdateStatus().charAt(0) == 'M') {
boolean flag = projectServiceImpl
.actionDecider(convertprojectFormToprojectBO(projectForm));
if (flag == false)
form = "DBError";
else
form = "Success";
}
return form;
}
and this is my model class
package com.nousinfo.tutorial.model;
import java.util.Date;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.NumberFormat;
public class ProjectForm {
#NotNull
#NumberFormat
#Min(1)
private Integer employeeNumber;
#NotEmpty(message = "project code can't be blank")
private String projectCode;
private Date startDate;
private Date endDate;
private String role;
private String updateStatus;
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Integer getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(Integer employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getUpdateStatus() {
return updateStatus;
}
public void setUpdateStatus(String updateStatus) {
this.updateStatus = updateStatus;
}
}
this is my jsp for date
<%# 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://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!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></title>
<script>
function actionChange(url) {
if (url == 'Save') {
document.form.action = "/EmployeeWebSpring/projectController/updateProject";
}
if (url == 'Delete') {
document.form.action = "/EmployeeWebSpring/projectController/deleteProject";
}
}
function home() {
window.location.href = "/EmployeeWebSpring/search/searchspring";
}
</script>
</head>
<body background="../images/flower.jpg">
<img src="../images/Header.png" width="1500"/>
<hr width="1500">
<form:form name='form' commandName="projectForm">
<fmt:message key="project.searchResult.header" />
<c:choose>
<c:when test="${empty requestScope.projectBO}">
<fmt:message key="searchResult.noresult" />
</c:when>
<c:otherwise>
<table align="center">
<form:hidden path="updateStatus" />
<tr align="center">
<th><fmt:message key="employeeNumber" /></th>
<td><form:input path="employeeNumber"
value="${requestScope.projectBO.employeeNumber}" /></td>
</tr>
<tr align="center">
<th><fmt:message key="projectCode" /></th>
<td><form:input path="projectCode"
value="${requestScope.projectBO.projectCode}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="startDate" /></th>
<td><form:input path="startDate"
value="${requestScope.projectBO.startDate}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="endDate" /></th>
<td><form:input path="endDate"
value="${requestScope.projectBO.endDate}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="role" /></th>
<td><form:input path="role"
value="${requestScope.projectBO.role}" /></td>
</tr>
</table>
<br>
<center>
<table>
<tr>
<td><input type="submit" name="method" value="Save"
onclick="actionChange(this.value)" /></td>
<td><input type="submit" name="method" value="Delete"
onclick="actionChange(this.value)" /></td>
<td><input type="button" onclick="home" value="Cancel" /></td>
</tr>
</table>
</center>
</c:otherwise>
</c:choose>
<br />
<fmt:message key="searchResult.searchAgain" />
<a href="/EmployeeWebSpring/search/searchspring"> <fmt:message
key="searchResult.click" />
</a>
</form:form>
</body>
</html>
All you need is the custom editor for Date type, through which you can format the incoming & outgoing date object.This was already explained in the post
Spring MVC - Binding a Date Field

spring form controller with html checkbox

I am trying to bind the input type checkbox using spring form controller,But i failed .
Here i am posting Controller,bean and jsp example,One more thing is i can't use
.
Below is the code:
Controller:
package com.test.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;
#SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {
private UserService userService;
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
user.setCommunity(user.getCommunity());
userService.add(user);
return new ModelAndView("userForm","user",user);
}
}
jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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>Registration Page</title>
<script>
function submitForm(){
document.testForm.submit();
}
</script>
</head>
<body>
<form:form method="POST" commandName="user" name="testForm" action="./userRegistration.htm">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="1" label="India" />
<form:option value="2" label="USA" />
<form:option value="3" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><input type="checkbox" name="community" value="Hibernate"/>Hibernate</br>
<input type="checkbox" name="community" value="test"/>test</br>
<input type="checkbox" name="community" value="test1"/>test1</br>
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" onclick="submitForm();"></td>
</tr>
</table>
</form:form>
</body>
</html>
Java beans:
package com.test.domain;
public class User {
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
I tried different ways,but no luck.Any hints please.
the browser will not send the field in the request if the checkbox isn't checked. the value will either be "true" or not sent. you will never get a "false" value.
add a hidden field with _name for every checkbox
EX:
<input type="checkbox" name="community" value="Hibernate"/>
<input type="hidden" name="_community" value="on"/>
Then, spring will take care of it.
If you do not use the form tag it will not automaticly bind your checkboxes. If you use plain html you have to bind the your self.
You can solve this by adding a list of community objects and then use form:checkboxes.
For example:
<form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
I would also recomend you to use a HashMap when using ModelAndView like this:
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
model.put("communityList", communityList);
return new ModelAndView("userFormat", model);
Manually bind using 'ServletRequestUtils'... http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/ServletRequestUtils.html
Example
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
Long subscriptionOwnerId = ServletRequestUtils.getLongParameter(request, "id");
return new ModelAndView('test'); }`

Resources