Announcement Announcement Module
Collapse
No announcement yet.
How to make HttpMessageConverter aware of request locale? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to make HttpMessageConverter aware of request locale?

    In a Spring MVC 3.1 application, how should I use the request's locale to control string formatting by an HttpMessageConverter?

    I have this enum:

    Code:
        public enum Soil {
    
            SAND("0.35"),
            PEAT("0.70");
            
            private Double porosity;
            
            Soil(String porosity) {
                this.porosity = new Double(porosity);
            }
            
            @NumberFormat(pattern = "0.00")
            public Double getPorosity() {
                return porosity;
            }
    
        }
    I also have a controller for accessing soil properties:

    Code:
        @Controller
        @RequestMapping("/soil/*")
        public class SoilController {
    
            @RequestMapping(value="{id}/porosity")
            public @ResponseBody Double getPorosity(@PathVariable String id) {
                Soil soil = Soil.valueOf(id);
                return soil.getPorosity();
            }
            
        }
    As I understand it, by using @RequestBody, Spring converts the returned Double to a response body by using an
    HttpMessageConverter. This works fine, but the response string is always formatted using the default locale ('en_US' in this case). For instance, a GET request to /soil/PEAT/porosity will result in a '0.7' being written to the response body.

    However, most visitors have 'nl' as their preferred locale, expecting a decimal comma instead of a decimal point. In this case, I'd like the response string to be formatted as '0,7'.

    I can add an HttpServletRequest parameter to the handler method's signature to determine the request's locale, but don't know how to pass this information to the HttpMessageConverter - a MappingJacksonHttpMessageConverter in this case (*). I know it is possible to configure the MappingJacksonHttpMessageConverter bean by overriding the defaults in the <mvc:annotation-driven> tag, but how do I make it aware of the request locale?

    (*) DEBUG: org.springframework.web.servlet.mvc.method.annotat ion.RequestResponseBodyMethodProcessor - Written [0.7] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJac ksonHttpMessageConverter@145240a]

  • #2
    Answering my own question for completeness' sake: i18n formatting is best handled by a view. See http://stackoverflow.com/questions/1...cale-to-contro.

    Comment

    Working...
    X