2013-05-20 1 views
1

안녕하세요. 어디서나 찾고 있었지만 해결책을 찾을 수 없습니다. 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 파일에서. 어떻게 해결할 수 있을까요?

+0

여기에 설명 된 것과 동일한 문제가 있다고 생각합니다. http://stackoverflow.com/questions/5073488/jsr-303-and-spring-mvc-binding-result. 나는 Spring이 순수한 Bean의 유효성 검사와 유효성 검사의 최상위에 여러 개의 레이어를 둔다는 것이 문제라고 생각한다. 유효성 검사와 유효성 검사는 컨트롤러에서 무엇을하는지에 따라 다르게 동작한다. – Hardy

답변

0

이 작업을 시도 할 수 :

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 
    <property name="messageInterpolator" ref="messageSource"/> 
</bean> 

<mvc:annotation-driven validator="validator"/> 

아이디어는 명시 적으로 사용하는 메시지 소스 유효성 검사기를 이야기하는 것입니다. 나는 나 자신을 시험해 보지 않았지만 그것은 가치가있다.

+1

이것은 좋은 생각이지만, 슬프게도, messageInterpolator 속성이 쓰기 가능하지 않기 때문에 작동하지 않습니다. –

1

저는 이것이 아주 오래된 질문이라는 것을 알고 있습니다 만, 저는 이것을 얼마 동안 해결하려고 노력해 왔습니다. 방금 이 주위 주위에 일을 발견했기 때문에, 나는 그것을 다른 사람들이 아마도 같은 일에 붙어 있도록 돕기 위해 그것을 공유하는 줄 알았습니다.

java config으로이 작업을하고 있으므로주의해야합니다.

먼저 컨트롤러에 자동 무선 링크를 추가하십시오.이 프로퍼티 파일을 읽을 수있게하는 것입니다

@Autowired 
private Environment environment; 

영업 이익은 이미 XML을 통해 정의 된 MessageSource를 가지고,하지만 자바는 WebMvcConfigurerAdapter를 확장하는 설정 클래스에있을 것 config (설정). 내 경우에는 다음과 함께 작업했습니다.

@Bean 
public MessageSource messageSource() { 
    ResourceBundleMessageSource msg= new ResourceBundleMessageSource(); 
    msg.setUseCodeAsDefaultMessage(true); 
    msg.setBasename("PATH_TO_YOUR_MESSAGE_FILE"); 
    msg.setDefaultEncoding("UTF-8"); 
    return msg; 
} 

해당 부분을 파일 경로로 바꾸십시오. 어쨌든 이제 문제를 해결하십시오. 새로운 기능이 하나

res.setResult(result.getAllErrors()); 

및 통화 : 위로 컨트롤러,이 라인을 교체

private LinkedList<CustomErrorMsg> createErrorMessages(List<FieldError> originalErrors) { 
    // Create a new list of error message to be returned 
    LinkedList<CustomErrorMsg> newErrors = new LinkedList<>(); 

    // Iterate through the original errors 
    for(FieldError fe: originalErrors) { 
     // If the codes are null, then put the default message, 
     // if not, then get the first code from the property file. 
     String msg = (fe.getCodes() == null) ? fe.getDefaultMessage() 
       : environment.getProperty(fe.getCodes()[0]); 

     // Create the new error and add it to the list 
     newErrors.add(new CustomErrorMsg(fe.getField(), msg)); 
    } 

    // Return the message 
    return newErrors; 
} 
: 이제

createErrorMessages(result.getFieldErrors()); 

을,이 메시지를 변환하는 새로운 방법입니다

if 부분은 코드가없는 경우와 컨트롤러에서 비즈니스 논리 유효성 검사를 수행 할 때 작동하며 수동으로 새 필드 오류를 추가합니다.

이 해결 방법은 세관 메시지의 매개 변수와 작동하지 않습니다. 또 다른 메모에서 최대 절전 모드 유효성 검사를 사용하지만 AJAX 콜백이 필요하지 않은 다른 페이지가있는 경우이 전략을 사용할 필요가 없습니다. 그것들은 단순히 기본값으로 작동합니다.

저는 이것이 우아한이 아니라는 것을 알고 있습니다. 그리고 그것은 원하는 것보다 약간 더 많은 코드를 추가 할 수 있습니다. 그러나 이전에 말했듯이, 그것은 "주위를 둘러싼"것입니다.