How to search by ID an OBJ with Spring MVC and Thymeleaf? - java

Im learning Spring MVC and Thymeleaf, currently I can make a page to create an OBJ and save it in my DB, also i can make a list of all of the obj and show it on the page.
What im trying to do is to be able to introduce and id in the page and search the matching id OBJ and show it on screen.
This is my Entity:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
int dni;
String name;
String surname;
public int getDni() {
return dni;
}
public void setDni(int dni) {
this.dni = dni;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
This is my Repository:
package com.demolorenzo.user;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends CrudRepository<User, String> {
List<User>findAll();
List<User>findByName(String name);
List<User>findByDni(int dni);
}
And my Controller:
package com.demolorenzo.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class DemoController {
#Autowired
UserRepository userrepo;
#GetMapping("/Home")
public String userForm(Model model) {
model.addAttribute("user", new User());
return "Home";
}
#PostMapping("/Home")
public String userSubmit(#ModelAttribute User user, Model model) {
model.addAttribute("user", user);
userrepo.save(user);
return "users";
}
#GetMapping("/search")
public String searchForm(Model model) {
model.addAttribute("user", new User());
return "search";
}
#PostMapping("/search")
public String searchSubmit(#ModelAttribute User user, Model model) {
model.addAttribute("user", userrepo.findByDni(user.getDni()));
return "users";
}
}
This is the View (/search):
<form action="#" th:action="#{/search}" th:object="${user}" method="post">
<p> DNI: <input type="number" th:field="*{dni}"/> </p>
<p> <input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
And the last View (/users):
<h1>Result</h1>
<p th:text="'Dni: ' + ${user.dni}" />
<p th:text="'Name: ' + ${user.name}" />
<p th:text="'Surname: ' + ${user.surname}" />
Submit another message
And this is the error im getting:
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'dni' cannot be found on object of type 'java.util.ArrayList' - maybe not public or not valid?

Your view is trying to access the dni property of the user object:
<p th:text="'Dni: ' + ${user.dni}" />
However, in the controller, you are doing:
#PostMapping("/search")
public String searchSubmit(#ModelAttribute User user, Model model) {
model.addAttribute("user", userrepo.findByDni(user.getDni()));
return "users";
}
You are adding the result of the userrepo.findByDni() method as user. But that method returns a List<User>, not a single user.
So user in the view is a List<User> which obviously has not dni property.
You should probably update the controller method to put the result of the repository method in a variable users for example. And use th:each to iterate over those users.

Related

Resolved [org.springframework.beans.TypeMismatchException: Issue

I'm attempting to build a twitter clone website using spring boot. I'm getting an error and looked through my code. I'm not sure what I'm doing wrong:
2022-03-15 12:23:51.067 WARN 4580 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'com.example.demo.Tweet'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value 'Test'; nested exception is java.lang.NumberFormatException: For input string: "Test"]
This is a springboot application using postgres as its database. I also have a User repository in the code that does sign me in properly. I would appreciate any assistance with this. Thank you.
Edit: Added full stacktrace.
Edit2: Added an image of the tweeting.html to show where the string "Test" came from.
Tweet.java
package com.example.demo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Entity
#Table(name="tweets")
public class Tweet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id",unique=true, nullable = false)
private Integer id;
#Column(name="userid", unique=true, nullable=false)
private Integer userid;
#Column(name="tweet", nullable=false)
private String tweet;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userid;
}
public void setUserId(Integer userid) {
this.userid = userid;
}
public String getTweet() {
return tweet;
}
public void setTweet(String tweet) {
this.tweet = tweet;
}
}
TweetRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface TweetRepository extends JpaRepository<Tweet, Integer>{
public Tweet findAllById(Integer userid);
}
TwitterController.java
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Controller
public class TwitterController{
#Autowired
private UserRepository userRepo;
private TweetRepository tweetRepo;
#RequestMapping("/")
public String index(Model model) {
//model.addAttribute("message", "Welcome to spring!");
return "index";
}
#RequestMapping("/testing")
public String testing(Model model) {
model.addAttribute("message", "Welcome to spring boot!");
return "testing";
}
#GetMapping("/register")
public String signup(Model model) {
User user = new User();
model.addAttribute("user", user);
return "register";
}
#RequestMapping("/login")
public String login(Model model) {
return "login";
}
#RequestMapping("/tweeting")
public String tweeting(Model model) {
Tweet tweet = new Tweet();
model.addAttribute("tweet", tweet);
return "tweeting";
}
#PostMapping("/process_register")
public String processRegister(User user) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepo.save(user);
return "register_success";
}
#PostMapping("/process_tweet")
public String processTweet(Tweet tweet) {
tweetRepo.save(tweet);
return "tweet_success";
}
}
tweeting.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Tweet</title>
<link href="webjars/bootstrap/5.1.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container col-xl-10 col-xxl-8 px-4 py-5">
<div class="row align-items-center g-lg-5 py-5">
<div class="col-md-10 mx-auto col-lg-5">
<form class="p-4 p-md-5 border rounded-3 bg-light" th:action="#{/process_tweet}" th:object="${tweet}" method="post">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput" placeholder=tweet th:field="*{tweet}">
<label for="floatingInput">Tweet</label>
</div>
<button class="w-100 btn btn-lg btn-info" type="submit">Post</button>
</form>
</div>
</div>
</div>
<script src="webjars/jquery/3.6.0/jquery.min.js"></script>
<script src="webjars/bootstrap/5.1.0/js/bootstrap.min.js"></script>
<script>
</script>
</body>
</html>

How to store Form data in a H2 Database (currently works using POSTman, but not the website form)

I am just teaching myself the Spring framework and am trying to makie a simple library app which stores user (book) inputs in a form in the H2 Database, and then shows the user the newly inputted data from the H2 Database.
Form submission attempt 1:
I now have a working POST method which correctly saves a new book to the H2 repository - however when I try to connect this method to the submission of a form, no such repository stores occur.
Form submission attempt 2:
Working POST request using POSTman 3:
Working POST request using POSTman 4:
Code snippets below:
HTMLfile with the Thymeleaf form inside:
<h2> Enter a book below to add it to your basket: </h2>
<form action="/addToBasket" th:action="#{/addToBasket}" th:object="${book}" method="post">
<p> Book Title: <input type="text" th:field="*{bookTitle}"></p>
<p> Author: <input type="text" th:field="*{bookAuthor}"></p>
<p> publicationYear: <input type="text" th:field="*{publicationYear}"></p>
<p> price: <input type="text" th:field="*{price}"></p>
<br>
<!-- <input type="submit" value="Submit">-->
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
POST method in the controller class which works for POST requests from POSTman, but fails to store the form data in the same way:
#PostMapping("/addToBasket")
public Basket addToBasket(#RequestBody Basket newBook) {
return basketRepository.save(newBook);
}
Basket #entity:
#Entity
public class Basket {
private #Id #GeneratedValue Long basketId;
private String bookTitle;
private String author;
private String publisher;
public Basket() {
}
public Basket( String bookTitle, String author, String publisher) {
this.bookTitle = bookTitle;
this.author = author;
this.publisher = publisher;
}
For anyone wondering, this is how you do it...
Set the form up like below, (it just needs to point to the name of the path in the controller method):
<form action="/addToBasket" method="post">
B name:<input name="bookTitle" value="yosi"/><br>
A name:<input name="author" value="lev"/><br>
<input type="submit"/>
</form>
Then set up the method in the controller like so:
#RequestMapping(value = "/addToBasket", method = RequestMethod.POST)
public #ResponseBody String test( Basket basket) {
basketRepository.save(basket);
return "Hello test : " + basket;
}
^It takes in the inputs from the form as a Basket object so you just need to save this to the appropriate repository, make sure you have a toString() method in this Basket class so you can print out the results if necessary to do so
This is my Basket class in case this is useful:
package springLibrary.domain;
import javax.persistence.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
#Entity
public class Basket {
// private Set<Book> bookBasket = new HashSet<>();
private #Id #GeneratedValue Long basketId;
private String bookTitle;
private String author;
private String publisher;
public Basket() {
}
public Basket( String bookTitle, String author, String publisher) {
this.bookTitle = bookTitle;
this.author = author;
this.publisher = publisher;
}
public Long getBasketId() {
return basketId;
}
public void setBasketId(Long basketId) {
this.basketId = basketId;
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle = bookTitle;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Basket basket = (Basket) o;
return Objects.equals(basketId, basket.basketId);
}
#Override
public String toString() {
return "Basket{" +
"basketId=" + basketId +
", bookTitle='" + bookTitle + '\'' +
", author='" + author + '\'' +
", publisher='" + publisher + '\'' +
'}';
}
#Override
public int hashCode() {
return Objects.hash(basketId);
}
}
^it has the same variable names as those used in the HTML file.
When you run your locally hosted site, if you have an appropriate getter for basket e.g
#RequestMapping("/basket")
public String getBasket(Model model){
model.addAttribute("basket", basketRepository.findAll());
return "basket/list";
}
... then you should be able to see your newly stored basket object in your basket repository.

JSTL Spring Boot - Bean property 'email' is not readable or has an invalid getter method

I am fairly new to using Spring Boot and JSTL. I am currently trying to implement something in my view where I can select multiple checkboxes and send the data over to my controller to operate on. I think I have done everything correctly but can't seem to find the root of the problem here. Can someone please help? Getting the following error:
021-02-09 17:49:45.227 ERROR 16216 --- [nio-8080-exec-6]
o.s.web.servlet.tags.form.CheckboxTag : Invalid property 'email' of
bean class [java.util.ArrayList]: Bean property 'email' is not
readable or has an invalid getter method: Does the return type of the
getter match the parameter type of the setter?
org.springframework.beans.NotReadablePropertyException: Invalid
property 'email' of bean class [java.util.ArrayList]: Bean property
'email' is not readable or has an invalid getter method: Does the
return type of the getter match the parameter type of the setter? at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:625)
~[spring-beans-5.3.3.jar:5.3.3] at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:615)
~[spring-beans-5.3.3.jar:5.3.3]
My Controller:
package com.bizlinks.mainapp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import com.bizlinks.mainapp.models.Lead;
import com.bizlinks.mainapp.repository.UserRepository;
#Controller
public class AdminController {
#Autowired // This means to get the bean called userRepository
//Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository;
#RequestMapping(value = "admin", method = RequestMethod.GET)
public String List(Model model) {
List<Lead> leads = userRepository.findAll();
model.addAttribute("leads", leads);
return "admin";
}
#RequestMapping(value = "admin", method = RequestMethod.POST)
public String deleteLead(#ModelAttribute("leads")List<Lead> leads){
for(int i =0; i< leads.size();i++) {
System.out.println(leads.get(i).getEmail());
}
return "admin";
}
}
My model:
package com.bizlinks.mainapp.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "leads")
public class Lead {
#Id
#Column(name = "email")
private String email;
#Column(name = "firstName")
private String firstName;
#Column(name = "surName")
private String surName;
#Column(name ="phone")
private String phone;
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
My view body:
<body>
<nav class="nav nav-fill">
<a class="nav-link" href="/">Home</a>
</nav>
<div class="container-fluid con">
<table>
<tr>
<th>First Name</th>
<th>Surname</th>
<th>Email</th>
<th>Phone</th>
</tr>
<form:form action="admin" modelAttribute="leads">
<c:forEach items="${leads}" var="item">
<tr>
<td><c:out value="${item.email}"/></td>
<td><c:out value="${item.firstName}"/></td>
<td><c:out value="${item.surName}"/></td>
<td><c:out value="${item.phone}"/></td>
<form:checkbox path="email" value="${item.email}"/>
</tr>
</c:forEach>
<input type="submit" value="Submit" />
</form:form>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.min.js"></script>
</body>

Problem with saving data from Thymeleaf form to database with Spring MVC

I've just started learning Spring MVC. I try to save some data from the Thymeleaf form to repository, which extends CrudRepository. Unfortunately, the data doesn't display.
When I go to the results page I see used IDs but no data typed to form. Where is the mistake?
Here is a Controller
package com.jtm.twiservice.controller;
import com.jtm.twiservice.Main;
import com.jtm.twiservice.model.Customer;
import com.jtm.twiservice.repository.CustomerRepository;
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.web.bind.annotation.*;
#Controller
public class CustomerClientController {
private static final Logger myLog = LoggerFactory.getLogger(Main.class);
#Autowired
private CustomerRepository customerRepository;
#GetMapping("/customer")
public String customerForm(Model model) {
model.addAttribute("customer", new Customer());
return "customer";
}
#PostMapping("/customer")
public String createCustomer(Customer customer, Model model) {
customerRepository.save(customer);
return "customer";
}
#GetMapping("/customers")
public String getCustomers(Model model) {
model.addAttribute("customers", customerRepository.findAll());
return "customers;
}
}
`Model:
package com.jtm.twiservice.model;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String schoolForm;
public Customer() {}
public Customer(String firstName, String lastName, String email, String schoolForm) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.schoolForm = schoolForm;
}
#Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s', email='%s', schoolForm='%s']",
id, firstName, lastName, email, schoolForm);
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getSchoolForm() {
return schoolForm;
}
}
repository:
package com.jtm.twiservice.repository;
import com.jtm.twiservice.model.Customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long> { }
form extract:
<form action="#" th:action="#{/customer}" th:object="${customer}" method="post">
<p class="text"><label>first name:</label> <input type="text" th:field="*{firstName}" /></p>
<p class="text"><label>last name:</label> <input type="text" th:field="*{lastName}" /></p
<p class="text"><label>school form:</label> <input type="text" th:field="*{schoolForm}" /></p>
<div class="text">email: <input type="text" th:field="*{email}" /></div>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /> </p>
</form>
And extract from results template:
<td th:text="${customer.id}">customer ID</td>
<td th:text="${customer.firstName}">first name</td>
<td th:text="${customer.lastName}">last name</td>
Try to use
List<Customer> customers = new customerRepository.findAll();
Model.addAttribute("c" , customers);
See my question for more information Store pictures in H2 database spring boot thymleaf
Another way, with this code:
model.addAttribute("customers", customerRepository.findAll());
for result template:
<th:block th:each="customer : ${customers}">
<td th:text="${customer.id}">customer ID</td>
<td th:text="${customer.firstName}">first name</td>
<td th:text="${customer.lastName}">last name</td>
</th:block>
try this :
#PostMapping("/customer")
public String createCustomer(Customer customer,BindingResult result)
{
if (result.hasErrors())
{
return "your error page in here";
}
customerRepository.save(customer);
return "customer";
}
Although this post is already old, I just stumbled upon it when debugging my own code; my answer may still help someone in the future.
I believe I had a similar issue, where the Thymeleaf form didn't actually assign values to the entity's fields. For me the issue was that the entity had no setters for its fields - it looks like you have that problem here as well.

Spring+Velocity unsuccessful attempts to save object

I`ve ran into a problem with controller/vm data transfer and could not find any solution.
Ive got a User (see class below)
package com.Entity;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import java.util.Date;
#Entity
#Transactional
#Table(name = "USERS")
public class User {
private Long id;
private UserType type;
private String email;
private String password;
private String name;
private String tel;
private Date regDate;
private Date lastActive;
private Agent office;
//Constructors
public User(){
}
public User(UserType type, String email, String password, String name, String tel, Agent office) {
this.type = type;
this.email = email;
this.password = password;
this.name = name;
this.tel = tel;
this.regDate = new Date();
this.lastActive = null;
this.office = office;
}
//Getters
#Id
#SequenceGenerator(name = "USERID_SEQ", sequenceName = "USERID_SEQ",allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USERID_SEQ")
#Column(name = "ID")
public Long getId() {
return id;
}
#Column(name = "TYPE")
public UserType getType(){
return type;
}
#Column(name = "EMAIL")
public String getEmail() {
return email;
}
#Column(name = "PASSWORD")
public String getPassword() {
return password;
}
#Column(name = "NAME")
public String getName() {
return name;
}
#Column(name = "TEL")
public String getTel() {
return tel;
}
#Column(name = "DATE_REG")
public Date getRegDate() {
return regDate;
}
#Column(name = "LAST_ACTIVE")
public Date getLastActive() {
return lastActive;
}
#ManyToOne (targetEntity = Agent.class, fetch = FetchType.EAGER)
#JoinColumn(name = "OFFICEID")
public Agent getOffice() {
return office;
}
// Setters
}
Controller for it
package com.Controllers;
import com.Entity.AgentType;
import com.Entity.User;
import com.Services.AgentService;
import com.Services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 org.springframework.web.servlet.ModelAndView;
import java.util.List;
//TODO: TEST CONTROLLER SUBJECT TO DELETE
#Controller
public class ViewController {
#Autowired
private UserService userService;
#Autowired
private AgentService agentService;
#RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView listUsersPage(){
List<User>list = userService.getAll();
return new ModelAndView("fragments/userss.vm","users",list);
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public ModelAndView edit(#PathVariable Long id){
return new ModelAndView("fragments/edit.vm",
"user", (User)userService.getById(id));
}
//FUNCTIONAL
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public ModelAndView delete(#PathVariable Long id){
userService.delete(userService.getById(id));
return new ModelAndView("redirect:/list");
}
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(User user){
User user1 = user;
//userService.update(user1);
return new ModelAndView("redirect:/list");
}
//Model Attributes
#ModelAttribute
public void userTypesList(Model model){
model.addAttribute("types", userService.getPositions());
}
#ModelAttribute
public void officesList(Model model){
model.addAttribute("offices", agentService.getAllByType(AgentType.OFFICE));
}
}
and a pages (.vm) to add new or edit existing users(just one example the edit page):
<title>EDIT USER</title>
<body>
<form method="post" action="/update">
id:
<input type="text" name="id" path="id" value="$user.id"/> <br>
Type:
<select name="type" path="type">
<option hidden selected>$user.type</option>
#foreach($type in $types)
<option value="$type">$type</option>
#end
</select> <br>
e-mail:
<input type="text" name="email" path="email" value="$user.email"/> <br>
Password:
<input type="text" name="password" path="password" value="$user.password"/> <br>
Name:
<input type="text" name="name" path="name" value="$user.name"/> <br>
Tel:
<input type="text" name="tel" path="tel" value="$user.tel"/> <br>
Reg Date:
<input type="date" name="regDate" path="regDate" value="$user.regDate"/> <br>
Last Active:
<input type="date" name="lastActive" path="lastActive" value="$user.lastActive"/> <br>
Office:
<select name="office" path="office">
<option hidden selected value="$user.office">$user.office.name</option>
#foreach($office in $offices)
<option value="$office">$office.name</option>
#end
</select> <br>
<input type="submit" value="Update"/>
</form>
</body>
The problem is that I cant manage to save the updated User via /update(User user). Ive tried different ways, but still no success.
Whis this code I`m getting HTTP Status 400 – Bad Request. The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
Could you please help me out? What is wrong with it?
In your code you are missing a couple of things.
Frist of all, you miss the model attribute specified in the form:
<form method="post" action="/update" modelAttribute="user">
Second, you are missing the model attribute specified in the post method:
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(#ModelAttribute("user") User user){
User user1 = user;
userService.update(user1);
return new ModelAndView("redirect:/list");
}
If you need further details, you can read Getting Started with Forms in Spring MVC

Categories