#java #spring-boot #model-view-controller
#java #весенняя загрузка #модель-представление-контроллер
Вопрос:
Попытка проверить форму с помощью аннотаций @NotNull @NotBlank, но ни одно из сообщений не отображается на веб
-странице _@ annotations не работает, поскольку ни одна из проверок не отображается на странице _
Проверка проверки формы
Класс модели
package com.cognizant.bmi.bean;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
public class User {
private int userId;
@NotBlank(message="Name is required")
private String name;
@NotBlank(message="phoneNumber is required")
private String phoneNumber;
@NotNull(message="Height is required")
@Min(value=0,message="Height should be >0")
private Integer height;
@NotNull(message="Weight is required")
@Min(value=0,message="Weight should be >0")
private Double weight;
private String genderType;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public String getGenderType() {
return genderType;
}
public void setGenderType(String genderType) {
this.genderType = genderType;
}
@Override
public String toString() {
return "User [userId=" userId ", name=" name ", phoneNumber=" phoneNumber ", height=" height
", weight=" weight ", genderType=" genderType "]";
}
}
Форма определена в JSP, который необходимо проверить
JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>BMI Calculator</title>
</head>
<body>
<br>
<br>
<h1 id="heading">BMI Calculator</h1>
<table>
<caption style="font-weight: bolder;">Body Mass Index Calculator Form</caption>
<sf:form action="getBMI" modelAttribute="user" method="GET" name="form">
<tr>
<td>Enter Name:</td>
<td><sf:input path="name" id="name" required="true"
name="name" /> <sf:errors style="color:red" path="name" ></sf:errors></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><sf:input path="phoneNumber" id="phoneNumber" required="true"
name="phoneNumber" /> <sf:errors style="color:red" path="phoneNumber"></sf:errors></td>
</tr>
<tr>
<td>Height in CM:</td>
<td><sf:input path="height" id="height" required="true"
name="height" /> <sf:errors style="color:red" path="height" ></sf:errors></td>
</tr>
<tr>
<td>Weight in KG:</td>
<td><sf:input path="weight" id="weight" required="true"
name="weight" /> <sf:errors style="color:red" path="weight" ></sf:errors></td>
</tr>
<tr>
<td>Gender:</td>
<td><sf:select path="genderType" items="${genderList}"
id="genderType" name="genderType">
<sf:errors path="genderType"></sf:errors>
</sf:select><br></td>
</tr>
<tr>
<td><input type="submit" id="submit" name="calculateBMI"
value="CalculateBMI"></td>
<td><input type="reset" id="Clear" name="Clear" value="Clear"></td>
</tr>
</sf:form>
</table>
${status}
</body>
</html>
Класс контроллера
КОНТРОЛЛЕР
package com.cognizant.bmi.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResu<
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.cognizant.bmi.bean.User;
import com.cognizant.bmi.service.BMIService;
@Controller
public class BMIController {
@Autowired
private BMIService bmiService;
@RequestMapping(value = "/bmiForm", method = RequestMethod.GET)
public String showBMIForm(@ModelAttribute("user") User user) {
return "bmiCalculatorForm";
}
@RequestMapping(value = "/getBMI", method = RequestMethod.GET)
public String getBMIStatus(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap map) {
if (result.hasErrors())
{
return "bmiCalculatorForm";
}
User user1=bmiService.addUserDetails(user);
double bmi=bmiService.calculateBMI(user);
String bmiStatus=bmiService.getBMIStatus(bmi);
map.put("user.userId",user.getUserId());
map.put("user.name", user.getName());
map.put("user.height",user.getHeight());
map.put("user.weight", user.getWeight());
map.put("bmi", bmi);
map.put("bmiStatus",bmiStatus);
return "bmiStatus";
}
@ModelAttribute("genderList")
public List<String> populateGenderList() {
return bmiService.genderType;
}
}
Комментарии:
1. Вы пробовали
@Validated
вместо@Valid
?2. @Eniss Никаких изменений
Ответ №1:
Проблема заключалась в том, что я использовал проверку в JSP, а также использовал @Annotation для проверки
Удалено «Required =’true'» из разрешенной проблемы jsp, и теперь она работает.
Спасибо @Eniss за немедленный ответ
РАБОЧИЙ JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>BMI Calculator</title>
</head>
<body>
<br>
<br>
<h1 id="heading">BMI Calculator</h1>
<table>
<caption style="font-weight: bolder;">Body Mass Index Calculator Form</caption>
<sf:form action="getBMI" modelAttribute="user" method="GET" name="form">
<tr>
<td>Enter Name:</td>
<td><sf:input path="name" id="name"
name="name" /> <sf:errors style="color:red" path="name" ></sf:errors></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><sf:input path="phoneNumber" id="phoneNumber"
name="phoneNumber" /> <sf:errors style="color:red" path="phoneNumber"></sf:errors></td>
</tr>
<tr>
<td>Height in CM:</td>
<td><sf:input path="height" id="height"
name="height" /> <sf:errors style="color:red" path="height" ></sf:errors></td>
</tr>
<tr>
<td>Weight in KG:</td>
<td><sf:input path="weight" id="weight"
name="weight" /> <sf:errors style="color:red" path="weight" ></sf:errors></td>
</tr>
<tr>
<td>Gender:</td>
<td><sf:select path="genderType" items="${genderList}"
id="genderType" name="genderType">
<sf:errors path="genderType"></sf:errors>
</sf:select><br></td>
</tr>
<tr>
<td><input type="submit" id="submit" name="calculateBMI"
value="CalculateBMI"></td>
<td><input type="reset" id="Clear" name="Clear" value="Clear"></td>
</tr>
</sf:form>
</table>
${status}
</body>
</html>