How to receive a Array from a Json into Set<String> in Java? - java

Basically my json post is looks like this:
{username: "2kzhuanyonghao2", password: "qqq542417349", confirmPassword: "qqq542417349", firstname: "peiran", lastname: "liu", …}
confirmPassword: "qqq542417349"
email: "liupeiran9324#gmail.cokm"
firstname: "peiran"
lastname: "liu"
password: "qqq542417349"
phone: "234324234322"
roles: Array(2)
0: "Manager"
1: "Admin"
length: 2
__proto__: Array(0)
username: "2kzhuanyonghao2"
__proto__: Object
Well, as you can see the roles is a Array(2) which contain "Manager" and "Admin"
Now I wish my Java spring backend can get this roles into a Set of String, then I have a
signUpRequest class :
package com.crmbackend.payLoad.request;
import java.util.Set;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class SignupRequest {
#NotBlank
#Size(min = 1, max = 128)
private String username;
#NotBlank
#Size(min = 5, max = 128)
private String password;
#NotBlank
#Size(max = 128)
#Email
private String email;
#NotBlank
#Size(max = 45)
private String firstname;
#NotBlank
#Size(max = 45)
private String lastname;
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#NotBlank
#Size(max = 64)
private String phone;
private Set<String> roles;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
}
and when I use this class, I'm doing this:
Set<String> roleSetString = signUpRequest.getRoles();
Every attribute is fine, except this roles attribute, I keep get Null value for this.
Here is my controller where call the signUpRequest:
#PostMapping("/signup")
public ResponseEntity<?> regietserUser(#Valid #RequestBody SignupRequest signUpRequest) {
if (userRepo.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity.badRequest().body(new ReturnMessageResponse("Error: Username is already exist!"));
}
if (userRepo.existsByEmail(signUpRequest.getEmail())) {
return ResponseEntity.badRequest().body(new ReturnMessageResponse("Error: Email is already used"));
}
User user = new User(signUpRequest.getUsername(), signUpRequest.getFirstname(), signUpRequest.getLastname(),
encoder.encode(signUpRequest.getPassword()), signUpRequest.getEmail(), signUpRequest.getPhone());
Set<String> roleSetString = signUpRequest.getRoles();
Set<Role> roles = new HashSet<>();
//if there are no roll specific
System.out.println(roleSetString);
if (roleSetString == null) {
Role userRole = roleRepo.findByName("User")
.orElseThrow(() -> new RuntimeException("Error: Role user is missing/not found"));
roles.add(userRole);
} else {
roleSetString.forEach(role -> {
switch (role) {
case "Admin":
Role adminRole = roleRepo.findByName("Admin")
.orElseThrow(() -> new RuntimeException("Error: Role Admin is not found."));
roles.add(adminRole);
break;
case "Manager":
Role managerRole = roleRepo.findByName("Manager")
.orElseThrow(() -> new RuntimeException("Error: Role Manager is not found."));
roles.add(managerRole);
break;
case "User":
Role userRole = roleRepo.findByName("User")
.orElseThrow(() -> new RuntimeException("Error: Role User is not found."));
roles.add(userRole);
break;
}
});
}
user.setRoles(roles);
userRepo.save(user);
return ResponseEntity.ok(new ReturnMessageResponse("User registered successfully!!"));
}
But as I pring out the roleSetString, it still return null,which means the getRoles() can not return me the role value, which I pass through json Array.
Any suggestions guys?

How/Where are you mapping each JSON field to class field? The problem is likely there.
Also there doesn't seem to be any annotations on your roles field in your class (unlike other fields), could this effect it?

Related

How to check if one user have already column with same value

I have a two tables: User and Wallet
User have: id
Wallet have: userId, walletName
Now, I want to avoid that so user cant have two wallets with same name.
I create something but it applies to all users, so if user with id 1 create a wallet with name walletSaving no-one can create wallet with that name, while I want to avoid that, I want to create something to check whether the user with id 1 have already wallet with that name.
So far I have this:
if (walletRepository.existsByWalletName(walletRequest.getWalletName())) {
return ResponseEntity.badRequest().body(new MessageResponse("You already have wallet with that name, choose another!"));
}
After some help I tried with something like this:
#PostMapping("/user/{user_id}/wallets")
public ResponseEntity<?> createWallet(#PathVariable(value = "user_id") Long user_id,
#RequestBody Wallet walletRequest, User user) {
if (walletRepository.existsByUserIdAndWalletName(user.getId(), walletRequest.getWalletName())) {
return ResponseEntity.badRequest()
.body(new MessageResponse("You already have wallet with that name, choose another!"));
}
Its still creating wallets with same name.
Just to provide more info.
User entity
#Entity
#Table(name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
#UniqueConstraint(columnNames = "email")
})
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
#Size(min = 3, max = 20)
private String username;
#NotEmpty
#Size(max = 50)
#Email
private String email;
#NotEmpty
#Size(min = 6)
private String password;
#NotEmpty(message = "Please, insert a first name")
private String firstName;
#NotEmpty(message = "Please, insert a last name")
private String lastName;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String username, String email, String password, String firstName, String lastName) {
this.username = username;
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Wallet entity
#Entity
#Table(name = "wallet")
public class Wallet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty(message = "Please, insert a wallet name")
private String walletName;
private double initialBalance;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private User user;
public Wallet() {
}
public Wallet(String walletName, double initialBalance) {
this.walletName = walletName;
this.initialBalance = initialBalance;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getWalletName() {
return walletName;
}
public void setWalletName(String walletName) {
this.walletName = walletName;
}
public double getInitialBalance() {
return initialBalance;
}
public void setInitialBalance(double initialBalance) {
this.initialBalance = initialBalance;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Wallet Repository
boolean existsByUserIdAndWalletName(Long userId, String walletName);
You need to include the userId in your query:
final long userId = getUserId(); // get the currently authenticated user's id
if (walletRepository.existsByUserIdAndWalletName(userId, walletRequest.getWalletName())) {
return ResponseEntity.badRequest()
.body(new MessageResponse("You already have wallet with that name, choose another!"));
}
existsByUserIdAndWalletName(userId, walletName);
or
findByUserIdAndWalletName(userId, walletName);
If id of the user and walletName is provided, it will check only for that user if it has that wallet name or not, and if in that situation returns something (true or result>0), that will mean that for that specific user the wallet name is already taken.
https://www.baeldung.com/spring-data-derived-queries#multiple-condition-expressions

Hibernate adds unnecessary row in role table after user registration

I'm trying to add a functionality to my webapp with user registration. Webapp is based on spring boot, hibernate and mysql database, frontend is in angular. Generally, the user creation procedure is working correctly, user data is correctly send from frontend to backend via json and saved to the database in shop_user table (with all the user data, such as name, surname, address etc.), but it DOESN'T have role column.
I also have table 'role', which should be:
id name
1 USER
2 ADMIN
and joined table user_role, which consists of user_id from table shop_user and role id from table role, so it should look like this:
id_user id_role
1 2
2 1
3 1
When user is being created on the website, it is hard-coded to set the role by default to USER. This seems to work quite well as it adds a new row in shop_user, and it adds a row to user_role, but... it also creates a new row in 'role' table.
so in the end 'role' table looks like this:
id name
1 ADMIN
2 USER
3 USER
4 USER
5 USER
99 USER
`
while this is not a blocking bug that stops application from working, it is not 'as it should work' unfortunately... as the table should only consist of two role rows (and possibly additional ones, in the future), but not multiplicated for each user!
here's the flawed code of user:
User
#Entity
#Table(name = "shop_user")
public class User extends AbstractEntity {
#Column
private String firstName;
#Column
private String lastName;
#Column
private String addressLine;
#Column
private String city;
#Column
private String country;
#Column
private String zipCode;
#Column
private String phoneNumber;
#Column
private String email;
#Column
private String password;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "user_role",
joinColumns = #JoinColumn(name = "id_user", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "id_role", referencedColumnName = "id"),
uniqueConstraints = {#UniqueConstraint(columnNames = {"id_user", "id_role"})})
private List<Role> roles;
public User() {
}
public User(User user) {
setId(user.getId());
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.addressLine = user.getAddressLine();
this.city = user.getCity();
this.country = user.getCountry();
this.zipCode = user.getZipCode();
this.phoneNumber = user.getPhoneNumber();
this.email = user.getEmail();
this.password = user.getPassword();
this.roles= user.getRoles();
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
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 getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Role implementation:
Role
#Entity
#Table(name = "role")
public class Role extends AbstractEntity {
#Column
private String name;
#ManyToMany(mappedBy = "roles", cascade = CascadeType.PERSIST)
private List<User> users;
public Role(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
Abstract entity:
AbstractEntity
#MappedSuperclass
public abstract class AbstractEntity implements Persistable<Long> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public void setId(Long id) {
this.id = id;
}
#Override
public Long getId() {
return id;
}
#Override
public boolean isNew() {
return id == null;
}
}
User service:
UserServiceImpl
#Service
public class UserServiceImpl extends AbstractServiceImpl<User, UserDTO> implements UserService {
private final UserRepository userRepository;
private final UserConverter userConverter;
public UserServiceImpl(UserRepository userRepository, UserConverter
userConverter) {
this.userRepository = userRepository;
this.userConverter = userConverter;
}
#Override
protected JpaRepository<User, Long> getRepository() {
return userRepository;
}
#Override
protected Converter<User, UserDTO> getConverter() {
return userConverter;
}
#Override
#Transactional
public User registerUser(User user) {
List<Role> roles = new LinkedList<>();
roles.add(new Role("USER"));
user.setRoles(roles);
return userRepository.save(user);
}}
I am nearly sure that this comes to the relations mapping in Hibernate and object creation, but can't quite figure it out...
Any help will be appreciated, thank you!
The issue is here:
#Override
#Transactional
public User registerUser(User user) {
List<Role> roles = new LinkedList<>();
roles.add(new Role("USER"));
user.setRoles(roles);
return userRepository.save(user);
}}
Since the relationship User -> Role is cascade persist, the (new) role new Role("USER") is also persisted and you ended up with a new Role for each user instead of reusing the existing one.
The solution is to check the existence of a Role with name = USER. If doesn't exist, insert it. Otherwise add the existent one to the roles collection.

Creating an instance of a class and at the same time create an instance of another class that depends on the first class [duplicate]

This question already has answers here:
Hibernate: duplicate key value violates unique constraint
(4 answers)
Closed 6 years ago.
EDIT:How is this question different from the one linked?
I think this question is different because it seems as if it is caused by JPA trying to add another user with the same id, because of a foregin key value in the class (Student) being added. The issue linked seems to be caused by not generateing the ids automatically.
I have a method that creates a User and returns a User. I pass this User to another method to create a Student. The user is a student. But I can't do this because I get :
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "pk_user_id"
Detail: Key (user_id)=(7001) already exists.
My methods in the backing bean looks like this:
public Users2 addUser(String username, String password, String emailadress,
String firstname, String lastname) {
Users2 u = new Users2();
u.setUsername(username);
u.setPassword(password);
u.setEmailaddress(emailadress);
u.setFirstname(firstname);
u.setLastname(lastname);
System.out.println(em + ": Adding course " + u);
em.persist(u);
em.flush();
System.out.println(u.getUser_id());
return u;
}
public void addStudent(Users2 u2) {
Student s = new Student();
s.setUser_id(u2.getUser_id());
s.setUsername(u2.getUsername());
s.setLastname(u2.getLastname());
s.setFirstname(u2.getFirstname());
s.setPassword(u2.getPassword());
s.setEmailaddress((u2.getEmailaddress()));
em.persist(s);
}
My method in the Jsf bean looks like this:
#Inject
DbStore store;
public String CreateUser(){
long usrid;
String username = this.username;
String password = this.password;
String emailadress = this.emailaddress;
String firstname = this.firstname;
String lastname = this.lastname;
Users2 u1 = store.addUser(username, password, emailadress, firstname, lastname);
//System.out.println(usrid);
String role = this.role;
if(this.role.equals("Student"))
store.addStudent(u1);
return "admin_listcourses.xhtml";
}
My entities:
import javax.persistence.Id;
import javax.validation.constraints.Max;
import java.util.List;
import java.util.Set;
#Entity
#Table(name = "student")
#SecondaryTable(name = "users2", pkJoinColumns=#PrimaryKeyJoinColumn(name="user_id", referencedColumnName="user_id"))
public class Student {
/**
* Created by Elev1 on 2016-08-25.
*
*/
#Id
#SequenceGenerator(name="student_student_id_seq",
sequenceName="student_student_id_seq",
allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator="seq")
#Column(name = "student_id", updatable=false)
private long student_id;
#Column(table="users2", name="username")
private String username;
#Column(table="users2", name="firstname")
private String firstname;
#Column(table="users2", name="lastname")
private String lastname;
#Column(table="users2", name="password")
private String password;
#Column(table="users2", name="emailaddress")
private String emailaddress;
#Column(table="users2", name="user_id")
private long user_id;
#ManyToMany
#JoinTable(name="student_course",
joinColumns=
#JoinColumn(name="student_id", referencedColumnName="student_id"),
inverseJoinColumns=
#JoinColumn(name="course_id", referencedColumnName="course_id")
)
// public List<Course> getCourses() { return courses ; }
public List<Course> courses;
//Getters and setters
public long getStudent_id() {
return student_id;
}
public void setStudent_id(long student_id) {
this.student_id = student_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public long getUser_id() {
return user_id;
}
public void setUser_id(long user_id) {
this.user_id = user_id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
}
package se.lexicon.entities;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
public class Users2{
// ***********************
// ** Attributes **
// ***********************
#Id
#SequenceGenerator(name="users_user_id_seq",
sequenceName="users_user_id_seq",
allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator="seq")
private Long user_id;
#Column(name = "username", length = 64)
private String username;
private String password;
#Column(name = "emailaddress", length = 64)
private String emailaddress;
#Column(name = "firstname")
private String firstname;
#Column(name = "lastname")
private String lastname;
#Temporal(TemporalType.TIMESTAMP)
private Date last_login;
// ************************
// ** Constructors **
// ************************
// public User() {
// public User(Long user_id) {
// this.user_id = user_id;
// }
// public User(Long user_id, String username, String password, String emailaddress, ??? last_login) {
// this.user_id = user_id;
// this.username = username;
// this.password = password;
// this.emailaddress = emailaddress;
// this.last_login = last_login;
//}
// ******************************
// ** Getters & Setters **
// ******************************
public long getUser_id() {
return user_id;
}
public void setUser_id(long user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public Date getLast_login() {
return last_login;
}
public void setLast_login(Date last_login) {
this.last_login = last_login;
}
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;
}
//}
}
EDIT: My solution. I removed the foregin_key constraint in the student table. I only kept student_id, course_id and user_id in the Student class. I removed all connections between Student and Users2 in the Student class, instead I use methods to get those from the Users2 class if a student_id is given. When a user is created, that is a Student, then a Student is added with the user_id of the user set as the user_id of the Student.
Now this isn't a very good solution, so if some one can solve my original problem I would be happy to accept the solution. But for now my solution will have to do.
When you persist a Student instance JPA will also create a row in the Users2 table with the user_id as foreign key to the row in the Student table. But there is already a row with the very same ID in the Users2, as you persisted a Users2 instance just before. That's the reason, why you are facing this SQLException.
To me it does not make much sense to use the SecondaryTable-approach here, as there might me Users which are no Students at all, right? But in your current model the Users table is storing a Foreign Key to the Student table..
In this case here it seems to be more appropriate to use inheritance (or maybe some composition) here, instaead of the SecondaryTable-approach.
A Student is-a User, so Student may inherit from User.
You will find a first overview how to define the mapping in this case here: https://en.wikibooks.org/wiki/Java_Persistence/Inheritance

JerseyTest field becomes NULL in resource

For some strange reason a field of my entity has been changed to NULL in my resource.
User Entity
The User entity contains: userName, firstName, lastName, email. The JerseyTest instantiates a new User object:
newUser = new User();
newUser.setEmail(getEmail());
newUser.setFirstName("Erwin");
newUser.setLastName("Eberhard");
newUser.setUserName("abc");
Send entity in test
Before sending the data, the log in the test tells me:
[main] INFO feature.AccountStepDefinition - Erwin Eberhard erwin
erwineberhard#gmail.com
Everthing seems to be OK, so the test sends the data to the resource:
logger.info(newUser.toString());
responseUser = target("auth/register").request().post(Entity.json(newUser), User.class);
AccountResource
The AccountResource retrieves the user, and the log tells us:
[qtp1533672820-20] INFO nl.bolt.ffinschrijven.controllers.AccountsController
- Erwin Eberhard null erwineberhard#gmail.com
For some reason the username has been changed in NULL.
Method in AccountResource
#POST
#Path("/register")
#ApiOperation(value = "Register user.", notes = "After registration a JWT token has been added as header value.")
#ApiResponse(code = 200, message = "", response = User.class, responseHeaders = #ResponseHeader(name = "X-FFI-AUTH", description = "Token generated after authentication", response = String.class) )
#Consumes("application/json")
public Response callback(User user) {
logger.info(user.toString());
ServiceResult serviceResult = accountService.register(user);
if (serviceResult.serviceState == ServiceState.success) {
String jwt = "Bearer " + JwtHelper.createJWT(UUID.randomUUID().toString(), ApiConfiguration.issuer,
user.getEmail(), Long.valueOf(ApiConfiguration.token_ttl));
return Response.status(201).entity(serviceResult.content).header("Authorization", jwt).build();
}
if (serviceResult.serviceState == ServiceState.invalid) {
return Response.status(400).entity(serviceResult.responseMessages.toString()).build();
}
return Response.status(500).build();
}
Postman
When I send the data with POSTMAN, there is no problem:
Headers
Content-Type application/json
Raw content
{
"firstName": "Erwin",
"lastName" : "Eberhard",
"email" : "erwin#gmail.com",
"userName": "erwineberhard"
}
How to get the beloved 201 with my JerseyTest?
UPDATE 1
User.class
The User class extends from a generic User class:
#Entity
#Table
public class User extends GenericUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private List<Eventcomponent> eventcomponents =
new ArrayList<Eventcomponent>();
public Long getId() {
return id;
}
#Override
public String toString(){
return this.getFirstName() + " " + this.getLastName() + " " + this.getUserName()
+ " " + this.getEmail();
}
}
GenericUser.class
#MappedSuperclass
public abstract class GenericUser implements IEmail{
#NotNull(message="Gebruikersnaam niet meegegeven.")
#Column(name="userName", nullable = false)
protected String userName;
#NotNull(message="Email niet meegegeven.")
#Column(name="email", nullable = false)
protected String email;
#NotNull(message="Voornaam niet meegegeven.")
#Column(name="firstName", nullable = false)
protected String firstName;
#NotNull(message="Achternaam niet meegegeven.")
#Column(name="lastName", nullable = false)
protected String lastName;
#Column(name="locked", nullable = false)
protected Boolean locked;
protected String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
}
Looks like the protected getUserName() is the problem. The serializer can't find the userName property when serializing, so there is no field in the JSON of that property name, when it goes out. When the server gets the JSON there is no "userName" field, so it stays null in the server side object. To fix it, just make the method public.

Spring MVC BindingResult

The bindingResult.hasError() results to true even though the field is not empty or does not have any white spaces. I would like to know what am I missing here.-----------------------------------------------------------
This is my controller
#RequestMapping(value = "/login",method = RequestMethod.POST)
public ModelAndView login(#ModelAttribute("user")User user, BindingResult bindingResult,
HttpServletRequest request, HttpServletResponse response,
#RequestParam("usernametxt") String username, #RequestParam("passwordtxt") String password)
{
try
{
// Using Spring ValidationUtils class to check for empty fields.
// This will add the error if any in the bindingResult object.
ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult,"userName","usernametxt", "Username cannot be empty.");
ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult,"password","passwordtxt", "Password should not be empty");
if (bindingResult.hasErrors())
{
//returning the errors on same page if any errors..
return new ModelAndView("/LoginPage", "user", user);
}
else
{
// If the user details is validated then redirecting the user to success page,
// else returning the error message on login page.
ServiceFacade facade = new ServiceFacadeImpl();
List<User> userList = facade.getAllUsers();
for(int index = 0; index < userList.size(); index++){
String uname = userList.get(index).getUserName();
String pword = userList.get(index).getPassword();
if(username.equals(uname) && password.equals(pword))
{
request.getSession().setAttribute("user", user);
//Creating a redirection view to success page. This will redirect to UsersController
RedirectView redirectView = new RedirectView("success.do", true);
return new ModelAndView(redirectView);
}
else
{
bindingResult.addError(new ObjectError("Invalid", "Invalid credentials. " +
"Username or Password is incorrect."));
//return new ModelAndView("login", "user", user);
}
}
}
} catch (Exception e) {
System.out.println("Exception in LoginController "+e.getMessage());
e.printStackTrace();
return new ModelAndView("/LoginPage", "user", user);
}
return null;
}
EDIT 1
USER BEAN
package com.nutsaboutcandywebproject.model;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "users", catalog = "db_nutsaboutcandy")
public class User {
private int userId;
private String username;
private String firstname;
private String lastname;
private String password;
private String role;
private String address;
public User(){
}
public User(int userId, String username, String firstname,
String lastname, String password, String role, String address) {
super();
this.userId = userId;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.role = role;
this.address = address;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "user_id", unique = true, nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#Column(name = "username", nullable = false)
public String getUserName() {
return username;
}
public void setUserName(String username) {
this.username = username;
}
#Column(name = "firstname", nullable = false)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name = "lastname", nullable = false)
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
if(password.length()>=6){
this.password = password;
}
else{
throw new IllegalArgumentException("Password length must be more than 6 characters");
}
}
#Column(name = "user_role", nullable = false)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Column(name = "address", nullable = false)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

Categories