密码确认与Spring注解

huangapple 未分类评论48阅读模式
英文:

Password confirmation with spring annotation

问题

以下是翻译好的内容:

能否有人解释一下我遇到的错误。我正在按照教程进行密码确认。

2020-05-29 15:23:33.397 ERROR 10832 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : 
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause

javax.validation.ConstraintViolationException: Validation failed for classes [com.example.onlineshop.model.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
	ConstraintViolationImpl{interpolatedMessage='密码不匹配', propertyPath=, rootBeanClass=class com.example.onlineshop.model.User, messageTemplate='密码不匹配'}

如果我没有弄错的话,我已经做得没问题了。

这是我的注册控制器。

@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String showRegistration(WebRequest request, Model model) {
    User user = new User();
    model.addAttribute("user", user);
    return "registration";
}

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult, HttpServletRequest request, Errors errors) {
    ModelAndView model = new ModelAndView();
    User userExists = userService.findUserByName(user.getName());
    if (userExists != null) {
        bindingResult
                .rejectValue("name", "errors.user",
                        "已经有一个使用提供的用户名注册的用户");
    }
    if (bindingResult.hasErrors()) {
        model.setViewName("registration");
    } else {
        userService.saveUser(user);
        model.addObject("successMessage", "用户已成功注册");
        model.addObject("user", new User());
        model.setViewName("registration");
    }
    return model;
}

这是一个服务。

public User saveUser(User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setActive(true);
    Role userRole = roleRepository.findByRole("CUSTOMER");
    user.setRoles(new HashSet<>(Arrays.asList(userRole)));
    return userRepository.save(user);
}

这是我的模型。抱歉,因为代码太多而导致显示混乱。

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int id;
    
    @Column(name = "name")
    @NotEmpty(message = "*请输入您的名字")
    private String name;
    
    @Column(name = "email")
    @ValidEmail
    @NotEmpty(message = "*请输入您的电子邮件")
    private String email;
    
    @Column(name = "password")
    @NotEmpty(message = "*请输入您的密码")
    @Length(min = 5, message = "*您的密码长度应至少为5个字符")
    private String password;
    
    @Transient
    private String matchingPassword;
    
    @Column(name = "active")
    private Boolean active;
    
    @ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;
}
英文:

Can someone please explain me the error I am getting. I am doing password confirmation by tutorial.

2020-05-29 15:23:33.397 ERROR 10832 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : 
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction] with root cause

javax.validation.ConstraintViolationException: Validation failed for classes [com.example.onlineshop.model.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage=&#39;Passwords don&#39;t match&#39;, propertyPath=, rootBeanClass=class com.example.onlineshop.model.User, messageTemplate=&#39;Passwords don&#39;t match&#39;}

If I am not mistaken I am did everything correctly.

Here is my Registration controller.

@RequestMapping(value = &quot;/registration&quot;, method = RequestMethod.GET)
public String showRegistration(WebRequest request, Model model) {
    User user = new User();
    model.addAttribute(&quot;user&quot;, user);
    return &quot;registration&quot;;
}

@RequestMapping(value = &quot;/registration&quot;, method = RequestMethod.POST)
public ModelAndView createNewUser(@Valid User user, BindingResult bindingResult, HttpServletRequest request, Errors errors) {
    ModelAndView model = new ModelAndView();
    User userExists = userService.findUserByName(user.getName());
    if (userExists != null) {
        bindingResult
                .rejectValue(&quot;name&quot;, &quot;errors.user&quot;,
                        &quot;There is already a user registered with the name provided&quot;);
    }
    if (bindingResult.hasErrors()) {
        model.setViewName(&quot;registration&quot;);
    } else {
        userService.saveUser(user);
        model.addObject(&quot;successMessage&quot;, &quot;User has been registered successfully&quot;);
        model.addObject(&quot;user&quot;, new User());
        model.setViewName(&quot;registration&quot;);
    }
    return model;
}

This is a service

public User saveUser(User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setActive(true);
    Role userRole = roleRepository.findByRole(&quot;CUSTOMER&quot;);
    user.setRoles(new HashSet&lt;&gt;(Arrays.asList(userRole)));
    return userRepository.save(user);
}

This is my model. Sorry for the view. Complaining about too much code

  • @Data

  • @Builder

  • @AllArgsConstructor

  • @NoArgsConstructor

  • @Entity

  • @Table(name = "user")

  • public class User {

  • @Id

  • @GeneratedValue(strategy = GenerationType.AUTO)

  • @Column(name = "user_id")

  • private int id;

  • @Column(name = "name")

  • @NotEmpty(message = "*Please enter your name")

  • private String name;

  • @Column(name = "email")

  • @ValidEmail

  • @NotEmpty(message = "*Please enter your email")

  • private String email;

  • @Column(name = "password")

  • @NotEmpty(message = "*Please enter your password")

  • @Length(min = 5, message = "*Your password length should be at least 5 characters")

  • private String password;

  • @Transient

  • private String matchingPassword;

  • @Column(name = "active")

  • private Boolean active;

  • @ManyToMany(cascade = CascadeType.MERGE)

  • @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"),

  • inverseJoinColumns = @JoinColumn(name = "role_id"))

  • private Set<Role> roles;

  • }

huangapple
  • 本文由 发表于 2020年5月29日 17:38:25
  • 转载请务必保留本文链接:https://java.coder-hub.com/62082954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定