Reading the content of property file in Spring Validator Class
I am using Spring 3.0. Can i read a property file from a localdrive eg: C:\prop\mylogin.properties(not under webapps/application server)
mylogin.properties
login.heading=Login
login.username=Username
login.password_blank=Password cannot be blank
I want to use the above in my Validator class(java bean class). Please Note : I using MultiAction Controller not SpringFormController
public class MyUserValidator implements Validator
{
@Override
public void validate(Object command, Errors errors) {
String msg=null;
//some conditions checked
String msg=login.password_blank;-------->get from property file ??
errors.rejectValue("User",msg,"defaultvalue");
}
Hi we are using resource bundle, not sure how this will need to be used within validator?
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource" lazy-init="true">
<property name="basenames">
<list>
<value>${deployment.properties.path}/xyzsite/mylogin</value>
</list>
</property>
<property name="cacheSeconds" value="${deployment.properties.cache_in_seconds}"/>
</bean>
What change i cud make in the answer u have mentioned if resource bundle is been used?
for example if i wa开发者_开发问答nt to set a PageSize int pagesize=5; ---> get this from property file
mylogin.properties
login.heading=Login
login.username=Username
login.password_blank=Password cannot be blank
login.page_row_size=5
Error messages are usually best handled as a standard combination of a Java ResourceBundle
and JSTL, but that won't work for loading the properties from an arbitrary location on the filesystem.
So you'll have to do things a bit more manually. The simplest thing would be to inject the location of the properties file, then extract the properties from it:
public class MyUserValidator implements Validator {
private Resource propertiesLocation;
@Required
public void setPropertiesLocation(Resource propertiesLocation) {
this.propertiesLocation = propertiesLocation;
}
@Override
public void validate(Object command, Errors errors) {
try {
Properties props = PropertiesLoaderUtils.loadProperties(propertiesLocation);
String key = "login.password_blank";
String errorMessage = props.getProperty(key);
errors.rejectValue("User", key, errorMessage);
} catch (IOException e) {
// handle me
}
}
}
and in the config:
<bean id="userValidator" class="com.x.MyUserValidator">
<property name="propertiesLocation" value="file:/prop/mylogin.properties"/>
</bean>
Note the following line:
errors.rejectValue("User", key, errorMessage);
Since you're not using ResourceBundle
, you need to pass in the "default error message" as the 3rd argument.
Alright got this sorted by doing following mav= new ModelAndView mav.addAllObjects(errors.getModel());
and in jsp using
精彩评论