Cant get view of the form in thymeleaf after put to it list of object - spring

I have a big problem to solve and I don`t see the sollution of this, because IntelliJ not given me any log. Here is the point:
When I try to open the page with form where I put data od employee and address, address form is invisible.
My code:
View:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Dodaj nową firmę</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" th:href="#{/webjars/bootstrap/4.4.1-1/css/bootstrap.min.css}" />
<script th:src="#{/webjars/jquery/3.5.1/jquery.min.js}"></script>
<script th:src="#{/webjars/bootstrap/4.4.1-1/js/bootstrap.min.js}"></script>
</head>
<body>
<div style = "text-align: center;">
<h1>Dodaj nowego pracownika do bazy danych</h1>
</div>
<form class="form-horizontal" th:object="${employee}" th:action="#{/employees}" th:method="post">
<div class="container" style="margin-top:10mm;">
<div class="row">
<div class="col-sm">
<div style = "text-align: center;">
<h5>Dane osobowe</h5>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{name}"/>
<label class="control-label">Imię</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('name')}" th:errors="*{name}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{surname}"/>
<label class="control-label">Nazwisko</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('surname')}" th:errors="*{surname}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{position}"/>
<label class="control-label">Stanowisko</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('position')}" th:errors="*{position}"/></div>
</div>
<div class="form-group">
<input type="number" class="form-control" th:field="*{age}"/>
<label class="control-label">Wiek</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('age')}" th:errors="*{age}"/></div>
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{nationality}"/>
<label class="control-label">Obywatelstwo</label>
<div class="text-danger"><p th:if="${#fields.hasErrors('nationality')}" th:errors="*{nationality}"/></div>
</div>
</div>
<div class="col-sm">
<div th:object="${listAddress}">
<div style = "text-align: center;">
<h5>Dane adresowe</h5>
</div>
<div style = "text-align: center;">
<h6>Adres stały</h6>
</div>
<div th:each="row, stat : ${listAddress.addresses}">
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].type}"/>
<label class="control-label">Typ adresu</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('type')}" th:errors="*{type}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].street}"/>
<label class="control-label">Ulica</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('street')}" th:errors="*{street}"/></div>-->
</div>
<div class="form-group">
<input type="number" class="form-control" th:field="*{addresses[__${stat.index}__].streetNr}"/>
<label class="control-label">Numer domu</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('streetNr')}" th:errors="*{streetNr}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].flatNr}"/>
<label class="control-label">Numer mieszkania</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('flatNr')}" th:errors="*{flatNr}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].postalCode}"/>
<label class="control-label">Kod pocztowy</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('postalCode')}" th:errors="*{postalCode}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].city}"/>
<label class="control-label">Miasto</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('city')}" th:errors="*{city}"/></div>-->
</div>
<div class="form-group">
<input type="text" class="form-control" th:field="*{addresses[__${stat.index}__].country}"/>
<label class="control-label">Kraj</label>
<!-- <div class="text-danger"><p th:if="${#fields.hasErrors('country')}" th:errors="*{country}"/></div>-->
</div>
</div>
</div>
<div style = "text-align: right;">
<button type="submit" class="btn btn-primary btn-lg active center-block">ZAPISZ</button>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Controller:
#RequestMapping("/new")
public String addNewEmployee(Model model) {
AddressesList listOfAddress = new AddressesList();
ArrayList<Address> addressesArray = new ArrayList<>();
listOfAddress.setAddresses(addressesArray);
model.addAttribute("employee", new Employee()).addAttribute("listAddress", listOfAddress);
return "new_employee_form";
}
AddressList class
public class AddressesList {
private List<Address> addresses;
public AddressesList() {
}
public AddressesList(List<Address> addresses) {
this.addresses = addresses;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
}
Address class
public class Address {
public Long idAddress;
public Long idEmployee;
public String type;
public String street;
public String streetNr;
public Integer flatNr;
public String postalCode;
public String city;
public String country;
public Address() {
}
private Address(Long idEmployee, String type, String street, Integer flatNr, String streetNr, String postalCode, String city, String country) {
this.idEmployee = idEmployee;
this.type = type;
this.street = street;
this.streetNr = streetNr;
this.flatNr = flatNr;
this.postalCode = postalCode;
this.city = city;
this.country = country;
}
public static class AddressBuilder{
private Long idAddress;
private Long idEmployee;
private String type;
private String street;
private String streetNumber;
private Integer flatNr;
private String postalCode;
private String city;
private String country;
public AddressBuilder setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
return this;
}
public AddressBuilder setType(String type) {
this.type = type;
return this;
}
public AddressBuilder setStreet(String street) {
this.street = street;
return this;
}
public AddressBuilder setFlatNr(Integer flatNr) {
this.flatNr = flatNr;
return this;
}
public AddressBuilder setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
return this;
}
public AddressBuilder setPostalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
public AddressBuilder setCity(String city) {
this.city = city;
return this;
}
public AddressBuilder setCountry(String country) {
this.country = country;
return this;
}
public Address build(){
return new Address(idEmployee, type, street, flatNr, streetNumber, postalCode, city, country);
}
}
public void setIdAddress(Long idAddress) {
this.idAddress = idAddress;
}
public void setIdEmployee(Long idEmployee) {
this.idEmployee = idEmployee;
}
public void setType(String type) {
this.type = type;
}
public void setStreet(String street) {
this.street = street;
}
public void setFlatNr(Integer flatNr) {
this.flatNr = flatNr;
}
public void setStreetNr(String streetNr) {
this.streetNr = streetNr;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setCity(String city) {
this.city = city;
}
public void setCountry(String country) {
this.country = country;
}
public Long getIdAddress() {
return idAddress;
}
public Long getIdEmployee() {
return idEmployee;
}
public String getType() {
return type;
}
public String getStreet() {
return street;
}
public Integer getFlatNr() {
return flatNr;
}
public String getStreetNr() {
return streetNr;
}
public String getPostalCode() {
return postalCode;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
#Override
public String toString() {
return "Address{" +
"idAddress=" + idAddress +
", idEmployee=" + idEmployee +
", type='" + type + '\'' +
", street='" + street + '\'' +
", flattNr=" + flatNr +
", streetNumber='" + streetNr + '\'' +
", postalCode='" + postalCode + '\'' +
", city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}
}
I get the page like this with no errors
with no address form on the right side od page.
Please help to solve this problem.

You are adding an empty list of addresses to your backing object:
ArrayList<Address> addressesArray = new ArrayList<>();
listOfAddress.setAddresses(addressesArray);
If you want the form to show up, you need to add at least one address so it has something to loop over.
ArrayList<Address> addressesArray = new ArrayList<>();
addressesArray.add(new Address());
listOfAddress.setAddresses(addressesArray);

I think I do this wrong.
When I add index to ArrayList form showed up.
#RequestMapping("/new")
public String addNewEmployee(Model model) {
AddressesList listOfAddress = new AddressesList();
ArrayList<Address> addressesArray = new ArrayList<Address>(2);
addressesArray.add(0, new Address());
addressesArray.add(1, new Address());
listOfAddress.setAddresses(addressesArray);
model.addAttribute("employee", new Employee()).addAttribute("listAddress", listOfAddress);
return "new_employee_form";
}
I want to enter a permanent and correspondence address in the form, accept the form (POST) and save it to class objects. How to do it?

Related

How to make Search data using Spring boot

i am a beginner of spring boot framework.i want to work with search records using spring boot application. my index.html is loaded successfully when i enter the employee id on the employee id textbox and click search button relevant employee name result want to display the below textbox.but i don't know how to pass it .what i tired so so i attached below.
index.html
<form action="#" th:action="#{/search}" th:object="${employee}" method="post">
<div alight="left">
<tr>
<label class="form-label" >Employee ID</label>
<td>
<input type="hidden" th:field="*{id}" />
<input type="text" th:field="*{id}" class="form-control" placeholder="Employee ID" />
</td>
</tr>
</div>
<br>
<tr>
<td colspan="2"><button type="submit" class="btn btn-info">Search</button> </td>
</tr>
<div alight="left">
<tr>
<label class="form-label" >Employee Name</label>
<td>
<input type="text" th:field="*{ename}" class="form-control" placeholder="Employee Name" />
</td>
</tr>
</div>
</form>
Controller
#Controller
public class EmployeeController {
#Autowired
private EmployeeService service;
#GetMapping("/")
public String add(Model model) {
List<Employee> listemployee = service.listAll();
// model.addAttribute("listemployee", listemployee);
model.addAttribute("employee", new Employee());
return "index";
}
#RequestMapping("/search/{id}")
public ModelAndView showSearchEmployeePage(#PathVariable(name = "id") int id) {
ModelAndView mav = new ModelAndView("new");
Employee emp = service.get(id);
mav.addObject("employee", emp);
return mav;
}
}
Entity
#Entity
public class Employee {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String ename;
private int mobile;
private int salary;
public Employee() {
}
public Employee(Long id, String ename, int mobile, int salary) {
this.id = id;
this.ename = ename;
this.mobile = mobile;
this.salary = salary;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getMobile() {
return mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [id=" + id + ", ename=" + ename + ", mobile=" + mobile + ", salary=" + salary + "]";
}
Repository
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
It is easiest to create a dedicated form data object:
public class EmployeeSearchFormData {
private long employeeId;
// getter and setter
}
In the controller:
#Controller
public class EmployeeController {
#Autowired
private EmployeeService service;
#GetMapping("/")
public String add(Model model) {
model.addAttribute("employeeSearchFormData", new EmployeeSearchFormData());
return "index";
}
#PostMapping("/search")
public String doSearchEmployee(#ModelAttribute("employeeSearchFormData") EmployeeSearchFormData formData, Model model) {
Employee emp = service.get(formData.getEmployeeId());
model.addAttribute("employee", emp);
return "index";
}
}
Thymeleaf template:
<form action="#" th:action="#{/search}" th:object="${employeeSearchFormData}" method="post">
<div alight="left">
<tr>
<label class="form-label" >Employee ID</label>
<td>
<input type="text" th:field="*{employeeId}" class="form-control" placeholder="Employee ID" />
</td>
</tr>
</div>
<br>
<tr>
<td colspan="2"><button type="submit" class="btn btn-info">Search</button> </td>
</tr>
<div alight="left">
<tr>
<label class="form-label" >Employee Name</label>
<td>
<input type="text" th:field="${employee.ename}" class="form-control" placeholder="Employee Name" />
</td>
</tr>
</div>
</form>
Note the use of th:field="${employee.ename}" and not use *{...}. I also removed the hidden field as it does not seem needed to have it to me.
As an alternative, you can have the #PostMapping redirect to /employee/<id> if there is an endpoint available like that:
#PostMapping("/search")
public String doSearchEmployee(#ModelAttribute("employeeSearchFormData") EmployeeSearchFormData formData) {
return "redirect:/employee/" + formData.getEmployeeId();
}

Image uploading and displaying from database H2 error spring boot thymleaf

I am trying to build a Book shop website using Springboot,thymleaf,H2 embedded. When I try to upload the picture of new book category it gives me a null pointer error
this is my Category.class
#Entity
#Table(name="category")
public class Category implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Size(min=1, max=90)
#Column(name="CATEGORY_NAME")
private String CategoryName;
#Lob
#Column(name="CATEGORY_PHOTO")
private byte[] CategoryPhoto;
public Category(Long id, #Size(min = 1, max = 90) String categoryName, byte[] categoryPhoto) {
super();
this.id = id;
CategoryName = categoryName;
CategoryPhoto = categoryPhoto;
}
public byte[] getCategoryPhoto() {
return CategoryPhoto;
}
public void setCategoryPhoto(byte[] categoryPhoto) {
CategoryPhoto = categoryPhoto;
}
public Category() {}
#OneToMany(mappedBy = "category", cascade=CascadeType.ALL, orphanRemoval=true)
private Set<Book> Books = new HashSet<>();
public Set<Book> getBooks() {
return Books;
}
CategoryController:
#Controller
#RequestMapping(value="/categories")
public class CategoryController {
private final Logger logger = LoggerFactory.getLogger(BookController.class);
private MessageSource messageSource;
#Autowired
private CategoryService categoryService;
#GetMapping
public String list(Model uiModel) {
logger.info("Listing categories:");
List<Category> categories = categoryService.findALL();
uiModel.addAttribute("categories", categories);
logger.info("No. of categories: " + categories.size());
return "categories";
}
#GetMapping(value = "/{id}")
public String show(#PathVariable Long id, Model model) {
Category category = categoryService.findbyID(id);
if(category.getCategoryPhoto() == null) {
logger.debug("Downloading photo for id: {} with size{}",
category.getId(), category.getCategoryPhoto().length);
}
model.addAttribute("category", category);
return "showCategory";
}
#GetMapping(value = "/new")
public String create(Model uiModel) {
logger.info("creating Category ...");
Category category = new Category();
uiModel.addAttribute("category", category);
return "updateCategory";
}
#PostMapping
public String saveCategory(#Valid Category category, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes,
Locale locale, #RequestParam(value="file", required=false) Part file) {
logger.info("Creating Category....");
if(bindingResult.hasErrors())
{
uiModel.addAttribute("message", new Message("error", messageSource.getMessage("category_save_fail", new Object[] {}, locale)));
uiModel.addAttribute("Category", category);
return "categories/new";
}
uiModel.asMap().clear();
redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("Category_save_success", new Object[] {}, locale)));
logger.info("Category ID" + category.getId());
//process upload file
if(file != null) {
logger.info("File name:" + file.getName());
logger.info("File size:" + file.getSize());
logger.info("File content type:" + file.getContentType());
byte[] filecontent = null;
try
{
InputStream inputStream = file.getInputStream();
if(inputStream == null)
logger.info("File InputStream is null");
filecontent = IOUtils.toByteArray(inputStream);
category.setCategoryPhoto(filecontent);
}catch(IOException ex) {
logger.error("Error Saving uploaded file");
}
category.setCategoryPhoto(filecontent);
}
categoryService.save(category);
return "redirect:/categories/" + category.getId();
}
}
updatecategories.html page :: used for creating a new category and updating category with Name and Categoryphoto
<form class="form-horizontal" th:object="${category}" th:action="#{/categories}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Category Name</label>
<div class="col-sm-10">
<input class="form-control" th:field="*{CategoryName}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Category Photo</label>
<div class="col-sm-10">
<input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
</div>
</div>
<div class="row">
<button class="btn btn-default">Save</button>
</div>
</form>
show Categories.html page for showing the category name and photo after creating or updating
<form class="form-horizontal" th:object="${category}" th:action="#{/categories}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Category Name</label>
<div class="col-sm-10">
<input class="form-control" th:field="*{CategoryName}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Category Photo</label>
<div class="col-sm-10">
<input name="file" type="file" value="upload" class="form-control" th:field="*{CategoryPhoto}"/>
</div>
</div>
<div class="row">
<button class="btn btn-default">Save</button>
</div>
</form>
here is a image when I create a new category
error Image:
sorry for Long Question description but I want to clarify the details. Help would be appreciated.
I got the mistake I am using MessageSource without autowiring it Done that. And Adding Messages to my properties file.

Bad request error while submitting a form in Spring 4

I'm getting a 400 bad request error while submitting my form.
I'm using spring 4.0.6 version. I don't why this is happening. Please see the below error what I'm getting.
Here is my JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page isELIgnored="false" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="<c:url value='/static/js/jquery-3.3.1.js' />"></script>
<script src="<c:url value='/static/js/bootstrap.min.js' />"></script>
<script src="<c:url value='/static/js/jquery.validate.min.js' />"></script>
<script src="<c:url value='/static/js/additional-methods.min.js' />"></script>
<script src="<c:url value='/static/js/jquery.mask.js' />"></script>
<script src="<c:url value='/static/js/jquery-ui.js' />"></script>
<link href="<c:url value='/static/css/bootstrap.min.css' />" rel="stylesheet"></link>
<link href="<c:url value='/static/css/jquery-ui.css' />" rel="stylesheet"></link>
<style>
.head-color {
background: rgb(243, 246, 234);
color: #800000;
text-align:center;
}
.date-width{
width:25% !important;
}
.error{
color:red;
}
</style>
<script type="text/javascript">
$(function() {
document.getElementById("claimFilingForm").reset();
$('.phone-us').mask('(000) 000-0000');
$('.zip-code').mask('00000-0000');
$( "#phoneAssignedDate" ).datepicker();
jQuery.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg !== value;
}, "This field is required.");
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#claimFilingForm" ).validate({
rules: {
firstName: {
required: true
},
lastName: {
required: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
// valueNotEquals: "default"
},
nickname: {
required: true
},
zip: {
required: true,
zipcodeUS: true
},
phone: {
required: true,
phoneUS: true
},
email: {
required: true,
email: true
},
optradio: {
required: true
},
phoneAssignedDate: {
required: {
depends: function() {
return $('input[name="optradio"]:checked').val() == 'N';
}
}
},
signature: {
required: true
}
},
messages: {
},
errorPlacement: function(error, element) {
var placement = $(element).data('error');
if (placement) {
$(element).css("display","");
$(placement).append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
if ($(form).valid())
{
form.submit();
}
return false; // prevent normal form posting
}
})
});
</script>
</head>
<body>
<div class="container">
<h2 class="well head-color">CLAIM FILING</h2>
<div class="form-group">
<span style="font-weight: bold; color: #875a24;">This is a claim in connection with a class of persons
who were successfully sent unsolicited Pollo Trophical Commercial text messages on
what are commonly called recycled numbers between March 1, 2012 and March 15, 2017</span>
</div>
<div class="col-lg-12 well">
<div class="row">
<form:form id="claimFilingForm" modelAttribute="claimant" method="POST" action="claimFiling">
<div class="col-sm-12">
<div class="form-group">
<span style="font-weight: bold;">1. You Must Provide Your Contact Information, including any nicknames or
aliases or any name you use to obtain mobile telephone service for you or your
family members</span>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>First Name</label>
<form:input type="text" id="firstName" name="firstName" path="firstName" placeholder="Enter First Name" class="form-control" autofocus=""/>
</div>
<div class="col-sm-6 form-group">
<label>Last Name</label>
<form:input type="text" id="lastName" name="lastName" path="lastName" placeholder="Enter Last Name" class="form-control"/>
</div>
</div>
<div class="form-group">
<label>Address</label>
<form:textarea placeholder="Enter Address" id="address" name="address" path="address" rows="3" class="form-control"></form:textarea>
</div>
<div class="row">
<div class="col-sm-4 form-group">
<label>City</label>
<form:input type="text" id="city" name="city" path="city" placeholder="Enter City Name" class="form-control"/>
</div>
<div class="col-sm-4 form-group">
<label>State</label>
<form:input type="text" id="state" name="state" path="state" placeholder="Enter State Name" class="form-control"/>
</div>
<div class="col-sm-4 form-group">
<label>Zip</label>
<form:input type="text" id="zip" name="zip" path="zip" placeholder="Enter Zip5-Zip4 Code" class="form-control zip-code"/>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label>Company/Nickname/Alias</label>
<form:input type="text" id="nickname" name="nickname" path="nickname" placeholder="Enter Company/Nickname/Alias" class="form-control"/>
</div>
<div class="col-sm-6 form-group">
<label>Phone Number</label>
<form:input type="text" id="phone" name="phone" path="phone" placeholder="Enter Phone Number" class="form-control phone-us"/>
</div>
</div>
<div class="form-group">
<label>Email Address</label>
<form:input type="text" id="email" name="email" path="email" placeholder="Enter Email Address" class="form-control"/>
</div>
<div class="form-group">
<br/><br/>
<span style="font-weight: bold;">2. You Must Verify Ownership of the Number Listed Above please select one</span>
</div>
<div class="form-group radio">
<label><form:radiobutton id="optradio1" name="optradio" path="optradio" value="N" data-error="#optradio-error"/>The telephone number listed above was assigned
to me as of below mentioned date
and I did not consent to receive Pollo Trophical advertising text messages
<form:input type="text" id="phoneAssignedDate" name="phoneAssignedDate" placeholder="Select a Date" path="phoneAssignedDate" class="form-control date-width" style="cursor: pointer;" readonly="true"/></label>
</div>
<br/>
<div class="form-group radio">
<label><form:radiobutton id="optradio2" name="optradio" path="optradio" value="Y" />The number listed above was assigned to me and I consented to receive texts from Pollo Trophical</label>
</div>
<div class="form-group">
<span id="optradio-error" class="text-danger align-middle error">
<!-- Put name validation error messages here -->
</span>
</div>
<div class="form-group">
<label>Signature</label>
<form:input type="text" id="signature" name="signature" path="signature" placeholder="Enter Your Name" class="form-control"/>
</div>
<button type="submit" class="btn btn-lg btn-info">Submit</button>
</div>
</form:form>
</div>
</div>
</div>
</body>
</html>
Here is my Controller
package com.application.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 com.application.model.Claimant;
import com.application.service.ClaimFilingService;
#Controller
#RequestMapping("/")
public class ClaimFilingController {
#Autowired
private ClaimFilingService claimFilingService;
#RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String home(ModelMap model) {
return "redirect:/claimFiling";
}
/*
* This method will serve as default GET handler.
*/
#RequestMapping(value = { "/claimFiling" }, method = RequestMethod.GET)
public String newRegistration(ModelMap model, HttpServletRequest request) {
Claimant claimant = new Claimant();
model.addAttribute("claimant", claimant);
return "claimFiling";
}
/*
* This method will be called on form submission, handling POST request It
* also validates the user input
*/
#RequestMapping(value = { "/claimFiling" }, method = RequestMethod.POST)
public String saveRegistration(#ModelAttribute("claimant") Claimant claimant, ModelMap model, HttpServletRequest request) {
String result = claimFilingService.insertClaimDetails(claimant, request);
if(!result.equalsIgnoreCase("")) {
model.addAttribute("ClaimId", result);
return "success";
}
model.addAttribute("message","Process Failed");
return "claimFiling";
}
}
Here is my Claimant model class
package com.application.model;
import java.sql.Date;
public class Claimant {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zip;
private String nickname;
private String phone;
private String email;
private String optradio;
private Date phoneAssignedDate;
private String signature;
public Claimant(String firstName, String lastName, String address, String city, String state, String zip,
String nickname, String phone, String email, String optradio, Date phoneAssignedDate, String signature) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.nickname = nickname;
this.phone = phone;
this.email = email;
this.optradio = optradio;
this.phoneAssignedDate = phoneAssignedDate;
this.signature = signature;
}
public Claimant() {
super();
// TODO Auto-generated constructor stub
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOptradio() {
return optradio;
}
public void setOptradio(String optradio) {
this.optradio = optradio;
}
public Date getPhoneAssignedDate() {
return phoneAssignedDate;
}
public void setPhoneAssignedDate(Date phoneAssignedDate) {
this.phoneAssignedDate = phoneAssignedDate;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
}
I'm a beginner to spring so can some body help me to identify the problem.
Yes, I found the mistake. In the POJO class I changed the type of phoneAssignedDate to String. This resolved my problem :-)

Spring #ModelAttributes auto binding

Hi i am tring to use #ModelAttributes for auto binding from view to controller.
this jsp page should send all elements which is Personal Schedule VO.
<form name="insertFrm" action="myScheduleInsert" method="POST">
<ul>
<input type="hidden" class="form-control" name="perschd_num" >
<li>
<label class='control-label'>title</label>
<input type="text" class="form-control" name="perschd_title" >
</li>
<li>
<input type="hidden" class="form-control" name="perschd_writer" >
<li>
<label class='control-label'>start date</label>
<input type="date" id="fullYear" class="form-control" name="perschd_start_date" value="">
</li>
<li>
<label class='control-label'>end date</label>
<input type="date" class="form-control" name="perschd_end_date" >
</li>
<li>
<label class='control-label'>content</label>
<input type="text" class="form-control" name="perschd_cont" >
</li>
</ul>
</div>
<!-- button-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary">
</form>
and this is my controller for insert feature by using #ModelAttributes PerschdVO perschd and when i try print all out, all is null.
//insertSchedule
#RequestMapping("/myScheduleInsert")
public String myScheduleInsert(#ModelAttribute PerschdVO perschdVO ){
String view="redirect:/professor/mypage/mySchedule";
*System.out.println(perschdVO);*
try {
proService.insertPerschd(perschdVO);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
and this is PerschdVO
public class PerschdVO {
private int perschd_num;
private String perschd_title;
private String perschd_cont;
private Date perschd_date;
private String perschd_start_date;
private String perschd_end_date;
private String perschd_writer; //id
public String getPerschd_writer() {
return perschd_writer;
}
public void setPerschd_writer(String perschd_writer) {
this.perschd_writer = perschd_writer;
}
public int getPerschd_num() {
return perschd_num;
}
public void setPerschd_num(int perschd_num) {
this.perschd_num = perschd_num;
}
public String getPerschd_title() {
return perschd_title;
}
public void setPerschd_title(String perschd_title) {
this.perschd_title = perschd_title;
}
public String getPerschd_cont() {
return perschd_cont;
}
public void setPerschd_cont(String perschd_cont) {
this.perschd_cont = perschd_cont;
}
public Date getPerschd_date() {
return perschd_date;
}
public void setPerschd_date(Date perschd_date) {
this.perschd_date = perschd_date;
}
public String getPerschd_start_date() {
return perschd_start_date;
}
public void setPerschd_start_date(String perschd_start_date) {
this.perschd_start_date = perschd_start_date;
}
public String getPerschd_end_date() {
return perschd_end_date;
}
public void setPerschd_end_date(String perschd_end_date) {
this.perschd_end_date = perschd_end_date;
}
why this elements from jsp does not match with this? Eventhough i matched all name in jsp file to PerschdVO's get() names.
and if i fix like this
public String myScheduleInsert(
Principal who,
#RequestParam("perschd_start_date")String perschd_start_date,
#RequestParam("perschd_end_date")String perschd_end_date,
#RequestParam("perschd_title")String perschd_title,
#RequestParam("perschd_cont")String perschd_cont
){
PerschdVO perschdVO = new PerschdVO();
...}
than the data from jsp could be sent to #Controller, but still can't get informations about using #ModelAttributes. cos if i use that always 400 bad request happened.

Spring , HIbernate need assistance

This is my index.jsp
<body>
<div class="container">
<div class="row">
<h1 class="text-center">Rupasinghe Trust Invesments</h1>
<div
class="col-lg-4 col-md-4 col-sm-8 col-xs-12 col-lg-offset-4 col-md-offset-4 col-sm-offset-2">
<div class="myForm">
<form:form class="form_signin" method="POST" commandName="user" action="login">
<%-- <form:input path="branch" type="text" class="form-control" name="branch"
placeholder="Branch Code" required="autofocus" /><br />
--%>
<form:input path="username"
type="text" class="form-control" name="username"
placeholder="Username" required="autofocus" /><br />
<form:input path="password"
type="password" class="form-control" name="password"
placeholder="Password" required="autofocus" /><br />
<input type="submit" value="Login" class="btn"/>
</form:form>
</div>
</div>
</div>
</div>
</body>
This is my LoginController.java
#Controller
public class LoginController {
#RequestMapping(value="/login" , method=RequestMethod.POST)
public String login(#ModelAttribute("user") User user , BindingResult result){
return "mainFrameAdminPanlel";
}
}
This is the bean User.java
#Entity
public class User {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String username;
private String password;
#ManyToOne
#JoinColumn(name="branchId")
private BranchEntity branch;
#OneToMany
private Set<UserAccess> userAccess;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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 BranchEntity getBranch() {
return branch;
}
public void setBranch(BranchEntity branch) {
this.branch = branch;
}
public Set<UserAccess> getUserAccess() {
return userAccess;
}
public void setUserAccess(Set<UserAccess> userAccess) {
this.userAccess = userAccess;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
I am getting this error
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
I am new to spring and still couldn't get what is wrong with this. Please help ! Thank you in advance
When you load the first page itself, I mean the page containing the form, you need to pass an instance of User. This exception is thrown since you have not passed instance of User that you are trying to use in the form. Kindly check.

Resources