I am considering now the example "Registration, entry through the spring" https://hellokoding.com/registration-and-login-example-with-spring-xml-configuration-maven-jsp-and-mysql/

When registering a new user, after clicking the Submit button, the method that takes in the database ALL existing ROLE (now I have created ROLE_USER and ROLE_ADMIN) and adds them to the user automatically works. java security

Question: I can not understand how to send only ROLE_USER to the method, so that the user is automatically created with it, and ROLE_ADMIN is added manually.

Here's an example: https://github.com/hellokoding/registration-login-spring-xml-maven-jsp-mysql

Here is the method that is responsible for saving the new user. https://github.com/hellokoding/registration-login-spring-xml-maven-jsp-mysql/blob/master/src/main/java/com/hellokoding/account/service/UserServiceImpl.java#L24

I tried to pull the first value from the list through new HashSet<>(roleRepository.findAll()) and get(0) , but it didn’t work, it requires that we give it the data type "Role", and I’m not much I can understand how the code should look like.

I would be grateful for any hint. Thank.

  • Look for the role of user ID and assign. - Vartlok

1 answer 1

I suspect that you could pass a Role to the HashSet designer, not their collection. It should be something like this:

  Role roleUser = roleRepository.findOne(1L); // если ROLE_USER гарантирована с id=1 // Role roleUser = roleRepository.findOneByName("ROLE_USER"); // альтернативный вариант Set<Role> roles = new HashSet<>(); // т.к. User.setRoles требует Set roles.add(roleUser); // создадим Set с одним значением user.setRoles(roles); 
  • Thank. Your code came up. I also saw the problem, your phrase helped with "// because User.setRoles requires Set", tested it on the eve and put HashSet in there, and tried to pull out the first value from the hashset. Do not tell me why it did not work out for me? - Tryserg
  • Prompt, roleRepository.findAll() found all values. new HashSet<>(roleRepository.findAll()) - everything found is pushed into the HashSet collection. User.setRoles требует Set - but previously, HashSet was also quietly in there, how so? - Tryserg
  • one
    Set - the interface, HashSet implements the interface Set - Ruslan P.