Select thymeleaf doesn't create a value in my db - spring

I have a project of library in spring with thymeleaf and MySQL. I have a form of book in which I have select option with author and other with editorial. I receive a list of all of them from my ddbb, but when I submit in the button the data doesn't create a registry in my ddbb, But when I use input its work fine.
here is the code
HTML
<div class="form-group">
<label class="col-sm-2 col-form-label">Autor</label>
<div class="col-sm-6">
<select th:field="*{autor}" id="provincia">
<option th:each="autor:${autores}" th:text="${autor.nombre}"
th:value="${autor.id}" />
</select>
<!-- <input type="text" th:field="*{autor.id}" class="form-control" th:errorclass="'form-control alert-danger'" />-->
<!-- <small class="form-text text-danger" th:if="${#fields.hasErrors('autor.id')}" th:errors="*{autor.id}"></small> -->
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-form-label">Editorial</label>
<div class="col-sm-6">
<select th:field="*{editorial}">
<option th:each="editorial:${editoriales}"
th:text="${editorial.nombre}" th:value="${editorial.id}" />
</select>
<!-- <input type="text" th:field="*{editorial.id}" class="form-control" th:errorclass="'form-control alert-danger'" />-->
<!-- <small class="form-text text-danger" th:if="${#fields.hasErrors('editorial.id')}" th:errors="*{editorial.id}"></small> -->
</div>
</div>
Here is the controller
#RequestMapping(value = "/form_lib")
public String crearLibro(Model model) {
Libro libro = new Libro();
model.addAttribute("libro", libro);
model.addAttribute("titulo", "Formulario crear Libro");
model.addAttribute("autores", autorDao.listaAutores());
model.addAttribute("editoriales", editorialDao.listaEditoriales());
return "form_lib";
}
#RequestMapping(value = "/form_lib", method = RequestMethod.POST)
public String guardarLibro(#Valid #ModelAttribute Libro libro, BindingResult result, Model model,
#RequestParam("file") MultipartFile imagen, RedirectAttributes attributes) {
if (result.hasErrors()) {
model.addAttribute("titulo", "Formulario de Libro");
model.addAttribute("libro", libro);
System.out.println("errrorrrr");
return "listar_libro";
}
if (!imagen.isEmpty()) {
=Paths.get("src//main//resources//static/images");
String rutaAbsoluta = "//home//marce//Documentos//imagen";
try {
byte[] bytesImg = imagen.getBytes();
Path rutaCompleta = Paths.get(rutaAbsoluta + "//" + imagen.getOriginalFilename());
Files.write(rutaCompleta, bytesImg);
libro.setImagen(imagen.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(libro.toString());
libroDao.guardarLibro(libro);
return "redirect:/form_lib";
}
Here is the entity
#Entity
#Table(name = "libros")
public class Libro implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_libro")
private int id;
#Column(name = "isbn")
private long isbn;
#Column(name = "titulo")
private String titulo;
#Column(name = "anio")
private int anio;
#Column(name = "ejemplares")
private int ejemplares;
#Column(name = "ejemplaresp")
private int ejemplaresPrestados;
#Column(name = "ejemplaresr")
private int ejemplaresRestantes;
#Column(name = "alta")
private boolean alta;
#Column(name = "imagen")
private String imagen;
#OneToOne
#JoinColumn(name="id_autor")
private Autor autor;
#OneToOne
#JoinColumn(name="id_editorial")
private Editorial editorial;

Related

how to pass value in thymleaf, checking entity for betting service

creating simple match betting service. I have a problem in thymeleaf with passing the value of the match on which the user is currently betting. I want to pass the ID of the match I am betting on to the bet table. I'm not entirely sure about the entities I have whether they are designed correctly. Currently to the bet table passes me the team that the user is betting on by entering the name on input, I want to pass the match ID as well but without entering.
Bet entity
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Setter
#Getter
#Builder
public class Bet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name = "employee_id")
private Employee employee;
#ManyToOne(cascade = CascadeType.REMOVE)
#JoinColumn(name = "match_id")
private Match match;
#Column(name = "team_bet")
private String teamBet;
private String result;
}
Match entity
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Setter
#Getter
#Builder
public class Match {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "first_team_name")
private String firstTeamName;
#Column(name = "second_team_name")
private String secondTeamName;
#DateTimeFormat(pattern ="yyyy-MM-dd")
private Date dateOut;
#OneToMany(mappedBy = "match", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Bet> bet = new HashSet<>();
private String timeOut;
}
Controllers
#GetMapping("/matches/bet/{id}")
public String createBet(Model model, #PathVariable(name = "id") int matchId) throws MatchNotFoundExceptions {
Match match = matchService.getMatch(matchId);
Bet bet = new Bet();
model.addAttribute("match", match);
model.addAttribute("bet", bet);
return "bet_form";
}
#PostMapping("/bet/save")
public String saveBet(Bet bet, RedirectAttributes redirectAttributes) {
betService.createBet(bet);
redirectAttributes.addFlashAttribute("message", "The bet has been created successfully!");
return "redirect:/bets";
}
bet_form.html
<form th:action="#{/bet/save}" method="post"
style="max-width: 700px; margin: 0 auto" th:object="${bet}">
<input type="hidden" th:field="*{id}"/>
<input type="hidden">
<form th:object="${match}">
<!--send to bet entity-->
<td th:text="${id}"></td>
</form>
<div style="text-align: center" class="m-3">
<b>Match Start: </b>
<td th:text="${#dates.format(match.dateOut, 'yyyy-MM-dd')}"></td>
<td th:text="${match.timeOut}"></td>
<div style="text-align: center" class="m-3">
<a th:text="${match.firstTeamName}"></a>
<b>VS</b>
<a th:text="${match.secondTeamName}"></a>
<div class="m-4">
<b>Team Name:</b>
<input type="text" class="form-control"
th:field="*{teamBet}" required minlength="3" maxlength="24"/>
</div>
</div>
</div>
<div class="text-center">
<div class="m-3">
<input type="submit" value="accept" class="btn btn-primary"/>
<input type="submit" value="cancel" class="btn btn-warning"
onclick="location.href='/matches';"/>
</div>
</div>
</form>

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

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?

hibernate validation not working while one-to-one mapping in between two entities

During form submission, if there is any validation error then form shows the errors messages under the fields. But the actual problem is in another place. I have two entities User and UserDetails. These entities are mapped with each other by bidirectional one-to-one mapping. Validation is working only with the User entity fields but not with the UserDetails entity.
Spring - 5.0.2`
Hibernate - 5.2.10
User.java
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotEmpty(message="{common.error.msg}")
private String first_name;
#NotEmpty(message="{common.error.msg}")
private String last_name;
#NotEmpty(message="{common.error.msg}")
private String status;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY)
private UserDetails userDetails;
//Getter and setter methods
}
UserDetails.java
#Entity
#Table(name="user_details")
public class UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int user_id;
#NotEmpty(message="{common.error.msg}")
private String address;
#NotEmpty(message="{common.error.msg}")
private String mobile;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id")
private User user;
//Getter and setter methods
}
Get and Post methods in the controller class
#GetMapping(value="/create")
public String loadUserForm(Model model) {
model.addAttribute("command", new User());
return "backend/oms/user/form"; //JSP
}
#PostMapping(value="/create")
public String Save(#Valid #ModelAttribute("command") User user, BindingResult br, Model model, HttpSession session, RedirectAttributes ra) {
if(br.hasErrors()) {
return "backend/oms/user/form"; //JSP
} else {
try {
int id = userService.save(user);
if(id > 0) {
ra.addFlashAttribute("flash_msg", "ok|User added!");
return "redirect:/oms/user/edit/"+id;
} else {
return "backend/oms/user/create"; //JSP
}
} catch (ConstraintViolationException ex) {
model.addAttribute("err", "Something wrong! Please try again.");
return "backend/oms/user/form"; //JSP
}
}
}
messages.properties
common.error.msg=This field is required!
form.jsp
<form:form action="/oms/user/create" method="post" modelAttribute="command">
<label>First Name</label>
<form:input path="first_name" class="form-control" placeholder="First Name" value="" />
<form:errors cssClass="error" path="first_name" />
<label>Last Name</label>
<form:input path="last_name" class="form-control" placeholder="Last Name" value="" />
<form:errors cssClass="error" path="last_name" />
<label>Mobile</label>
<form:input path="userDetails.mobile" class="form-control" placeholder="Mobile" value="" />
<form:errors cssClass="error" path="userDetails.mobile" />
<label>Address</label>
<form:textarea path="UserDetails.address" class="form-control" placeholder="Address" value="" />
<form:errors cssClass="error" path="userDetails.address" />
<label>Status</label>
<form:select class="form-control" path="status">
<option value="">Choose...</option>
<option value="E">Enable</option>
<option value="D">Disable</option>
</form:select>
<form:errors path="status" cssClass="error"/>
<input type="submit" class="btn btn-primary" value="Save" />
</form>
Please see the screenshot
As you can see the image only fields from the User entity is validating but fields those are from the UserDetails are not validating. Please help.
It is solved now. #Valid annotation solved my problem. I need to put #Valid annotation before the entity variable declaration like below --
#OneToMany(mappedBy="majorHead", cascade = CascadeType.ALL)
#Valid
private List<MinorHead> minorHead = new ArrayList<MinorHead>();

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.

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