How to update two tables by using spring boot? - spring

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

Related

How do validation with thymeleaf and bean validation?

I'm trying to perform a simple validation in my view, I know that the jsf it is very simple to do more in the spring mvc is giving me a headache ...
Can anyone help me with this validation? see what I'm doing wrong ??
my model
package br.com.nextinfo.multimedia.web.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
#Table
#Entity(name="slideshow")
public class SlideShow {
private Long condigo;
private String titulo;
private String subTitulo;
private ImagemSlider imagemSlider;
#Id
#GeneratedValue(generator="codigo",strategy=GenerationType.AUTO)
#SequenceGenerator(name = "codigo", sequenceName = "codigo_slideshow")
#Column(name = "CODIGO")
public Long getCondigo() {
return condigo;
}
#NotNull
#NotBlank
#Column(name = "TITULO" ,nullable = false)
public String getTitulo() {
return titulo;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name ="CODIGO_IMAGEM")
public ImagemSlider getImagemSlider() {
return imagemSlider;
}
#NotNull
#NotBlank
#Column(name = "SUBTITULO" ,nullable = false)
public String getSubTitulo() {
return subTitulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setSubTitulo(String subTitulo) {
this.subTitulo = subTitulo;
}
public void setImagemSlider(ImagemSlider imagemSlider) {
this.imagemSlider = imagemSlider;
}
public void setCondigo(Long condigo) {
this.condigo = condigo;
}
}
my controller
package br.com.nextinfo.multimedia.web.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.nextinfo.multimedia.web.model.ImagemSlider;
import br.com.nextinfo.multimedia.web.model.SlideShow;
import br.com.nextinfo.multimedia.web.services.AbstractFactoryService;
import br.com.nextinfo.multimedia.web.services.CreateSlideShowService;
import br.com.nextinfo.multimedia.web.services.ImagemServiceDatabase;
#Controller
#RequestMapping("/arquivosbanco/")
public class FilesDatabaseController implements AbstractControllerApp ,PadraoCrudMetodos<ImagemSlider> {
#Autowired
private ImagemServiceDatabase imagemService;
#Autowired
private CreateSlideShowService slideShowService;
#Override
public String getRequisicaoPadrao(Model model) {
List<ImagemSlider> lista = this.getAbstractService().realizaPaginacao("0", "10" ,null).getContent();
model.addAttribute("listaObjetoPageStart", lista);
model.addAttribute("img", new ImagemSlider());
return this.getUrlInicial();
}
#Override
public String getUrlInicial() {
return "arquivos/database/listarquivosbancodedados";
}
#ResponseBody
#RequestMapping(value = "/img", method = RequestMethod.GET)
public void showImage(#RequestParam("id") Long id, HttpServletResponse response,HttpServletRequest request) throws ServletException, IOException {
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
ImagemSlider imgdatabase = imagemService.getAbstractService().getBean(id);
if (imgdatabase!=null ) {
response.getOutputStream().write(imgdatabase.getImage());
response.getOutputStream().close();
}
}
#Override
public AbstractFactoryService<ImagemSlider> getAbstractService() {
return imagemService;
}
#RequestMapping(value = "/createslideshow/{imagemid}" ,method=RequestMethod.GET)
public String createslider(#PathVariable("imagemid") Long image,Model model){
final ImagemSlider img = this.imagemService.getBean(image);
model.addAttribute("imgslider", img);
model.addAttribute("slideshow", new SlideShow());
return "arquivos/createdisplay";
}
#RequestMapping(value = "/save" ,method=RequestMethod.POST)
public String saveSlideShowr( #RequestParam Long imagemid ,#Valid final SlideShow slideshow,final BindingResult result ,RedirectAttributes redirectAttrs){
ImagemSlider img = this.imagemService.getBean(imagemid);
if (result.hasErrors()) {
redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.strategy", result);
redirectAttrs.addFlashAttribute("slideshow", slideshow);
return "redirect:/arquivosbanco/createslideshow/"+imagemid;
}else{
this.slideShowService.salva(slideshow);
if (img != null) {
slideshow.setImagemSlider(img);
this.slideShowService.salva(slideshow);
}
}
return this.getUrlInicial();
}
}
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="/templates/layouts/principal">
<head>
<title>Criacao slideshow</title>
</head>
<body>
<div class="container-fluid" layout:fragment="corpopagina">
<h3 class="page-header text-center">Criacao slide show</h3>
<form id="registration-form" class="form-horizontal" th:object="${slideShow}" th:action="#{/arquivosbanco/save/?imagemid=}+${imgslider.codigo}" method="post">
<!-- Print all errors here!-->
<div class="col-md-4 col-xs-12">
<div class="thumbnail">
<img class="img-responsive" th:attr="src=#{'/upload/img?codigo='+${imgslider.codigo}}" width="400" height="400" />
<span class="text-center"></span>
</div>
<div class="caption">
<h5>Codigo <span th:text="${imgslider.codigo}" class="badge" style="margin-left:20px">5</span></h5>
<h5>Nome <span th:text="${imgslider.nome}" class="badge" style="margin-left:20px">5</span></h5>
</div>
</div>
<div class="col-md-8 col-xs-12">
<div class="form-group">
<label class="col-xs-3 control-label">Titulo principal</label>
<div class="col-md-8">
<input type="text" class="form-control" name="titulo" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Sub titulo</label>
<div class="col-md-8">
<input type="text" class="form-control input-xs" name="subTitulo" />
</div>
</div>
<div class="form-actions">
<label class="col-md-3 control-label"></label>
<div class="col-md-7">
<button type="submit" class="btn btn-success btn-large">Salvar</button>
</div>
<div class="col-md-1"></div>
</div>
</div>
</form>
</div>
</body>
in my controller is validating usually more in view does not show anything how can I solve?
I am quite some time on stackoverflow, most can not find the solution ...
Your view is not showing anything as you have not included the error messages in your template. Here is an example below.
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name Error</td>

Spring MVC : unable to display drop down

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

bind form to an object in SPRING 3.0

Hi I am following Passing parameters from JSP to Controller in Spring MVC obviously I am missing something because I am getting
javax.el.PropertyNotFoundException: Property 'Title' not found on type com.outbottle.hellospring.entities.Movie
Any Idea as to what I am missing?
my Controller:
package com.outbottle.hellospring.controllers;
import com.outbottle.hellospring.entities.Movie;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.bind.annotation.SessionAttributes;
#Controller
#SessionAttributes("Movie")
public class FormPractice{
//display the form
#RequestMapping(value="/form", method= RequestMethod.GET)
public String form(ModelMap map) {
map.addAttribute("Movie", new Movie());
//return new ModelAndView("form", "movie", new Movie());
return "form";
}
// Process the form
#RequestMapping(value="/showMovies", method = RequestMethod.POST)
public String processMovieRegistration(#ModelAttribute("Movie") Movie moviedata,
BindingResult result,
HttpServletRequest request,
Map<String, Object> map){
//System.out.print(moviedata.Title);
map.put("moviedata", moviedata);
//map.addAttribute("movie", moviedata);
map.put("date", request.getParameter("date"));
return "showMovies";
}
public Movie formBackingObject() {
return new Movie();
}
}
My Object
package com.outbottle.hellospring.entities;
import java.util.Date;
public class Movie {
private String Title;
private Date ReleaseDate;
/**
* #return the ReleaseDate
*/
public Date getReleaseDate() {
return ReleaseDate;
}
/**
* #param ReleaseDate the ReleaseDate to set
*/
public void setReleaseDate(Date ReleaseDate) {
this.ReleaseDate = ReleaseDate;
}
/**
* #return the Title
*/
public String getTitle() {
return Title;
}
/**
* #param Title the Title to set
*/
public void setTitle(String Title) {
this.Title = Title;
}
}
The form
<form:form method="post" action="showMovies" modelAttribute="Movie" commandName="Movie">
<table>
<tr>
<td>Title</td>
<td><form:input path="Title" /></td>
</tr>
<tr>
<td>Date</td>
<!--Notice, this is normal html tag, will not be bound to an object -->
<td><input name="date" type="text"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="send"/>
</td>
</tr>
</table>
</form:form>
The view:
<body>
<h3>Here are the list</h3>
<c:choose>
<c:when test="${not empty moviedata.Title}">
<b>${moviedata.Title}</b>
</c:when>
<c:otherwise>
<b>No Movie yet.</b>
</c:otherwise>
</c:choose>
<br />
<br />
<c:choose>
<c:when test="${not empty date}">
<b>${date}</b>
</c:when>
<c:otherwise>
<b>still nothing.</b>
</c:otherwise>
</c:choose>
</body>
Have no idea why but removing the capital "T" in Title worked..
<body>
<h3>Here are the list</h3>
<c:choose>
<c:when test="${not empty moviedata.title}">
<b>${moviedata.title}</b>
</c:when>
<c:otherwise>
<b>No Movie yet.</b>
</c:otherwise>
</c:choose>
if anyone can explain why this works it would help me understand SPRING 3.0 faster.. but for now I am just glad I can move on..

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