Announcement Announcement Module
Collapse
No announcement yet.
Convert Boolean True/False to Yes/No Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Convert Boolean True/False to Yes/No

    Greetings,

    I'm sorry if this is common knowledge, I've done a couple of searches and have not been able to find anything on this topic.

    I want to convert all the booleans that are displayed on my pages from true/false to Yes/No. I tried using the Custom Boolean property editor but either I am doing it wrong or I am completely far off.

    What is the best solution to make this happen? Any help would be greatly appreciated.

    Thanks!

  • #2
    If you're using Spring 3, have a look at the Converters section of the MVC Showcase here: http://blog.springsource.com/2010/07...vc-3-showcase/. Converters are superior to PropertyEditors in many respects.

    Specifically, the showcase demonstrates how to implement and plug in a custom Converter. org.springframework.samples.mvc.convert.Conversion ServiceFactoryBean is used to register the converter and it is plugged into the Spring MVC infrastructure in /WEB-INF/spring/appServlet/servlet-context.xml as a bean ref from the mvc:annotation-driven element. You could simply use that example as a base and register your own BooleanToStringConverter that does the following:
    Code:
    public BooleanToStringConverter implements Converter<Boolean, String> {
        public String convert(Boolean bool) {
            return bool ? "Yes" : "No";
        }
    }
    Code:
    public class CustomConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {
    
    	@Override
    	protected void installFormatters(FormatterRegistry registry) {
    		// register the default formatters in superclass
    		super.installFormatters(registry);
    		// install my custom ones
    		registry.addConverter(new BooleanToStringConverter());
    	}	
    }
    Remember, for this converter to kick-in you need to wire the custom conversionService into mvc:annotation-driven AND you either need to use a spring:form tag such as spring:input that applies conversion, or spring:eval that also applies conversion. Just doing a c:out or JSTL ${var} won't apply the conversion logic. We're looking at being able to plug in our EL system as the default EL in Spring 3.1.

    Keith
    Last edited by Keith Donald; Nov 10th, 2010, 08:03 AM.

    Comment


    • #3
      If you use Spring 3 and yours is a web application, you need to:

      - Write a custom formatter for the Boolean type:
      Code:
      public class MyCustomBooleanFormatter implements Formatter<Boolean> {
          public String print (Boolean fieldValue, Locale locale) {
              if (fieldValue.booleanValue()) return "Yes";
              else return "No";
          }
      
          public Boolean parse (String clientValue, Locale locale) {
              if ("Yes".equals(clientValue)) return new Boolean(true);
              else if ("No".equals(clientValue)) return new Boolean(false);
              else //throw some parsing exception or do what you like
          }
      }
      - register this formatter using FormattingConversionServiceFactoryBean:
      Code:
      <mvc:annotation-driven conversion-service="conversionService"/>
      
      <bean id="conversionService"
      class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
          <property name="converters">
              <set>
                <bean class="com.example.MyCustomBooleanFormatter"/>
              </set>
          </property>
      </bean>
      and that's it.

      Comment


      • #4
        Enrico,

        Have you tested this? Looking at the code, the "converters" property only accepts Converter implementations, not Formatter implementations. It would be nice if it worked this way for Formatters, too, but it doesn't at the moment. The only way to register a custom Formatter using FormattingConversionServiceFactoryBean is to subclass and override installFormatters.

        FYI: for an explanation of the differences between the Converter and Formatter SPIs, see the reference documentation in this area.

        Keith

        Comment


        • #5
          My apology, I actually tested something similar but with Converters...I thought it would work also with Formatters since somewhere in the documentation I read that Formatters are just a more specialized type of converters (just String/Object instead of Object/Object converters).

          It would be nice if that worked also for formatters, maybe adding a "formatters" property to FormattingConversionServiceFactoryBean and implementing the same logic used for converters would be a nice add-on for future releases (I generally prefer not to "hack" my way into Spring by extending its classes and overriding its methods).

          Best regards,

          Enrico

          Comment


          • #6
            Thank you Keith! I read your original post and rummaged through the MVC Showcase code (conveniently already checked out, a valuable source!) and was able to get it running right after I read your update/edit about switching the tags to spring:eval.

            Again, thank you, you're a gentleman and a scholar!

            Comment


            • #7
              I opened a JIRA to make registering Formatters easier, vote it up at: https://jira.springframework.org/browse/SPR-7732

              Comment


              • #8
                I fell into a little issue. How are we suppose to handle null values?

                A page that has all of its Boolean values set to true/false loads perfectly fine, however if I try to load a page that holds onto a Boolean with a null value I get this:

                Code:
                java.lang.NullPointerException at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:97) at
                org.springframework.web.servlet.tags.EvalTag.doEndTag(EvalTag.java:113) at
                org.apache.jsp.WEB_002dINF.jsp.operatingDetails.show_jsp._jspx_meth_spring_005feval_005f0(show_jsp.java:3540) at
                org.apache.jsp.WEB_002dINF.jsp.operatingDetails.show_jsp._jspService(show_jsp.java:442) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at
                javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377) at
                org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at
                Thanks
                Last edited by jkrfs; Nov 10th, 2010, 04:22 PM.

                Comment


                • #9
                  You may have hit a bug in Spring 3.0.x--try upgrading to 3.0.5.RELEASE, the latest maintenance version.

                  Comment


                  • #10
                    I upgraded to 3.0.5 last night and I am still running into the same error. I have two test cases, one with all values filled out, the page loads fine. The other with some null values where the page breaks with that error.

                    Comment


                    • #11
                      @jkrfs:
                      I think you should handle the null case yourself in the converter:

                      Code:
                      public BooleanToStringConverter implements Converter<Boolean, String> {
                          public String convert(Boolean bool) {
                              if (bool != null)
                                  return bool ? "Yes" : "No";
                              else
                                  return ""; //or whatever you want
                          }
                      }
                      give it a try.

                      @Keith:
                      I voted the Jira issue, thanks for taking my advice into consideration. I really appreciate it.

                      Enrico

                      Comment


                      • #12
                        By the way, I tried another way which miraculously worked. I wrapped all booleans with

                        Code:
                        <spring: message code="${myObject.theBoolean}" />
                        And replaced true/false in my message.properties to Yes/No, and it displayed. However, when there was a null value, again the page did not complete loading and got an error. I did add

                        Code:
                        =
                        alone in the message.properties file, and again the page loaded fine. I'm not sure if this is the most elegant solution, but at least its working...right?

                        Comment


                        • #13
                          @Enrico,

                          I tried checking for a null value in the BooleanToStringConverter yesterday but the page would still load with the same error that I previously posted.

                          Comment


                          • #14
                            Converters are null safe, you never have to worry about handling nulls there. (see the JavaDocs for the Converter and Formatter SPI noting this)

                            In any case, this was a known bug in 3.0.x that should be fixed in 3.0.5--I can't remember which maintenance release exactly it was fixed in but I remember seeing it.

                            Here's the JIRA I was thinking of. Not exactly the same thing, but related: https://jira.springframework.org/browse/SPR-7459

                            For clarity, can you paste in the snippet of your spring:eval usage from your JSP and the full stacktrace you're getting again when the value is null. If you've confirmed you're indeed running 3.0.5 and still getting this, please definitely do open a JIRA at jira.springframework.org reporting the bug.

                            Keith
                            Last edited by Keith Donald; Nov 11th, 2010, 01:18 PM.

                            Comment


                            • #15
                              Snippet
                              Code:
                              <td><spring:message  code="label.financialStatementsAssembled"/>:</td>
                              <td><spring:eval expression="${serviceAgreement.financialStatementsAssembled}" /></td>
                              Unfortunately, I dont have the full stack trace anymore, I 'fixed' it the issue with what I did in the post above and had to move on. I can set everything back again and try it again tonight.

                              Comment

                              Working...
                              X