Announcement Announcement Module
Collapse
No announcement yet.
resource bundle to read properties from poperty file Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • resource bundle to read properties from poperty file

    when i use properties file to read the content from resource bundle
    it always give me default string rather than existing string in property file
    so how can i get it
    code is here:
    this is web.xml file==>
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>
    <web-app>
    <servlet>
    <servlet-name>springapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherSe rvlet</servlet-class>
    <load-on-startup>2</load-on-startup>
    </servlet>

    <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>/app/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
    <welcome-file>
    /jsp/SearchTrans.jsp
    </welcome-file>
    </welcome-file-list>

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    /WEB-INF/ConnectDB-services.xml
    </param-value>
    </context-param>



    <servlet>
    <servlet-name>context</servlet-name>
    <servlet-class>org.springframework.web.context.ContextLoade rServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>

    </web-app>


    ==============================================
    ConnectDB-services.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverM anagerDataSource">
    <property name="driverClassName"><value>com.microsoft.jdbc.s qlserver.SQLServerDriver</value></property>
    <property name="url">
    <value>jdbc:microsoft:sqlserver://192.168.1.3:1433;databaseName=mcpg;SelectMethod=cu rsor</value>
    </property>
    <property name="username"><value>iusr_mcpg</value></property>
    <property name="password"><value>mcpg</value></property>
    </bean>

    <bean id="messageSource" class="org.springframework.context.support.Resourc eBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages"/>
    </bean>

    </beans>
    ========================================
    this is springapp-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
    <!-- - Application context definition for "springapp" DispatcherServlet. -->
    <beans>

    <bean id="valdiform" class="LoginValid">
    <property name="messages" ref="messageSource"/>
    </bean>

    <bean id="springappController" class="SpringappController">
    <property name="messages" ref="messageSource"/>
    <property name="sessionForm"><value>true</value></property>
    <property name="commandName"><value>loginCommand</value></property>
    <property name="commandClass"><value>LoginCommand</value></property>
    <property name="formView">
    <value>SearchTrans</value>
    </property>
    <property name="validator">
    <ref bean="valdiform"/>
    </property>
    <property name="successView">
    <value>show</value>
    </property>
    </bean>


    <bean id="urlMapping" class="org.springframework.web.servlet.handler.Sim pleUrlHandlerMapping">
    <property name="interceptors">
    <list>
    <ref local="contentInterceptor"/>
    </list>
    </property>

    <property name="mappings">
    <props>
    <prop key="/abc.do">springappController</prop>
    </props>
    </property>
    </bean>

    <bean id="contentInterceptor" class="org.springframework.web.servlet.mvc.WebCont entInterceptor">
    <property name="cacheSeconds"><value>30</value></property>
    <property name="supportedMethods"><value>POST</value></property>
    </bean>

    <bean id="viewResolver" class = "org.springframework.web.servlet.view.InternalReso urceViewResolver">
    <property name="viewClass"><value>org.springframework.web.se rvlet.view.JstlView</value></property>
    <property name ="prefix"><value>/jsp/</value></property>
    <property name ="suffix"><value>.jsp</value></property>
    </bean>

    </beans>

    ==============================
    LoginValid.java

    import org.springframework.context.*;
    import org.springframework.validation.*;
    public class LoginValid implements Validator {

    public boolean supports(Class clazz) {
    return LoginCommand.class.isAssignableFrom(clazz);
    }

    private MessageSource messages;

    public void setMessages(MessageSource messages) {
    this.messages = messages;
    System.out.println("hello " + messages);
    }



    public void validate(Object obj, Errors errors) {
    String message = this.messages.getMessage("app.vishal",
    null, "Required", null);
    System.out.println(message);
    System.out.println("i m in valid");
    LoginCommand account = (LoginCommand)obj;
    String ord = account.getOrderid();
    System.out.println("i m in display"+ord.length());
    if (ord.length()==0) {
    System.out.println("i m in valid");
    errors.rejectValue("orderid", "orderid.required");
    return;
    }
    }
    }

  • #2
    Me too facing the same problem while loading the key -value pairs in errors.reject value. Can any one help us?

    Comment


    • #3
      Can you post your messages.properties file?

      Comment


      • #4
        thanks in advance

        applicationcontext.xml
        <bean id="messageSource" class="org.springframework.context.support.Resourc eBundleMessageSource">
        <property name="basenames">

        <value>messages</value>

        </property>

        messages.properties:
        error.required=Please enter {0}

        (i have placed this under web-inf/classes)

        validationutil.java

        Object[] msgFormatArgs = new Object[] { fieldName};
        errors.rejectValue(fieldKey, "error.required", msgFormatArgs,
        fallbackErrorMessage);

        Comment


        • #5
          Apparently I can see nothing wrong in your configuration.

          Did you try inspecting the messages object instance in your validator class to see if there is something wrong with it?

          Also, take a look at this link: http://static.springframework.org/sp...ageSource.html

          As quoted from ResourceBundleMessageSource API:
          This MessageSource caches both the accessed ResourceBundle instances and the generated MessageFormats for each message. It also implements rendering of no-arg messages without MessageFormat, as supported by the AbstractMessageSource base class. The caching provided by this MessageSource is significantly faster than the built-in caching of the java.util.ResourceBundle class.

          Unfortunately, java.util.ResourceBundle caches loaded bundles forever: Reloading a bundle during VM execution is not possible. As this MessageSource relies on ResourceBundle, it faces the same limitation. Consider ReloadableResourceBundleMessageSource for an alternative that is capable of refreshing the underlying bundle files.
          Is your VM somehow caching this message source and thus is not able to display the messages you add?

          Comment


          • #6
            Thanks leonardoborges .
            I debugged it and was able to retrieve msgs. may be some cache problem
            Now "error.required" was retrieved from properties file.but not able to substitute the arguments.

            messages.properties:
            error.required =Please enter {0}
            label.firstname=FirstName

            Both the methods display only Please enter {0} {argument not subsituted}

            1 Method:
            DefaultMessageSourceResolvable msgSourceRes = new DefaultMessageSourceResolvable("label.firstname");
            Object[] msgFormatArgs = new Object[] { msgSourceRes };
            errors.rejectValue(fieldKey, "error.require", msgFormatArgs, "values required");

            2 Method:
            errors.rejectValue(fieldKey, errorMessageKey, new String[]{"firstname"},
            "values required");

            Comment


            • #7
              Note that this:

              messages.properties:
              error.required =Please enter {0}
              label.firstname=FirstName
              should look like this

              messages.properties:
              error.required =Please enter '{0}'
              label.firstname=FirstName
              Try now and see if this works!

              Comment


              • #8
                Thanks leo!!!
                I would check this and tell the output

                Comment


                • #9
                  i tried giving like this \{0}\,it works fine.

                  Comment


                  • #10
                    Simple Resource Bundle Usage

                    <bean id="messageSource" class="org.springframework.context.support.Resourc eBundleMessageSource">
                    <property name="basename" value="/WEB-INF/com.test.resource.MyErrorMessages"/>
                    </bean>

                    Your resource file placed in src/com/test/resource/MyErrorMessages.properties. It may contain

                    myerror.key={0} is my name

                    After compilation will go into classes as-
                    /WEB-INF/classes/com/test/resource/MyErrorMessages.properties

                    This is the default bundle when Locale specific bundle is not found.

                    In your code you should inject "messageSource" bean
                    and use API-

                    messageSource.getMessage("myerror.key",new Object[]{"John"}, Locale.getDefault());

                    This will look for MyErrorMessages_en_US.properties, if it doesnt find , t'will take the key from default MyErrorMessages.properties.

                    Your result will be display as-
                    John is my name

                    Thats all there is to it!! Good Luck !
                    Last edited by L10y; Mar 16th, 2009, 01:47 PM.

                    Comment


                    • #11
                      Hi there.
                      I'd like to access message source from spring javascript.
                      I mean, I'd like to display message from messageResource instead "Username cannot be null!" text.

                      Code:
                      <script type="text/javascript">
                      	Spring.addDecoration(new Spring.ElementDecoration({
                      		elementId : "j_username",
                      		widgetType : "dijit.form.ValidationTextBox",
                      		widgetAttrs : { required : true, invalidMessage : "Username cannot be null!" }}));  
                      </script>
                      How can I do this?

                      Comment

                      Working...
                      X