[英]Parameter of a controller method in Spring MVC
我在Spring MVC World中還很陌生,因此我想向您提出一個問題。
我已經通過STS模板創建了一個新的Spring MVC項目。
因此,現在我有一個最小的項目,該項目一旦執行,就會顯示Hello World消息,並顯示當前日期和時間
這是該項目的唯一控制器類的代碼:
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";
}
}
因此,只有一種稱為home的方法可以處理對“ /” URL的HTTP GET調用,對我來說這很清楚。
這不是線索,是關於此方法的輸入參數的,因為您可以看到此方法收到兩個輸入參數:
1)模型
2)包含有關用戶信息的Locale對象
但是:誰創建了此Locale對象,以及何時將其作為輸入參數傳遞到我的控制器中?
TNX
安德里亞
LocaleResolver正在這樣做。
HandlerMethodInvokere最終使用一種這樣的解析器來檢查您正在調用的@RequestMapping方法的參數(在您的情況下為“ home”方法)。 當遇到Locale參數時,它僅使用語言環境解析器來獲取Locale對象作為參數傳遞。
您可以在這里查看有關它的更多信息: 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/
在GET請求中,您可以使用該請求的特殊參數(例如?language=en
將語言環境信息發送到服務器。 但是問題是您的servlet容器如何知道language
參數是承載您的語言環境信息的參數。 為了讓Spring MVC容器知道這個特殊的語言環境參數,您需要兩個像下面這樣在targer-servlet.xml
添加特殊的攔截器:
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language" />
</bean>
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" >
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
現在,您的servlet容器知道了與GET請求一起傳遞的locale參數的值。 但是仍然需要有人根據所選的語言鏈接來更改語言環境,並相應地顯示來自屬性文件的消息。 有一個名為localeResolver
的特殊bean可以進行救援,例如下面的波紋管:
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
現在,如果您想在GET請求處理程序方法中使用語言環境對象,則可以編寫方法簽名,例如public String home(Locale locale, Model model)
(就像您所做的一樣)。 然后,您的servlet容器將獲得額外的工作,即在調用該語言環境對象之前將其作為方法參數,然后像魔術一樣將其放入方法中!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.