Spring MVC Controller refer to string in property file

Viewed 281

I was having some problem when trying to access the key value pairs in properties file using Spring MVC.

Here is where I stored the properties file: ../common/properties/AppResource.properties.

An example of key value pair in the file:

error.password.mismatch=Invalid userid and/or password, please try again

In my servlet.xml, I declared the following bean:

<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
<property name="basename"> 
    <value>classpath*:common/properties/*.properties</value> 
</property> 

In my controller, I am trying to access the key value pair:

} catch (UserNotFoundException e) {
    model.addAttribute("errorMessage", "error.password.mismatch");
    return "login";
} 

In my JSP page, I am printing the error message:

<font class="errorClass"><form:errors path="errorMessage" /></font>

However, the message printed out was "error.password.mismatch" instead of referring to the text in properties file. Any ideas?

1 Answers

The path attribute of <form:errors/> denotes the field that you want to show error for. You will need to register a field error against that field.

If you are using custom Validator,

@Override
public void validate(Object target, Errors errors) {
    // your logic here
    errors.rejectValue("fieldName", "error.password.mismatch");
}

And in JSP:

<form:errors path="fieldName"/>


NOTE:

If you want to show message in a different manner other than using <form:errors/> tag,

You can do

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<fmt:message key="error.password.mismatch"/>

Or

<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>

<s:message code="error.password.mismatch"/>

Or

If you want to resolve the value from controller, you can use MessageSourceAccessor.

<bean id="messageSourceAccessor" class="org.springframework.context.support.MessageSourceAccessor">
    <constructor-arg ref="messageSource"/>
</bean>

In controller:

@Autowired
private MessageSourceAccessor messageSourceAccessor;

and

model.addAttribute("someMessage", messageSourceAccessor.getMessage("error.password.mismatch"));

and in JSP:

<c:out value="${someMessage}"/>


Answering to OP's comment:

If I used the MessageSourceAccesor, where do I declare the path for property files?

From Spring Framework Reference:

<beans>
    <bean id="messageSource"
            class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>format</value>
                <value>exceptions</value>
                <value>windows</value>
            </list>
        </property>
    </bean>
</beans>

The example assumes that you have three resource bundles called format, exceptions and windows defined in your classpath.

Related