BindingResult отображает ошибку и способ отображения ошибок на JSP страницах - PullRequest
0 голосов
/ 07 мая 2020

Мой вопрос: я получаю ошибку BindingResult, хотя я использую правильный формат данных и удовлетворяю всем требованиям, а также как отображать эти сообщения об ошибках на стороне сервера на моих JSP страницах. Это было бы слишком полезно.

У меня есть класс модели пользователя:

package com.nischal.bookshelf.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Length;

@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Email(message = "Sorry the Email Id is not Valid") //I want to display this message to my JSP page if user provide me with wrong email id
@NotEmpty(message = "Sorry! you have not entered your Email Id yet.")
private String email;

@NotEmpty(message = "Sorry! you have not entered your password yet")
@Length(min = 6, message = "Sorry your Password is too short")
private String password;

@NotEmpty(message = "Sorry! you have not entered your phone number yet")
@Pattern(regexp="(^|[0-9] {10})",message = "Sorry mobile number must be of ten digits")
private String phone;

У меня есть страница JSP, т.е. регистрация. jsp как

<code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action = "registerUser" method = "post">
<pre>
    Email: <input type = "email" name = "email"/>
    Password: <input type = "password" name = "password"/>
    Phone: <input type = "text" name = "phone">
    <input type = "submit" value = "Register"/>     
$ {msg} ** Я хочу отобразить здесь сообщение об ошибке на стороне сервера **

У меня класс UserController как

package com.nischal.bookshelf.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nischal.bookshelf.entity.User;
import com.nischal.bookshelf.repos.UserRepository;

@Controller
public class UserController {

private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

@Autowired
private UserRepository userRepository;

@RequestMapping("/showRegistration")
public String showRegistration() {
    LOGGER.info("We are inside of the /login/registration i.e showRegistration(). ");
    return "/login/registration";
}

@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public String registerUser(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, ModelMap modelMap) {
    if(bindingResult.hasErrors()) {
        modelMap.addAttribute("msg", "Please Correct the error in the above forms");
        LOGGER.info("We are having the errors.");
        return "/login/registration";
    }
    else {
        userRepository.save(user);
    }
    return "/login/login";
}

}

Отображается следующий тип ошибки, хотя каждое свойство удовлетворяет требованиям enter image description here

Ее необходимо перенести на страницу входа в систему, но это не так. 't и показывает ту же страницу ошибки, что и: enter image description here

...