Image uploading and displaying from database H2 error spring boot thymleaf - spring-boot

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.

Related

Select thymeleaf doesn't create a value in my db

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;

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

Request method 'GET' not supported Spring Boot

I'm a beginer full stack developer. I need help.
I have the following code:
Controller:
#Controller
public class GreetingController {
#Autowired
private MessageRepos messageRepos;
#GetMapping("/")
public String greeting(Map<String, Object> model) {
return "greeting";
}
#GetMapping("/main")
public String main(Map<String, Object> model) {
Iterable<Message> messages = messageRepos.findAll();
model.put("messages", messages);
return "main";
}
#PostMapping("/main")
public String add(#RequestParam String text, #RequestParam String tag, Map<String, Object> model) {
Message message = new Message(text, tag);
messageRepos.save(message);
Iterable<Message> messages = messageRepos.findAll();
model.put("messages", messages);
return "main";
}
#PostMapping("filter")
public String filter(#RequestParam String filter, Map<String, Object> model) {
Iterable<Message> messages;
if (filter != null && !filter.isEmpty()) {
messages = messageRepos.findByTag(filter);
} else {
messages = messageRepos.findAll();
}
model.put("messages", messages);
return "main";
}
HTML:
</div>
<div>
<form method="post">
<input type="text" name="text" placeholder="Message" />
<input type="text" name="tag" placeholder="Tag">
<button type="submit">Add</button>
</form>
</div>
<div>
<form method="post" action="filter">
<input type="text" name="filter">
<button type="submit">Find</button>
</form>
</div>
When I click on the buttons add and find I get the problem.
Problem:
Request method 'GET' not supported.

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?

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