save data to the database using spring boot - rest

when I post the data using the postman, the server replies with error code 500. the NetBeans terminal show:(java.sql.SQLIntegrityConstraintViolationException: Column 'email' cannot be null)
bellow my entityclass:
#Entity(name="user")
public class UserEntity {
#Id
#GeneratedValue
private long id;
#Column(nullable = true)
private String userId;
#Column(nullable = true)
private String FirstName;
#Column(nullable = true)
private String LastName;
#Column(nullable = true)
private String Email;
#Column(nullable = true)
private String Password;
#Column(nullable = true)
private String encryptedPassword;
#Column()
private String emailVerificationToken;
#Column()
private Boolean emailVerificationStatus=false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
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 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 getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
bellow is my service implementation class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.mobile.demo.impl;
import com.example.mobile.demo.DTo.UserDto;
import com.example.mobile.demo.Entity.UserEntity;
import com.example.mobile.demo.repository.UserRepository;
import com.example.mobile.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* #author iphone
*/
#Service
public class UserserviceImpl implements UserService{
#Autowired
UserRepository userRepository;//it is in the data layer so we need the repository to save in the database
#Override
public UserDto createuser(UserDto user) {
UserEntity userentity=new UserEntity();
BeanUtils.copyProperties(user, userentity);
System.out.println("the properties has been copied to the entity");
userentity.setEncryptedPassword("test");
userentity.setUserId("testID");
System.out.println("encryptef passwird and user id has been set");
UserEntity stotedValue=userRepository.save(userentity);
UserDto returnValue=new UserDto();
BeanUtils.copyProperties(stotedValue, returnValue);
return returnValue;
}
}
my model class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.mobile.demo.modoel;
/**
*
* #author iphone
*/
public class Model {
private String FirstName;
private String LastName;
private String Email;
private String Password;
public String getFirstName() {
return FirstName;
}
public void setFistName(String FirstName) {
this.FirstName = FirstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
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;
}
}
bellow is what Iam sending in the post request in the postman:
{
"FirstName":"jack",
"LastName":"testjack",
"Password":"124",
"Email":"emailTest#gmail.com"
}

The issue is in json to java Model mapping.
You need to rename your Model.java properties in this way:
Email -> email
FirstName -> firstName
Or add #JsonProperty("name"):
#JsonProperty("email")
private String Email;
Don't forget json changes, if you choose properties renaming:
{
"firstName":"jack",
"lastName":"testjack",
"password":"124",
"email":"emailTest#gmail.com"
}

Related

How to achieve MVVM + Live Data with retofit generic Api call in Android?

I want to create retrofit2 generic Api call in MVVM Architechture. I have not found any proper tutorial regardng this topic. I have done MVVM Architecture successfully . but I want to make Retrofit Api call generic through out the Application .Please help me out.
here is my code Repository
public class MainRepository {
// private List<ContactList> users = new ArrayList<>();
private MutableLiveData<ContactList> mutableLiveData = new MutableLiveData<>();
private Application application;
public MainRepository(Application application) {
this.application = application;
}
public MutableLiveData<ContactList> getMutableLiveData() {
Retrofit retrofit = ApiClient.getClient();
ApiListInterface apiListInterface = retrofit.create(ApiListInterface.class);
Call<ContactList> call = apiListInterface.getContacts();
call.enqueue(new Callback<ContactList>(){
#Override
public void onResponse(Call<ContactList> call, Response<ContactList> response) {
ContactList contactLists = response.body();
if (contactLists != null ) {
// users = (List<ContactList>) contactLists.ge;
mutableLiveData.setValue(contactLists);
}
}
#Override
public void onFailure(Call<ContactList> call, Throwable t) {
Log.d("ListSize"," - > Error "+ t.getMessage());
}
});
return mutableLiveData;
}
}
here is my ViewModel class
public class MainViewModel extends AndroidViewModel {
private MainRepository mainRepository;
public MainViewModel(#NonNull Application application) {
super(application);
mainRepository = new MainRepository(application);
}
public LiveData<ContactList> getAllUsers() {
return mainRepository.getMutableLiveData();
}
}
Here is My all Model class
public class ContactList {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = null;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
public class Contact {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("address")
#Expose
private String address;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("phone")
#Expose
private Phone phone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Phone getPhone() {
return phone;
}
public void setPhone(Phone phone) {
this.phone = phone;
}
}
public class Phone {
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("home")
#Expose
private String home;
#SerializedName("office")
#Expose
private String office;
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
}
Here is My Activity
public class MainActivity extends AppCompatActivity {
private MainViewModel mainViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
getUserList();
}
private void getUserList() {
mainViewModel.getAllUsers().observe(this, new Observer<ContactList>() {
#Override
public void onChanged(ContactList contactLists) {
Log.d("contacts_list",contactLists.getContacts().toString());
}
});
}
}

translate sql to JPQL

i m a total newbie to JPQL ,so i m working on a Spring Boot app and i have this SQL query part :
select TOP 10 RFC_NUMBER, RECIPIENT_ID from [50004].SD_REQUEST S
INNER JOIN [50004].AM_EMPLOYEE E
--ON S.RECIPIENT_ID = E.EMPLOYEE_ID
WHERE E.AVAILABLE_FIELD_5 ='j.doe'
AND SD_REQUEST.STATUS_ID NOT IN (8,6,18,7,24)
AND SD_REQUEST.RFC_NUMBER like 'I%'
to JPQL.
i tried doing a #Query like this :
#Query("select x from Incident x Left join x.recipient recip where recip.login=:login and (x.rfcnumber like :I_% or :rfcnumber = null )"
+ " and x.status NOT IN (8,6,18,7,24)")
but it only returns ALL the rfcnumber of the that employee , i want it to extract only the rfc number starting with letter I ,
i tried doing CONCAT from searching around in then web, same thing.
i m new to this so i figure it'll be something much simpler , i m thinking it's just syntax problem .
Thanks a bunch.
Edit (adding models):
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="SD_REQUEST")
public class Incident implements Serializable {
private static final long serialVersionUID = -8235081865121541091L;
#Id
#Column(name="REQUEST_ID")
private Integer inid;
#ManyToOne
#JoinColumn(name = "SUBMITTED_BY")
private Employee sender;
#Column(name="RFC_NUMBER")
private String rfcnumber;
#Column(name="CREATION_DATE_UT")
private Date date;
#Column(name="DESCRIPTION")
private String description;
#Column(name="COMMENT")
private String comment;
#Column(name="STATUS_ID")
private Integer status;
#ManyToOne
#JoinColumn(name = "RECIPIENT_ID")
private Employee recipient;
public Incident()
{
}
public Incident(int inid,String rfcnumber,Date date,String description,String comment,Integer status)
{
this.inid=inid;
this.rfcnumber= rfcnumber;
this.date=date;
this.description=description;
this.comment=comment;
this.status=status;
}
public int getInid() {
return inid;
}
public void setInid(int inid) {
this.inid = inid;
}
public String getRfcnumber() {
return rfcnumber;
}
public void setRfcnumber(String rfcnumber) {
this.rfcnumber = rfcnumber;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Employee getSender() {
return sender;
}
public void setSender(Employee sender) {
this.sender = sender;
}
public Employee getRecipient() {
return recipient;
}
public void setRecipient(Employee recipient) {
this.recipient = recipient;
}
public void setInid(Integer inid) {
this.inid = inid;
}
}
And here's the model for Employee :
import javax.persistence.*;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#Entity
#JsonDeserialize(as =Employee.class)
#Table(name = "AM_EMPLOYEE")
public class Employee implements Serializable {
private static final long serialVersionUID = 5071617893593927440L;
#Id
#Column(name = "EMPLOYEE_ID" )
private Integer id;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "AVAILABLE_FIELD_5")
private String login;
#OneToMany(mappedBy="sender")
#JsonIgnore
private List<Incident> myCreatedIncidents;
#OneToMany(mappedBy="recipient")
#JsonIgnore
private List<Incident> myOtherIncidents;
#Column(name = "PASSWD")
private String password;
public Employee() {
//super();
}
public Employee (String login,String password)
{
}
public Employee(Integer id, String lastName,String login, String password) {
this.id = id;
this.lastName = lastName;
this.login = login;
this.password = password;
}
/**
* #return the id
*/
public Integer getId() {
return id;
}
/**
* #param id
* the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* #return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* #param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #return the login
*/
public String getLogin() {
return login;
}
/**
* #param login
* the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
public List<Incident> getMyCreatedIncidents() {
return myCreatedIncidents;
}
public void setMyCreatedIncidents(List<Incident> myCreatedIncidents) {
this.myCreatedIncidents = myCreatedIncidents;
}
public List<Incident> getMyOtherIncidents() {
return myOtherIncidents;
}
public void setMyOtherIncidents(List<Incident> myOtherIncidents) {
this.myOtherIncidents = myOtherIncidents;
}
}
Hard-coded characters
I think you should use the same as in SQL:
like 'I%'
Specifically, according to the article # http://www.objectdb.com/java/jpa/query/jpql/string#LIKE_-_String_Pattern_Matching_with_Wildcards_ :
The percent character (%) - which matches zero or more of any character.
Blockquote
So try the following:
#Query("select x from Incident x Left join x.recipient recip where recip.login=:login and (x.rfcnumber like 'I%' or :rfcnumber = null )"
+ " and x.status NOT IN (8,6,18,7,24)"
)
Parameters
See the solutions # Parameter in like clause JPQL if you are using a parameter.
Examples:
LIKE :code%
Also other examples are included in the stackoverflow question.
#Query("select x from Incident x where x.recipient.login=:login and (x.rfcnumber like I% or x.rfcnumber = null )"
+ " and x.status NOT IN (8,6,18,7,24))"
try this query

Spring boot CrudRepository save - exception is org.hibernate.type.SerializationException: could not serialize

Not sure why I have an issue here, but when I save with a CrudRepository with these objects, I get the SerializationException (with no further information). Can someone take a look at my objects and offer me some insight into why they can't serialize? My pom.xml is attached last as well in case that helps somehow. I'm using a Postgres database.
EDIT: The database and now - tables are created, but objects are not creating rows.
The actual CrudRepository interface:
public interface AccountRepository extends CrudRepository<ZanyDishAccount, String> {}
ZanyDishAccount entity:
#Entity
public class ZanyDishAccount {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id; // internal id of the customer account for a Zany Dish subscription
private String status;
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "company_id")
private Company company;
#OneToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "order_id")
private Order order;
public ZanyDishAccount() {}
public ZanyDishAccount(Company company, Order order) {
this.company = company;
this.order = order;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+ ", company = " + company + ", status = " + status + "]";
}
}
Company entity:
#Entity
public class Company {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id;
private String phoneNumber;
private String website;
private String name;
private String uuid;
private String country;
public Company() {}
public Company(String phoneNumber, String website, String name, String uuid, String country) {
this.phoneNumber = phoneNumber;
this.website = website;
this.uuid = uuid;
this.country = country;
}
public String getPhoneNumber ()
{
return phoneNumber;
}
public void setPhoneNumber (String phoneNumber)
{
this.phoneNumber = phoneNumber;
}
public String getWebsite ()
{
return website;
}
public void setWebsite (String website)
{
this.website = website;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getUuid ()
{
return uuid;
}
public void setUuid (String uuid)
{
this.uuid = uuid;
}
public String getCountry ()
{
return country;
}
public void setCountry (String country)
{
this.country = country;
}
#Override
public String toString()
{
return "ClassPojo [phoneNumber = "+phoneNumber+", website = "+website+", name = "+name+", uuid = "+uuid+", country = "+country+"]";
}
}
Order entity:
#Entity
#Table(name = "_order")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long id;
private String pricingDuration;
private Items[] items;
private String editionCode;
public Order() {}
public Order(String pricingDuration, Items[] items, String editionCode) {
this.pricingDuration = pricingDuration;
this.items = items;
this.editionCode = editionCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPricingDuration ()
{
return pricingDuration;
}
public void setPricingDuration (String pricingDuration)
{
this.pricingDuration = pricingDuration;
}
public Items[] getItems ()
{
return items;
}
public void setItems (Items[] items)
{
this.items = items;
}
public String getEditionCode ()
{
return editionCode;
}
public void setEditionCode (String editionCode)
{
this.editionCode = editionCode;
}
#Override
public String toString()
{
return "ClassPojo [pricingDuration = "+pricingDuration+", items = "+items+", editionCode = "+editionCode+"]";
}
}
Thanks for your help!
Mike
Hm, this seems multi-faceted. Let's see if I can help at all. Last thing first...
No tables being created automatically.
I would take a look at this section in Spring's docs for the most basic approach: Initialize a database using Hibernate. For example, spring.jpa.hibernate.ddl-auto: create-drop will drop and re-create tables each time the application runs. Simple and easy for initial dev work. More robust would be leveraging something like Flyway or Liquibase.
Serialization issue
So without logs, and the fact that you have no tables created, the lack of a persistence layer would be the assumed culprit. That said, when you have tables and data, if you do not have a repository for all of the related tables, you'll end up with a StackOverflow error (the serialization becomes circular). For that, you can use #JsonBackReference (child) and #JsonManagedReference (parent). I have been successful using only #JsonBackReference for the child.
Items[]
I'm not sure what Item.class looks like, but that looks like an offensive configuration that I missed the first round.
Change private Items[] items; to private List<Item> items = new ArrayList<Item>();. Annotate with #ElementCollection.
Annotate Item.class with #Embeddable.

JavaFX properties fail to persist

I'm using some JavaFX properties in my app:
#Entity(name = "Klanten")
#Table(name = "Klanten")
#NamedQueries({
#NamedQuery(name = "Klanten.findAll", query = "select k from Klanten k")
})
public class Klant implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int klantId;
#Transient
private final SimpleStringProperty naam = new SimpleStringProperty();
//private String naam;
//private String straat;
#Transient
private final SimpleStringProperty straat = new SimpleStringProperty();
private String telefoon;
private String huisnummer;
private String gsm;
private String woonplaats;
private String email;
private String postcode;
#OneToMany(mappedBy = "Klant", cascade = CascadeType.REMOVE)
private List<Raam> ramen;
public Klant() {
}
public Klant(String naam) {
this.naam.set(naam);
}
#Override
public String toString() {
return this.naam.get();
}
#Access(AccessType.PROPERTY)
#Column(name="naam")
public String getNaam() {
return this.naam.get();
}
public void setNaam(String naam){
this.naam.set(naam);
}
public List<Raam> getRamen() {
return this.ramen;
}
#Id
public int getKlantId() {
return klantId;
}
public void setKlantId(int klantId) {
this.klantId = klantId;
}
#Access(AccessType.PROPERTY)
#Column(name="straat")
public String getStraat() {
return straat.get();
}
public void setStraat(String straat) {
this.straat.set(straat);
}
public String getTelefoon() {
return telefoon;
}
public void setTelefoon(String telefoon) {
this.telefoon = telefoon;
}
public String getHuisnummer() {
return huisnummer;
}
public void setHuisnummer(String huisnummer) {
this.huisnummer = huisnummer;
}
public String getGsm() {
return gsm;
}
public void setGsm(String gsm) {
this.gsm = gsm;
}
public String getWoonplaats() {
return woonplaats;
}
public void setWoonplaats(String woonplaats) {
this.woonplaats = woonplaats;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public StringProperty naamProperty() {
return naam;
}
public StringProperty straatProperty() {
return straat;
}
}
However when I let JPA generate my database, the column "naam" and "straat" aren't generated. I get no error. How can I resolve this?
I tried all the things listed here:
Possible solution 1
Possible solution 2
These didn't work.
You can try to use regular properties and then have another get method which returns a new SimpleStringProperty, i.e.:
public StringProperty naamProperty() {
return new SimpleStringProperty(naam);
}
public StringProperty straatProperty() {
return new SimpleStringProperty(straat);
}

In spring security 3,how to customize my # PreAuthorize annotation?

these days I meet a problem, I can not figure it out,so please help me...
My entity: Utilisateur this is a french word means user
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Utilisateur implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected int id;
protected String login;
protected String password;
protected String nom;
protected String prenom;
protected String email;
protected String username;}
#OneToOne(mappedBy="user", cascade={CascadeType.ALL})
private Role role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return login;
}
public void setUsername(String username) {
this.username = username;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
and a Role entity.
In my web app, there is a controller to show for example the information about a student(Etudiant in french)
#EJB(mappedName = "Etudiant.EtudiantFacade")
EtudiantFacade etudiantF;
// Affiche le detail d'un Etudiant (show the infomations of the student)
#RequestMapping(value = "/Etudiant/{idEtudiant}/info")
public ModelAndView detail(#PathVariable String idEtudiant, Model m) {
m.addAttribute("etudiant",
etudiantF.trouver(Integer.parseInt(idEtudiant)));
return new ModelAndView("EtudiantInformation", "null", null);
}
I implemented my own CustomUseDetailService using the entity Utilisateur directly.
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// TODO Auto-generated method stub
System.out.println("!!!!!!!!!!!!!!!!!");
System.out.println(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Utilisateur etudiant = etudiantF.trouverParLogin(username);
return new User(etudiant.getLogin(), etudiant.getPassword(), enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,getAuthorities(etudiant.getRole().getRole()));
}
and my security.xml is below:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/app/Login" access="permitAll"/>
<intercept-url pattern="/app/*" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
<form-login login-page="/app/Login"
authentication-success-handler-ref="authenticationSuccessHandler"/>
<logout logout-url="/app/Logout" logout-success-url="/"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
Last my question is:
for a student, his id is 1, his username is stu1,to control this student with id 1 can only access his own page information /ProjetName/Student/{studentId}/Info
how do I write the code with #PreAuthorize, I have see the document in form spring, there is example like #PreAuthorize(#contract.name = principal.username), because there is a attribute username in principal, but here,what I need is Id, I use #RequestMapping(value = "/Etudiant/{idEtudiant}/info") to match the student not the username. So how can I solve it? Many thanks... I can not find the tutorial.
You can provide your own implementation for User class (just extend org.springframework.security.core.userdetails.User). Add an identifier field to it. Then set corresponding value in loadUserByUsername method:
#Override
public UserDetails loadUserByUsername(String username)
...
return new CustomUser(etudiant.getId(), etudiant.getLogin(), etudiant.getPassword(), enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,getAuthorities(etudiant.getRole().getRole()));
}
Then you will be able to use it:
#PreAuthorize(#contract.name = principal.id)