In my Google Web Toolkit project, I got the following error:
Type 'com.example.model.User_$$_javassist_1' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = com.example.model.User#1dc2baa
What are the possible causes of this error?
package com.example.model;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String username;
private String fullname;
private String firstname;
private String lastname;
private String password;
private String picture;
private String adresse;
private String email;
private Integer telephone;
private Integer fax;
private String role;
public User() {
}
public User(Integer id, String username, String fullname, String firstname,
String lastname, String password, String picture, String adresse,
String email, Integer telephone, Integer fax, String role) {
this.id = id;
this.username = username;
this.fullname = fullname;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
this.picture = picture;
this.adresse = adresse;
this.email = email;
this.telephone = telephone;
this.fax = fax;
this.role = role;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTelephone() {
return telephone;
}
public void setTelephone(Integer telephone) {
this.telephone = telephone;
}
public Integer getFax() {
return fax;
}
public void setFax(Integer fax) {
this.fax = fax;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
package com.example.model;
import java.io.Serializable;
import java.util.Date;
public class Projet implements Serializable {
private Integer id;
private User user;
private String name;
private String description;
private String abrevation;
private Date dateDebut;
private Date dateFin;
private Date realDateDeb;
private Date realDateFin;
private String icone;
private Double budget;
private Double tauxTva;
public Projet() {
}
public Projet(Integer id, User user,
String name, String description,
String abrevation, Date dateDebut, Date dateFin, Date realDateDeb,
Date realDateFin, String icone, Double budget, Double tauxTva) {
this.id = id;
this.user = user;
this.name = name;
this.description = description;
this.abrevation = abrevation;
this.dateDebut = dateDebut;
this.dateFin = dateFin;
this.realDateDeb = realDateDeb;
this.realDateFin = realDateFin;
this.icone = icone;
this.budget = budget;
this.tauxTva = tauxTva;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAbrevation() {
return abrevation;
}
public void setAbrevation(String abrevation) {
this.abrevation = abrevation;
}
public Date getDateDebut() {
return dateDebut;
}
public void setDateDebut(Date dateDebut) {
this.dateDebut = dateDebut;
}
public Date getDateFin() {
return dateFin;
}
public void setDateFin(Date dateFin) {
this.dateFin = dateFin;
}
public Date getRealDateDeb() {
return realDateDeb;
}
public void setRealDateDeb(Date realDateDeb) {
this.realDateDeb = realDateDeb;
}
public Date getRealDateFin() {
return realDateFin;
}
public void setRealDateFin(Date realDateFin) {
this.realDateFin = realDateFin;
}
public String getIcone() {
return icone;
}
public void setIcone(String icone) {
this.icone = icone;
}
public Double getBudget() {
return budget;
}
public void setBudget(Double budget) {
this.budget = budget;
}
public Double getTauxTva() {
return tauxTva;
}
public void setTauxTva(Double tauxTva) {
this.tauxTva = tauxTva;
}
}
<hibernate-mapping>
<class name="com.example.model.Projet" table="PROJET" lazy="true">
<id name="id" column="PROJET_ID">
<generator class="native"/>
</id>
<property name="name"/>
<property name="description"/>
<property name="abrevation"/>
<property name="dateDebut"/>
<property name="dateFin"/>
<property name="realDateDeb"/>
<property name="realDateFin"/>
<property name="icone"/>
<property name="budget"/>
<property name="tauxTva"/>
<!--
-->
<many-to-one name="user" class="com.example.model.User" fetch="select">
<column name="USER_ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.example.model.User" table="USER" lazy="true">
<id name="id" column="USER_ID">
<generator class="native"/>
</id>
<property name="username"/>
<property name="fullname"/>
<property name="firstname"/>
<property name="lastname"/>
<property name="password"/>
<property name="picture"/>
<property name="adresse"/>
<property name="email"/>
<property name="telephone"/>
<property name="fax"/>
<property name="role"/>
</class>
</hibernate-mapping>
Related
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());
}
});
}
}
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"
}
File structure I have a flat file which has two types of data. such as I have a Comma delimited file that has information of a students. There are multiple files like class A students, class B students etc.
Data in file is like first line has the class information and the rest has student information. So I want to put the class information to class table and student information to student table.
First line would always be of HeaderDataDAO type and all other would be of StudentDataDAO.
How can I achieve this?
My File structure
Class-A*10*2013-14
1*Stone*Barrett*1964-10-19
2*Armando*Stone*1973-02-04****
3*Armando*Logan*1986-12-25
4*Latifah*Barnett*1959-07-24
5*Cassandra*Moses*1956-09-14*********
6*Audra*Hopkins*1984-08-30
7*Upton*Morrow*1973-02-04
8*Melodie*Velasquez*1953-04-26
9*Sybill*Nolan*1951-06-24*****
10*Glenna*Little*1953-08-27
StudentDataDAO.java
public class StudentDataDAO {
private long id;
private String firstName;
private String lastName;
private Date birthDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) throws ParseException {
if (!birthDate.equalsIgnoreCase("")) {
SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd");
this.birthDate = spf.parse(birthDate);
} else {
this.birthDate = null;
}
}
#Override
public String toString() {
return "CustomerData [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", birthDate=" + birthDate
+ "]";
}
}
HeaderDataDAO.java
public class HeaderDataDAO {
private String className;
private String numberOfStudent;
private String batch;
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getNumberOfStudent() {
return numberOfStudent;
}
public void setNumberOfStudent(String numberOfStudent) {
this.numberOfStudent = numberOfStudent;
}
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
#Override
public String toString() {
return "HeaderData [className=" + className + ", numberOfStudent=" + numberOfStudent + ", batch=" + batch + "]";
}
}
You can use CompositeItemWriter below is sample config
<bean id="compositeWriter"
class="org.springframework.batch.item.support.CompositeItemWriter">
<property name="delegates">
<list>
<ref bean="classWriter" />
<ref bean="studentWriter" />
</list>
</property>
</bean>
Using CompositeItemWriter. Find sample over here: https://github.com/spring-projects/spring-batch/blob/master/spring-batch-samples/src/main/resources/jobs/compositeItemWriterSampleJob.xml
http://grepcode.com/file/repo1.maven.org/maven2/org.springframework.batch/spring-batch-samples/1.0.1.RELEASE/jobs/compositeItemWriterSampleJob.xml
i'm starting with Rest and don't have no idea how to implement it properly. I got an exercise: i must implement a Rest-Client with the RestClient-API from javax.ws.rs standard library and i tried by using the code below, but i'm getting a null pointer exception. But the resource are there and when i try directly from the browser (http://localhost:8080/sep/rest/customers/112). Now my question how can i do it properly. Some constraints, i must use XML (not JSON) for the Data-support.
Hier my client-code:
public Response createCustomer(Customer customer){
log.info("Starting: Rest Create a Customer with Name: " + Customer.class.getName());
this.customerWebTarget = this.client.target(URL);
Response response = this.customerWebTarget.request().
buildPost(Entity.entity(customer, MediaType.APPLICATION_XML)).invoke();
log.info("Ending: Rest Create a Customer with Name: " + response.getEntity().getClass().getName());
return response;
}
CustomerResource-Code:
#Path("customers")
public class CustomerResource implements IAllowedMethods<Customer> {
private static final long serialVersionUID = -6367055402693237329L;
private Logger logger = Logger.getLogger(CustomerResource.class.getName());
#Inject
private CustomerService service;
public CustomerResource() {
logger.info("create of instance " + this.getClass().getName());
}
#Override
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response get() {
List<Customer> list = service.loadAll(Customer.FINDALL, Customer.class);
if (list != null && !list.isEmpty()) {
ResponseCustomerList responseList = new ResponseCustomerList();
responseList.setList(list);
return Response.ok(responseList).build();
}
return Response.status(Status.NOT_FOUND).build();
}
.
.
.
Customer Code:
import de.ostfalia.sep.adapter.XMLIntegerAdapter;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
private static final long serialVersionUID = 80668466040239995L;
#XmlID
#XmlJavaTypeAdapter(XMLIntegerAdapter.class)
private Integer customerNumber;
private String customerName;
private String contactLastName;
private String contactFirstName;
private String phone;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String postalCode;
private String country;
#XmlIDREF
private Employee salesRepEmployee;
private BigDecimal creditLimit;
private Set<Payment> payments;
private Set<Order> orders;
public Customer() {
}
public Customer(Integer customernumber) {
this.customerNumber = customernumber;
}
public Customer(Integer customerNumber, String customerName, String contactLastName, String contactFirstName,
String phone, String addressLine1, String city, String country) {
this.customerNumber = customerNumber;
this.customerName = customerName;
this.contactLastName = contactLastName;
this.contactFirstName = contactFirstName;
this.phone = phone;
this.addressLine1 = addressLine1;
this.city = city;
this.country = country;
}
public Integer getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(Integer customerNumber) {
this.customerNumber = customerNumber;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getContactLastName() {
return contactLastName;
}
public void setContactLastName(String contactLastName) {
this.contactLastName = contactLastName;
}
public String getContactFirstName() {
return contactFirstName;
}
public void setContactFirstName(String contactFirstName) {
this.contactFirstName = contactFirstName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Employee getSalesRepEmployee() {
return salesRepEmployee;
}
public void setSalesRepEmployee(Employee salesRepEmployee) {
this.salesRepEmployee = salesRepEmployee;
}
public BigDecimal getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(BigDecimal creditLimit) {
this.creditLimit = creditLimit;
}
#Override
public int hashCode() {
int hash = 0;
hash += (customerNumber != null ? customerNumber.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerNumber == null && other.customerNumber != null)
|| (this.customerNumber != null && !this.customerNumber.equals(other.customerNumber))) {
return false;
}
return true;
}
#Override
public String toString() {
return customerNumber.toString();
}
public Set<Payment> getPayments() {
return payments;
}
public void setPayments(Set<Payment> payments) {
this.payments = payments;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
Instead of response.getEntity(), use response.readEntity(String.class) to get the data as a String. If you want to deserialize it to a POJO, then just pass that class to the readEntity.
Also you should make sure to check the status code (response.getStatus()) to make sure it's a success status.
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)