안녕하세요. 어디서나 찾고 있었지만 해결책을 찾을 수 없습니다. Jquery 함수에서 ajax 호출을 만들고 스프링 입력 양식에서 데이터를 제출 중입니다. 컨트롤러에 입력. 컨트롤러는 JSR 303 Hibernate Validation으로 날짜를 확인하고 JSON에 의한 오류를 동일한 Jquery 함수 (Json에 의한 데이터 수신)로 반환하고 jsp에 오류를 표시합니다. 모든 것이 제대로 작동하지만 표시되는 오류 메시지는 dafault이거나 유효성 검사 주석의 메시지 매개 변수에 불과합니다. ValidationMessages.properties 파일에서 오류 메시지를 가져오고 준비된 메시지가있는 파일을 가지고 있지만 메시지를 표시하는 것은 ValidationMessages.properties가 아닌 dafault입니다. Json이받은 오류를 표시하고 싶기 때문에 form : error 태그를 사용하지 않습니다. 문제는 잘못된 메시지가 파일이 아니라 dafault로 표시된다는 것입니다.Spring MVC JSR 303 ValidationMessages.properties의 Json 응답 유효성 검사 오류로 인한 유효성 검사
정상적인 JSR 303 Validation (Ajax 및 Json없이)을 사용하여 양식별로 오류 메시지를 표시하는 동안 오류 태그가 제대로 작동하고 메시지가 ValidationMessages.properties 파일에서 온다고 추가합니다. 의 user.js
다음 function doAjaxPost() {
// get the form values
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: contexPath + "/AddUser.htm",
data: "name=" + name + "&education=" + education,
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
userInfo = "<ol>";
for(i =0 ; i < response.result.length ; i++){
userInfo += "<br><li><b>Name</b> : " + response.result[i].name +
";<b> Education</b> : " + response.result[i].education;
}
userInfo += "</ol>";
$('#info').html("User has been added to the list successfully. " + userInfo);
$('#name').val('');
$('#education').val('');
$('#error').hide('slow');
$('#info').show('slow');
}else{
errorInfo = "";
for(i =0 ; i < response.result.length ; i++){
errorInfo += "<br>" + (i + 1) +". " + response.result[i].defaultMessage;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
}
},
error: function(e){
alert('Error: ' + e);
}
});
}
에서
내 .jsp로 페이지가
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Users using ajax</title>
<script src="<%=request.getContextPath() %>/js/jquery.js"></script>
<script type="text/javascript">
var contexPath = "<%=request.getContextPath() %>";
</script>
<script src="<%=request.getContextPath() %>/js/user.js"></script>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/style/app.css">
</head>
<body>
<h1>Add Users using Ajax ........</h1>
<form:form method="post" modelAttribute="user">
<table>
<tr><td colspan="2"><div id="error" class="error"></div></td></tr>
<tr><td>Name:</td> <td><form:input path="name" /></td>
<tr><td>Education</td> <td><form:input path="education" /></td>
<tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
<tr><td colspan="2"><div id="info" class="success"></div></td></tr>
</table>
</form:form>
</body>
</html>
내 doAjaxPost 기능은 컨트롤러
package com.raistudies.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.raistudies.domain.JsonResponse;
import com.raistudies.domain.User;
@Controller
public class UserController {
private List<User> userList = new ArrayList<User>();
@RequestMapping(value="/AddUser.htm",method=RequestMethod.GET)
public String showForm(Map model){
User user = new User();
model.put("user", user);
return "AddUser";
}
@RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
public @ResponseBody JsonResponse addUser(@ModelAttribute(value="user") @Valid User user, BindingResult result){
JsonResponse res = new JsonResponse();
if(!result.hasErrors()){
userList.add(user);
res.setStatus("SUCCESS");
res.setResult(userList);
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
}
사용자 클래스
package com.raistudies.domain;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class User {
@NotEmpty
private String name = null;
@NotEmpty
@Size(min=6, max=20)
private String education = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
}
,536,913,632입니다 여기에 10
는 ValidationMessage.properties 여기
NotEmpty.user.name=Name of user cant be empty
NotEmpty.user.education = User education cant be empty
Size.education=education must hava between 6 and 20 digits
파일입니다 응용 프로그램-config.xml에 다음
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/ValidationMessages" />
</bean>
<!-- Scans the classpath of this application for @Components to deploy as beans -->
<context:component-scan base-package="com.raistudies" />
<!-- Configures the @Controller programming model -->
<mvc:annotation-driven/>
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
는 스크린 샷입니다 https://www.dropbox.com/s/1xsmupm1cgtv4x7/image.png?v=0mcns
당신은 기본 오류 메시지를하지 표시되어있다시피 ValidationMessages.properties 파일에서. 어떻게 해결할 수 있을까요?
여기에 설명 된 것과 동일한 문제가 있다고 생각합니다. http://stackoverflow.com/questions/5073488/jsr-303-and-spring-mvc-binding-result. 나는 Spring이 순수한 Bean의 유효성 검사와 유효성 검사의 최상위에 여러 개의 레이어를 둔다는 것이 문제라고 생각한다. 유효성 검사와 유효성 검사는 컨트롤러에서 무엇을하는지에 따라 다르게 동작한다. – Hardy