2014-10-06 6 views
0

나는 여기 http://docs.spring.io/docs/Spring-MVC-step-by-step/에 설명 된 봄 단계 웹 애플 리케이션을하고있다.봄에 오류 메시지를 어떻게 바꿀 수 있습니까?

<?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.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd 
     http://www.springframework.org/schema/mvc 
     http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 

     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
     <property name="basename" value="messages"/> 
     </bean> 

     <!-- Scans the classpath of this application for @Components to deploy as beans --> 
     <context:component-scan base-package="com.companyname.springapp.web" /> 

     <!-- Configures the @Controller programming model --> 
     <mvc:annotation-driven/> 

     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> 
     <property name="prefix" value="/WEB-INF/views/"></property> 
     <property name="suffix" value=".jsp"></property>   
     </bean> 
</beans> 

<%@ include file="/WEB-INF/views/include.jsp" %> 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 

<html> 
<head> 
    <title><fmt:message key="title"/></title> 
    <style> 
    .error { color: red; } 
    </style> 
</head> 
<body> 
<h1><fmt:message key="priceincrease.heading"/></h1> 
<form:form method="post" commandName="priceIncrease"> 
    <table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5"> 
    <tr> 
     <td align="right" width="20%">Increase (%):</td> 
     <td width="20%"> 
      <form:input path="percentage"/> 
     </td> 
     <td width="60%"> 
      <form:errors path="percentage" cssClass="error"/> 
     </td> 
    </tr> 
    </table> 
    <br> 
    <input type="submit" value="Execute"> 
</form:form> 
<a href="<c:url value="hello.htm"/>">Home</a> 
</body> 
</html> 

package com.companyname.springapp.service; 

import javax.validation.constraints.Max; 
import javax.validation.constraints.Min; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

public class PriceIncrease { 

    /** Logger for this class and subclasses */ 
    protected final Log logger = LogFactory.getLog(getClass()); 

    @Min(0) 
    @Max(50) 
    private int percentage; 

    public void setPercentage(int i) { 
     percentage = i; 
     logger.info("Percentage set to " + i); 
    } 

    public int getPercentage() { 
     return percentage; 
    } 
} 

package com.companyname.springapp.web; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServletRequest; 
import javax.validation.Valid; 

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

import com.companyname.springapp.service.PriceIncrease; 
import com.companyname.springapp.service.ProductManager; 

@Controller 
@RequestMapping(value="/priceincrease.htm") 
public class PriceIncreaseFormController { 

    /** Logger for this class and subclasses */ 
    protected final Log logger = LogFactory.getLog(getClass()); 

    @Autowired 
    private ProductManager productManager; 

    @RequestMapping(method = RequestMethod.POST) 
    public String onSubmit(@Valid PriceIncrease priceIncrease, BindingResult result) 
    { 
     if (result.hasErrors()) { 
      return "priceincrease"; 
     } 

     int increase = priceIncrease.getPercentage(); 
     logger.info("Increasing prices by " + increase + "%."); 

     productManager.increasePrice(increase); 

     return "redirect:/hello.htm"; 
    } 

    @RequestMapping(method = RequestMethod.GET) 
    protected PriceIncrease formBackingObject(HttpServletRequest request) throws ServletException { 
     PriceIncrease priceIncrease = new PriceIncrease(); 
     priceIncrease.setPercentage(15); 
     return priceIncrease; 
    } 

    public void setProductManager(ProductManager productManager) { 
     this.productManager = productManager; 
    } 

    public ProductManager getProductManager() { 
     return productManager; 
    } 
} 

title=SpringApp 
heading=Hello :: SpringApp 
greeting=Greetings, it is now 
priceincrease.heading=Price Increase :: SpringApp 
error.not-specified=Percentage not specified!!! 
error.too-low=You have to specify a percentage higher than {0}! 
error.too-high=Don''t be greedy - you can''t raise prices by more than {0}%! 
required=Entry required. 
typeMismatch=Invalid data. 
typeMismatch.percentage=That is not a number!!! 

문제는 내가 나는 다음과 같은 메시지를받지 못하고있어 percentaje 필드 (65)를 삽입 할 때 내가 예를 정의한 메시지를 받고되지 않습니다 don''t는이 욕심을 - 당신은 인상 can''t는 가격이 {0} % 이상!! 이 대신 기본 메시지가 나타납니다. 게시물을 더 짧게 만들기 위해 autowired 주석과 관련된 코드를 삭제했습니다. 응용 프로그램이 제대로 작동하는지, 반환 된 메시지에 문제가 있는지를 알아야합니다.

내가 원하는 메시지를 표시하려면 어떻게해야합니까?

답변

1

이 게시물은 spring mvc에서 유효성 검사를 수행하는 방법을 자세히 설명합니다. Click Here

+0

고마워를 구현해야, 그것은했다. – Martin

+0

대단히 환영합니다. Upvoting 도움이됩니다 :) – javafan

0

당신은 그냥 ... Validator 여기에 간단한 예제

public class PriceIncreaseValidator implements Validator { 

    @Override 
    public boolean supports(Class<?> clazz) { 
     return PriceIncrease.class.equals(clazz); 
    } 

    @Override 
    public void validate(Object o, Errors e) {    
     PriceIncrease priceIncrease = (PriceIncrease) o; 
     if(priceIncrease.getPercentage() == 0) { 
      e.rejectValue("priceIncrease", "error.too-low"); 
     } else if(priceIncrease.getPercentage() >= 50) { 
      e.rejectValue("priceIncrease", "error.too-high"); 
     } 

    } 
} 
관련 문제