如何在数据库中正确实现已验证的注册?

pnwntuvh  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(209)

同样的“springboot.model.user.setusername(string)”,因为“users”为null“错误不断出现。错误很明显,它表示不能设置null。我将json数据发送到dto类,在那里我检查它是否在数据库中,如果不在数据库中,然后安装。也许我犯了一个严重的错误,却看不出来。请告诉我需要做什么,如何正确赋值?
错误:

java.lang.NullPointerException: Cannot invoke "com.nor.springboot.model.User.setUsername(String)" because "users" is null
    at com.nor.springboot.service.JwtUserService.register(JwtUserService.java:121) ~[classes/:na]
    at com.coooo.springboot.controller.UserAuthenticationController.registerUser(UserAuthenticationController.java:88) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.8.jar:5.3.8]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.8.jar:5.3.8]

json请求:

{"username":"Ivanov",
"email":"Ivan@mail.com",
"password":"1a234567890"}

答复:

{
    "timestamp": "2021-07-03T18:48:42.872+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/auth/signup"
}

实体:

@Entity
@Table(name="usr",

uniqueConstraints = {
        @UniqueConstraint(columnNames = "username"),
        @UniqueConstraint(columnNames = "email"),
        @UniqueConstraint(columnNames = "phone")
})
public class User extends BaseEntity  {

    @NotBlank(message = "Username cannot be empty")
    @Size(min=3, message="min 3 characters")
    @Column(name = "username")
    private String username;

    @Column(name = "secondName")
    private String secondName;

    @NotBlank(message = "Password cannot be empty")
    @Size(min=8, message="min 8 characters")
    @Column(name = "password")
    private String password;

    @Column(name = "phone")
    private String phone;

    @Column(name = "description")
    private String description;

    @Email(message = "Email is not correct")
    @NotBlank(message = "Email cannot be empty")
    @Column(name = "email")
    private String email;

    @Column(name = "active")
    private boolean active;

    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    private Set<Role> roles;

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSecondName() {
        return companyName;
    }

    public void setSecondName(String companyName) {
        this.companyName = companyName;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

服务注册方法:

public class JwtUserService implements UserDetailsService{

            private UserRepository userRepository;

            private BCryptPasswordEncoder passwordEncoder;

              @Autowired
                public JwtUserService(UserRepository userRepository,  BCryptPasswordEncoder passwordEncoder) {
                    this.userRepository = userRepository;        
                    this.passwordEncoder = passwordEncoder;
              }

@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         User user = userRepository.findByUsername(username);

         if (user == null) {
                throw new UsernameNotFoundException("User with username: " + username + " not found");
            }
          JwtUser jwtUser = JwtUserFactory.create(user);

            return jwtUser;
    }

        public ResponseEntity<?> register(JwtUser user) {

                User users = userRepository.findByUsername(user.getUsername());
                User emails = userRepository.findByEmail(user.getEmail());
             if(users != null && emails !=null) {
                 return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username or email is exist"));

                }

                users.setUsername(user.getUsername()); 
                users.setPassword(passwordEncoder.encode(user.getPassword()));
                users.setRoles(Collections.singleton(Role.USER));
                users.setEmail(user.getEmail());
                users.setActive(true);

                userRepository.save(users);

                return new ResponseEntity<>("User Created!", HttpStatus.OK);

            }

配置:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String LOGIN_ENDPOINT = "/auth/**";

     @Autowired
     private  JwtTokenProvider jwtTokenProvider;

       @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
       }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http 
        .httpBasic().disable()
        .csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers(LOGIN_ENDPOINT).permitAll()       
        .anyRequest().authenticated()
        .and()
        .apply(new JwtConfigurer(jwtTokenProvider));

    }
}

jwt类用户详细信息:

public class JwtUser implements UserDetails {

    private String token;

    private  Long id;

    private  String username;

    private  String secondName;

    private  String password;

    private  String phone;

    private  String description;

    private  String email;

    private  boolean active;

    private  Date lastPasswordResetDate;

    private  Collection<? extends GrantedAuthority> authorities;

    public JwtUser(Long id, String username, String secondName, String password, String phone, String description,
            String email, boolean active, Date lastPasswordResetDate,
            Collection<? extends GrantedAuthority> authorities) {

        this.id = id;
        this.username = username;
        this.secondName = companyName;
        this.password = password;
        this.phone = phone;
        this.description = description;
        this.email = email;
        this.active = active;
        this.lastPasswordResetDate = lastPasswordResetDate;
        this.authorities = authorities;
    }

    public JwtUser(String token, Long id, String username, String secondName,  String phone, String description,
            String email, Collection<? extends GrantedAuthority> authorities) {
        this.token=token;
        this.id = id;
        this.username = username;
        this.secondName = companyName;      
        this.phone = phone;
        this.description = description;
        this.email = email;     
        this.authorities = authorities;
    }

    public JwtUser(String username, String password, Collection<? extends GrantedAuthority> authorities,
            String email, boolean active) {

        this.username = username;
        this.password=password;
        this.authorities = authorities;
        this.email = email;     
        this.active=active;

    }

    public JwtUser(){

    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    @JsonIgnore 
    public Long getId() {
        return id;
    }

    public String getSecondName() {
        return companyName;
    }

    public String getPhone() {
        return phone;
    }

    public String getDescription() {
        return description;
    }

    public String getEmail() {
        return email;
    }

    public boolean isActive() {
        return active;
    }
    @JsonIgnore
    public Date getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return authorities;
    }
    @JsonIgnore
    @Override
    public String getPassword() {

        return password;
    }

    @Override
    public String getUsername() {

        return username;
    }
    public void setUsername(String username) {
        this.username=username;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {

        return true;
    }
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {

        return true;
    }
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {

        return true;
    }

    @Override
    public boolean isEnabled() {

        return true;
    }

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题