Search code examples
javaspringspring-mvclocale

Parameter of a controller method in Spring MVC


I am quite new in Spring MVC World and I a question for you.

I have created a new Spring MVC project by the STS template.

So now I have a minimal project that, once that is executed, show an Hello World message with the current date and time shown

This is the code of the only controller class of this project:

package org.gnagna.bla;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

/**
 * Simply selects the home view to render by returning its name.
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate );

    return "home";
}

}

So there is only one method called called home that handled HTTP GET Call toward the "/" URL, ok this is clear for me.

The thing that this is not clead is about the input parameter of this method, as you can see this method receives two input parameter:

1) The model

2) A Locale object that contain some information about the user

But: who create this Locale object and when this is passed as input parameter in my controller?

Tnx

Andrea


Solution

  • A LocaleResolver is doing that.

    One such resolver is eventually used by the HandlerMethodInvokere to inspect the parameters of the @RequestMapping method that you are invoking (the "home" method in your case). When it comes across a Locale parameter it simply uses the locale resolver to fetch a Locale object to pass as argument there.

    You can see more information about it here: http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch16s06.html

    http://templth.wordpress.com/2010/07/21/configuring-locale-switching-with-spring-mvc-3/

    http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/