Bean Validation 1.1(JSR-349)到SpringMVC
到目前为止,请求已经能交给我们的处理器进行处理了,接下来的事情是要进行收集数据啦,接下来我们看看我们能从请求中收集到哪些数据,如图6-11:
图6-11
1、@RequestParam绑定单个请求参数值;
2、@PathVariable绑定URI模板变量值;
3、@CookieValue绑定Cookie数据值
4、@RequestHeader绑定请求头数据;
5、@ModelValue绑定参数到命令对象;
6、@SessionAttributes绑定命令对象到session;
7、@RequestBody绑定请求的内容区数据并能进行自动类型转换等。
8、@RequestPart绑定“multipart/data”数据,除了能绑定@RequestParam能做到的请求参数外,还能绑定上传的文件等。
除了上边提到的注解,我们还可以通过如HttpServletRequest等API得到请求数据,但推荐使用注解方式,因为使用起来更简单。
接下来先看一下功能处理方法支持的参数类型吧。
6.6.0、功能处理方法支持的参数类型
在继续学习之前,我们需要首先看看功能处理方法支持哪些类型的形式参数,以及他们的具体含义。
一、ServletRequest/HttpServletRequest 和 ServletResponse/HttpServletResponse
- public String requestOrResponse (
- ServletRequest servletRequest, HttpServletRequest httpServletRequest,
- ServletResponse servletResponse, HttpServletResponse httpServletResponse
- )
二、InputStream/OutputStream 和 Reader/Writer
- public void inputOrOutBody(InputStream requestBodyIn, OutputStream responseBodyOut)
- throws IOException {
- responseBodyOut.write("success".getBytes());
- }
responseBodyOut:获取相应的内容区字节流,等价于response.getOutputStream()。
- public void readerOrWriteBody(Reader reader, Writer writer)
- throws IOException {
- writer.write("hello");
- }
writer:获取相应的内容区字符流,等价于response.getWriter()。
InputStream/OutputStream 和 Reader/Writer两组不能同时使用,只能使用其中的一组。
三、WebRequest/NativeWebRequest
WebRequest是Spring Web MVC提供的统一请求访问接口,不仅仅可以访问请求相关数据(如参数区数据、请求头数据,但访问不到Cookie区数据),还可以访问会话和上下文中的数据;NativeWebRequest继承了WebRequest,并提供访问本地Servlet API的方法。
- public String webRequest(WebRequest webRequest, NativeWebRequest nativeWebRequest) {
- System.out.println(webRequest.getParameter("test"));//①得到请求参数test的值
- webRequest.setAttribute("name", "value", WebRequest.SCOPE_REQUEST);//②
- System.out.println(webRequest.getAttribute("name", WebRequest.SCOPE_REQUEST));
- HttpServletRequest request =
- nativeWebRequest.getNativeRequest(HttpServletRequest.class);//③
- HttpServletResponse response =
- nativeWebRequest.getNativeResponse(HttpServletResponse.class);
- return "success";
- }
② webRequest.setAttribute/getAttribute:到指定的作用范围内取/放属性数据,Servlet定义的三个作用范围分别使用如下常量代表:
SCOPE_REQUEST :代表请求作用范围;
SCOPE_SESSION :代表会话作用范围;
SCOPE_GLOBAL_SESSION :代表全局会话作用范围,即ServletContext上下文作用范围。
③ nativeWebRequest.getNativeRequest/nativeWebRequest.getNativeResponse:得到本地的Servlet API。
四、HttpSession
- public String session(HttpSession session) {
- System.out.println(session);
- return "success";
- }
注意:session访问不是线程安全的,如果需要线程安全,需要设置AnnotationMethodHandlerAdapter或RequestMappingHandlerAdapter的synchronizeOnSession属性为true,即可线程安全的访问session。
五、命令/表单对象
Spring Web MVC能够自动将请求参数绑定到功能处理方法的命令/表单对象上。
- @RequestMapping(value = "/commandObject", method = RequestMethod.GET)
- public String toCreateUser(HttpServletRequest request, UserModel user) {
- return "customer/create";
- }
- @RequestMapping(value = "/commandObject", method = RequestMethod.POST)
- public String createUser(HttpServletRequest request, UserModel user) {
- System.out.println(user);
- return "success";
- }
六、Model、Map、ModelMap
Spring Web MVC 提供Model、Map或ModelMap让我们能去暴露渲染视图需要的模型数据。
- @RequestMapping(value = "/model")
- public String createUser(Model model, Map model2, ModelMap model3) {
- model.addAttribute("a", "a");
- model2.put("b", "b");
- model3.put("c", "c");
- System.out.println(model == model2);
- System.out.println(model2 == model3);
- return "success";}
虽然此处注入的是三个不同的类型(Model model, Map model2, ModelMap model3),但三者是同一个对象,如图6-12所示:
图6-11
AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter将使用BindingAwareModelMap作为模型对象的实现,即此处我们的形参(Model model, Map model2, ModelMap model3)都是同一个BindingAwareModelMap实例。
此处还有一点需要我们注意:
- @RequestMapping(value = "/mergeModel")
- public ModelAndView mergeModel(Model model) {
- model.addAttribute("a", "a");//①添加模型数据
- ModelAndView mv = new ModelAndView("success");
- mv.addObject("a", "update");//②在视图渲染之前更新③处同名模型数据
- model.addAttribute("a", "new");//③修改①处同名模型数据
- //视图页面的a将显示为"update" 而不是"new"
- return mv;
- }
七、Errors/BindingResult
- @RequestMapping(value = "/error1")
- public String error1(UserModel user, BindingResult result)
- @RequestMapping(value = "/error2")
- public String error2(UserModel user, BindingResult result, Model model) {
以上代码都能获取错误对象。
Spring3.1之前(使用AnnotationMethodHandlerAdapter)错误对象必须紧跟在命令对象/表单对象之后,如下定义是错误的:
- @RequestMapping(value = "/error4")
- public String error4(UserModel user, Model model, Errors errors)
- }
Errors及BindingResult的详细使用请参考4.16.2数据验证。
八、HttpHeaders
2.在类级别注入HttpServletRequest
建议使用第二种方法,这样可避免每个方法都加入HttpHeaders参数
- @Controller
- @RequestMapping("/hello")
- public class HelloController {
- @Autowired
- private HttpServletRequest request;
- @RequestMapping(value="/printname/{name}", method=RequestMethod.GET)
- public String printName(@PathVariable String name,
- @RequestHeader HttpHeaders headers) {
- System.out.println("from request:" + request.getHeader("code"));
- System.out.println("from parameter:" + headers.getFirst("code"));
- return "hello";
- }
- }
九、其他杂项
java.util.Locale:
得到当前请求的本地化信息,默认等价于ServletRequest.getLocale(),如果配置LocaleResolver解析器则由它决定Locale,后续介绍;
java.security.Principal:
该主体对象包含了验证通过的用户信息,等价于HttpServletRequest.getUserPrincipal()。
以上测试在cn.javass.chapter6.web.controller.paramtype.MethodParamTypeController中。
其他功能处理方法的形式参数类型(如HttpEntity、UriComponentsBuilder、SessionStatus、RedirectAttributes)将在后续章节详细讲解。
6.6.1、 RequestMapping 用法详解之地址映射
@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性,下面我们把她分成三类进行说明。
1、 value, method;
value:
method:
2、 consumes,produces;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces:
3、 params,headers;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
示例:
1、value / method 示例
默认RequestMapping("....str...")即为value的值;
- @Controller
- @RequestMapping("/appointments")
- public
class AppointmentsController { -
-
private final AppointmentBook appointmentBook; -
-
@Autowired -
public AppointmentsController(AppointmentBook appointmentBook) { -
this.appointmentBook = appointmentBook; -
} -
-
@RequestMapping(method = RequestMethod.GET) -
public Map get() { -
return appointmentBook.getAppointmentsForToday(); -
} -
-
@RequestMapping(value="/{day}", method = RequestMethod.GET) -
public Map getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) { -
return appointmentBook.getAppointmentsForDay(day); -
} -
-
@RequestMapping(value="/new", method = RequestMethod.GET) -
public AppointmentForm getNewForm() { -
return new AppointmentForm(); -
} -
-
@RequestMapping(method = RequestMethod.POST) -
public String add(@Valid AppointmentForm appointment, BindingResult result) { -
if (result.hasErrors()) { -
return "appointments/new"; -
} -
appointmentBook.addAppointment(appointment); -
return "redirect:/appointments"; -
} - }
value的uri值为以下三类:
A) 可以指定为普通的具体值;
B)
C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);
example B)
- @RequestMapping(value="/owners/{ownerId}",
method=RequestMethod.GET) - public
String findOwner(@PathVariable String ownerId, Model model) { -
Owner owner = ownerService.findOwner(ownerId); -
model.addAttribute("owner", owner); -
return "displayOwner"; - }
example C)
- @RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
-
public void handle(@PathVariable String version, @PathVariable String extension) { -
// ... -
} - }
2 consumes / produces 示例
cousumes的样例:
- @Controller
- @RequestMapping(value
= "/pets", method = RequestMethod.POST, consumes="application/json") - public
void addPet(@RequestBody Pet pet, Model model) { -
// implementation omitted - }
produces的样例:
- @Controller
- @RequestMapping(value
= "/pets/{petId}", method = RequestMethod.GET, produces="application/json") - @ResponseBody
- public
Pet getPet(@PathVariable String petId, Model model) { -
// implementation omitted - }
方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;
3 params / headers 示例
params的样例:
- @Controller
- @RequestMapping("/owners/{ownerId}")
- public
class RelativePathUriTemplateC ontroller { -
-
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue") -
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { -
// implementation omitted -
} - }
headers的样例:
- @Controller
- @RequestMapping("/owners/{ownerId}")
- public
class RelativePathUriTemplateC ontroller { -
- @RequestMapping(value
= "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/") -
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { -
// implementation omitted -
} - }
http://www.ifeng.com/
”的请求;
上面仅仅介绍了,RequestMapping指定的方法处理哪些请求,下面一篇将讲解怎样处理request提交的数据(数据绑定)和返回的数据。
6.6.2、@RequestParam绑定单个请求参数值
@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。
请求中包含username参数(如/requestparam1?username=zhang),则自动传入。
此处要特别注意:右击项目,选择“属性”,打开“属性对话框”,选择“Java Compiler”然后再打开的选项卡将“Add variable attributes to generated class files”取消勾选,意思是不将局部变量信息添加到类文件中,如图6-12所示:
图6-12
当你在浏览器输入URL,如“requestparam1?username=123”时会报如下错误
Name for argument type [java.lang.String] not available, and parameter name information not found in class file either,表示得不到功能处理方法的参数名,此时我们需要如下方法进行入参:
即通过@RequestParam("username")明确告诉Spring Web MVC使用username进行入参。
接下来我们看一下@RequestParam注解主要有哪些参数:
value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;
defaultValue:默认值,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties['java.vm.version']}”。
表示请求中可以没有名字为username的参数,如果没有默认为null,此处需要注意如下几点:
原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。
Boolean包装类型类型:默认Boolean.FALSE,其他引用类型默认为null。
- public String requestparam5(
- @RequestParam(value="username", required=true, defaultValue="zhang") String username)
表示如果请求中没有名字为username的参数,默认值为“zhang”。
如果请求中有多个同名的应该如何接收呢?如给用户授权时,可能授予多个权限,首先看下如下代码:
如果请求参数类似于url?role=admin&rule=user,则实际roleList参数入参的数据为“admin,user”,即多个数据之间使用“,”分割;我们应该使用如下方式来接收多个请求参数:
或
到此@RequestParam我们就介绍完了,以上测试代码在cn.javass.chapter6.web.controller. paramtype.RequestParamTypeController中。
6.6.3、@PathVariable绑定URI模板变量值
@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。
- @RequestMapping(value="/users/{userId}/topics/{topicId}")
- public String test(
- @PathVariable(value="userId") int userId,
- @PathVariable(value="topicId") int topicId)
如请求的URL为“控制器URL/users/123/topics/456”,则自动将URL中模板变量{userId}和{topicId}绑定到通过@PathVariable注解的同名参数上,即入参后userId=123、topicId=456。代码在PathVariableTypeController中。
留意到spring mvc 3.1中 @PathVariable的两个增强,其中:
1)
- @RequestMapping("/people/{firstName}/{lastName}/SSN")
- public String find(Person person,
- @PathVariable String firstName,
- @PathVariable String lastName) {
- person.setFirstName(firstName);
- person.setLastName(lastName);
- }
这个在旧的版本中,要强制进行set,在新版本中,不用这样set了,可以这样:
- @RequestMapping("/people/{firstName}/{lastName}/SSN")
- public String search(Person person) {
- // person.getFirstName() and person.getLastName() are populated
- }
2) redirect中也可以和@PathVariable中一致了,原来的
- @RequestMapping(
- value="/groups/{group}/events/{year}/{month}/{slug}/rooms",
- method=RequestMethod.POST)
- public String createRoom(
- @PathVariable String group, @PathVariable Integer year,
- @PathVariable Integer month, @PathVariable String slug) {
- // ...
- return "redirect:/groups/" + group + "/events/" + year + "/" + month + "/" + slug;
- }
现在:
- @RequestMapping(
- value="/groups/{group}/events/{year}/{month}/{slug}/rooms",
- method=RequestMethod.POST)
- public String createRoom(
- @PathVariable String group, @PathVariable Integer year,
- @PathVariable Integer month, @PathVariable String slug) {
- // ...
- return "redirect:/groups/{group}/events/{year}/{month}/{slug}";
- }
6.6.4、@CookieValue绑定Cookie数据值
@CookieValue用于将请求的Cookie数据映射到功能处理方法的参数上。
如上配置将自动将JSESSIONID值入参到sessionId参数上,defaultValue表示Cookie中没有JSESSIONID时默认为空。
传入参数类型也可以是javax.servlet.http.Cookie类型。
测试代码在CookieValueTypeController中。@CookieValue也拥有和@RequestParam相同的三个参数,含义一样。
6.6.5、@RequestHeader绑定请求头数据
@RequestHeader用于将请求的头信息区数据映射到功能处理方法的参数上。
- @RequestMapping(value="/header")
- public String test(
- @RequestHeader("User-Agent") String userAgent,
- @RequestHeader(value="Accept") String[] accepts)
如上配置将自动将请求头“User-Agent”值入参到userAgent参数上,并将“Accept”请求头值入参到accepts参数上。测试代码在HeaderValueTypeController中。
@RequestHeader也拥有和@RequestParam相同的三个参数,含义一样。
6.6.6、@ModelAttribute绑定请求参数到命令对象
@ModelAttribute一个具有如下三个作用:
①绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;
②暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;
③暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。
一、绑定请求参数到命令对象
如用户登录,我们需要捕获用户登录的请求参数(用户名、密码)并封装为用户对象,此时我们可以使用@ModelAttribute绑定多个请求参数到我们的命令对象。
和6.6.1一节中的五、命令/表单对象功能一样。只是此处多了一个注解@ModelAttribute("user"),它的作用是将该绑定的命令对象以“user”为名称添加到模型对象中供视图页面展示使用。我们此时可以在视图页面使用${user.username}来获取绑定的命令对象的属性。
绑定请求参数到命令对象支持对象图导航式的绑定,如请求参数包含“?username=zhang&password=123&workInfo.city=bj”自动绑定到user中的workInfo属性的city属性中。
- @RequestMapping(value="/model2/{username}")
- public String test2(@ModelAttribute("model") DataBinderTestModel model) {
DataBinderTestModel相关模型请从第三章拷贝过来,请求参数到命令对象的绑定规则详见【4.16.1、数据绑定】一节,URI模板变量也能自动绑定到命令对象中,当你请求的URL中包含“bool=yes&schooInfo.specialty=computer&hobbyList[0]=program&hobbyList[1]=music&map[key1]=value1&map[key2]=value2&state=blocked”会自动绑定到命令对象上。
当URI模板变量和请求参数同名时,URI模板变量具有高优先权。
二、暴露表单引用对象为模型数据
- @ModelAttribute("cityList")
- public List<String> cityList() {
- return Arrays.asList("北京", "山东");
- }
如上代码会在执行功能处理方法之前执行,并将其自动添加到模型对象中,在功能处理方法中调用Model 入参的containsAttribute("cityList")将会返回true。
- @ModelAttribute("user") //①
- public UserModel getUser(@RequestParam(value="username", defaultValue="") String username) {
- //TODO 去数据库根据用户名查找用户对象
- UserModel user = new UserModel();
- user.setRealname("zhang");
- return user;
- }
如你要修改用户资料时一般需要根据用户的编号/用户名查找用户来进行编辑,此时可以通过如上代码查找要编辑的用户。
也可以进行一些默认值的处理。
- @RequestMapping(value="/model1") //②
- public String test1(@ModelAttribute("user") UserModel user, Model model)
此处我们看到①和②有同名的命令对象,那Spring Web MVC内部如何处理的呢:
(1、首先执行@ModelAttribute注解的方法,准备视图展示时所需要的模型数据;@ModelAttribute注解方法形式参数规则和@RequestMapping规则一样,如可以有@RequestParam等;
(2、执行@RequestMapping注解方法,进行模型绑定时首先查找模型数据中是否含有同名对象,如果有直接使用,如果没有通过反射创建一个,因此②处的user将使用①处返回的命令对象。即②处的user等于①处的user。
三、暴露@RequestMapping方法返回值为模型数据
大家可以看到返回值类型是命令对象类型,而且通过@ModelAttribute("user2")注解,此时会暴露返回值到模型数据(名字为user2)中供视图展示使用。那哪个视图应该展示呢?此时Spring Web MVC会根据RequestToViewNameTranslator进行逻辑视图名的翻译,详见【4.15.5、RequestToViewNameTranslator】一节。
此时又有问题了,@RequestMapping注解方法的入参user暴露到模型数据中的名字也是user2,其实我们能猜到:
(3、@ModelAttribute注解的返回值会覆盖@RequestMapping注解方法中的@ModelAttribute注解的同名命令对象。
四、匿名绑定命令参数
- public String test4(@ModelAttribute UserModel user, Model model)
- 或
- public String test5(UserModel user, Model model)
此时我们没有为命令对象提供暴露到模型数据中的名字,此时的名字是什么呢?Spring Web MVC自动将简单类名(首字母小写)作为名字暴露,如“cn.javass.chapter6.model.UserModel”暴露的名字为“userModel”。
对于集合类型(Collection接口的实现者们,包括数组),生成的模型对象属性名为“简单类名(首字母小写)”+“List”,如List<String>生成的模型对象属性名为“stringList”,List<UserModel>生成的模型对象属性名为“userModelList”。
其他情况一律都是使用简单类名(首字母小写)作为模型对象属性名,如Map<String, UserModel>类型的模型对象属性名为“map”。
6.6.7、@SessionAttributes绑定命令对象到session
有时候我们需要在多次请求之间保持数据,一般情况需要我们明确的调用HttpSession的API来存取会话数据,如多步骤提交的表单。Spring Web MVC提供了@SessionAttributes进行请求间透明的存取会话数据。
- //1、在控制器类头上添加@SessionAttributes注解
- @SessionAttributes(value = {"user"}) //①
- public class SessionAttributeController
- //2、@ModelAttribute注解的方法进行表单引用对象的创建
- @ModelAttribute("user") //②
- public UserModel initUser()
- //3、@RequestMapping注解方法的@ModelAttribute注解的参数进行命令对象的绑定
- @RequestMapping("/session1") //③
- public String session1(@ModelAttribute("user") UserModel user)
- //4、通过SessionStatus的setComplete()方法清除@SessionAttributes指定的会话数据
- @RequestMapping("/session2") //③
- public String session(@ModelAttribute("user") UserModel user, SessionStatus status) {
- if(true) { //④
- status.setComplete();
- }
- return "success";
- }
@SessionAttributes(value = {"user"})含义:
@SessionAttributes(value = {"user"}) 标识将模型数据中的名字为“user” 的对象存储到会话中(默认HttpSession),此处value指定将模型数据中的哪些数据(名字进行匹配)存储到会话中,此外还有一个types属性表示模型数据中的哪些类型的对象存储到会话范围内,如果同时指定value和types属性则那些名字和类型都匹配的对象才能存储到会话范围内。
包含@SessionAttributes的执行流程如下所示:
① 首先根据@SessionAttributes注解信息查找会话内的对象放入到模型数据中;
② 执行@ModelAttribute注解的方法:如果模型数据中包含同名的数据,则不执行@ModelAttribute注解方法进行准备表单引用数据,而是使用①步骤中的会话数据;如果模型数据中不包含同名的数据,执行@ModelAttribute注解的方法并将返回值添加到模型数据中;
③ 执行@RequestMapping方法,绑定@ModelAttribute注解的参数:查找模型数据中是否有@ModelAttribute注解的同名对象,如果有直接使用,否则通过反射创建一个;并将请求参数绑定到该命令对象;
此处需要注意:如果使用@SessionAttributes注解控制器类之后,③步骤一定是从模型对象中取得同名的命令对象,如果模型数据中不存在将抛出HttpSessionRequiredException Expected session attribute ‘user’(Spring3.1)
或HttpSessionRequiredException Session attribute ‘user’ required - not found in session(Spring3.0)异常。
④ 如果会话可以销毁了,如多步骤提交表单的最后一步,此时可以调用SessionStatus对象的setComplete()标识当前会话的@SessionAttributes指定的数据可以清理了,此时当@RequestMapping功能处理方法执行完毕会进行清理会话数据。
我们通过Spring Web MVC的源代码验证一下吧,此处我们分析的是Spring3.1的RequestMappingHandlerAdapter,读者可以自行验证Spring3.0的AnnotationMethodHandlerAdapter,流程一样:
(1、RequestMappingHandlerAdapter.invokeHandlerMethod
- //1、RequestMappingHandlerAdapter首先调用ModelFactory的initModel方法准备模型数据:
- modelFactory.initModel(webRequest, mavContainer, requestMappingMethod);
- //2、调用@RequestMapping注解的功能处理方法
- requestMappingMethod.invokeAndHandle(webRequest, mavContainer);
- //3、更新/合并模型数据
- modelFactory.updateModel(webRequest, mavContainer);
(2、ModelFactory.initModel
- Map<String, ?> attributesInSession = this.sessionAttributesHandler.retrieveAttributes(request);
- //1.1、将与@SessionAttributes注解相关的会话对象放入模型数据中
- mavContainer.mergeAttributes(attributesInSession);
- //1.2、调用@ModelAttribute方法添加表单引用对象
- invokeModelAttributeMethods(request, mavContainer);
- //1.3、验证模型数据中是否包含@SessionAttributes注解相关的会话对象,不包含抛出异常
- for (String name : findSessionAttributeArguments(handlerMethod)) {
- if (!mavContainer.containsAttribute(name)) {
- //1.4、此处防止在@ModelAttribute注解方法又添加了会话对象
- //如在@ModelAttribute注解方法调用session.setAttribute("user", new UserModel());
- Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
- if (value == null) {
- throw new HttpSessionRequiredException("Expected session attribute '" + name + "'");
- }
- mavContainer.addAttribute(name, value);
- }
(3、ModelFactory.invokeModelAttributeMethods
- for (InvocableHandlerMethod attrMethod : this.attributeMethods) {
- String modelName = attrMethod.getMethodAnnotation(ModelAttribute.class).value();
- //1.2.1、如果模型数据中包含同名数据则不再添加
- if (mavContainer.containsAttribute(modelName)) {
- continue;
- }
- //1.2.2、调用@ModelAttribute注解方法并将返回值添加到模型数据中,此处省略实现代码
- }
(4、requestMappingMethod.invokeAndHandle 调用功能处理方法,此处省略
(5、ModelFactory.updateMode 更新模型数据
- //3.1、如果会话被标识为完成,此时从会话中清除@SessionAttributes注解相关的会话对象
- if (mavContainer.getSessionStatus().isComplete()){
- this.sessionAttributesHandler.cleanupAttributes(request);
- }
- //3.2、如果会话没有完成,将模型数据中的@SessionAttributes注解相关的对象添加到会话中
- else {
- this.sessionAttributesHandler.storeAttributes(request, mavContainer.getModel());
- }
- //省略部分代码
到此@SessionAtrribute介绍完毕,测试代码在cn.javass.chapter6.web.controller.paramtype.SessionAttributeController中。
另外cn.javass.chapter6.web.controller.paramtype.WizardFormController是一个类似于【4.11、AbstractWizardFormController】中介绍的多步骤表单实现,此处不再贴代码,多步骤提交表单需要考虑会话超时问题,这种方式可能对用户不太友好,我们可以采取隐藏表单(即当前步骤将其他步骤的表单隐藏)或表单数据存数据库(每步骤更新下数据库数据)等方案解决。
6.6.8、@Value绑定SpEL表示式
@Value用于将一个SpEL表达式结果映射到到功能处理方法的参数上。
到此数据绑定我们就介绍完了,对于没有介绍的方法参数和注解(包括自定义注解)在后续章节进行介绍。接下来我们学习下数据类型转换吧。
AJAX与spring mvc交互
技术关键点是:
1、返回字符串,并且是ResponseBody
2、设置MIME type是 text/html
代码如下:
- @ResponseBody
- @RequestMapping(value="/callJs",produces = "text/html; charset=UTF-8")
- public String callJs()throws Exception{
- return "<script>parent.alert('Hello Js');</script>";
- }
(1)简单交互:
<table style="width: 100%" class="table" cellspacing="1" cellpadding="1" border="0">
<tr><td class="ti1" colSpan="2">请选择审讯室</td></tr>
<tr><td class="ti2hui">审讯室名称</td><td class="ti1cu">
<select id="roomid" name="roomid" >
<c:forEach items="${roomlist}" var="room">
<option value ="${room.id}">${room.name}</option>
</c:forEach>
</select>
</td></tr>
<tr><td class="ti2hui" colSpan="2" align="center"><input type="button" οnclick="setshow()" value="确定"/> </td></tr>
</table>
------------------------------ajax-----提交的参数可以通过url提交,也可以用data:{}方式提交----------------------------------------------
function setshow(){
$.ajax( {
type : "POST",
url : "<%=request.getContextPath()%>/initroom.do?method=set",
data : {
'room' : $("#roomid").find('option:selected').text(),
'roomid' :$("#roomid").val()
},
dataType: "json",
success : function(data) {
if(data.success){
alert("设置成功!");
}
else{
alert("设置失败!");
}
},
error :function(){
alert("网络连接出错!");
}
});
}
------------------------spring mvc-------------------------------------------------
@RequestMapping(params = "method=set")
public void jump(HttpSession session,HttpServletRequest request, HttpServletResponse response) throws Exception{
String roomid= request.getParameter("roomid");
String room= request.getParameter("room");
session.setAttribute("ROOMID", roomid);
session.setAttribute("ROOMNAME", room);
System.out.println("session set:"+room+"=="+roomid);
response.setCharacterEncoding("utf-8");
response.getWriter().write("{\"success\":true }");
response.getWriter().flush();
}
(2)springmvc 返回信息到ajax:
import com.googlecode.jsonplugin.JSONUtil;
List<Records> recordList = new ArrayList<Records>();
//获取recordlist操作省略
response.setCharacterEncoding("utf-8");
response.getWriter().write("{\"success\":true, \"data\":" + JSONUtil.serialize(recordList) + "}");
response.getWriter().flush();
-------------------------------ajax处理序列化对象--------------------------------------------
var text = '';
$(data.data).each(function() {
text = text + '<li οnclick="selectRecord(' + this.id + ')" style="cursor: pointer; height:20px; list-style:none; valign: center;line-height:23px;"><div style="float:left; width:15px; height:20px; background:url(Images/record_icon.png) no-repeat center;"></div>' + this.name + '</li>';
});
$('#recordDiv').html(text);
(3)最先进的做法:
在 Spring mvc3中,响应、接受 JSON都十分方便。
使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。
Spring这个转换是靠org.codehaus.jackson这个组件来实现的,所有需要引入jackson-core-asl和org.codehaus.jackson两个jar包
- <title>Spring MVC</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
- <script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
- <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/user/index.js"></script>
- </head>
- <body>
- <div id="info"></div>
- <form action="add" method="post" id="form">
- 编号:<input type="text" name="id"/>
- 姓名:<input type="text" name="username"/>
- 年龄:<input type="text" name="age"/>
- <input type="button" value="提交" id="submit"/>
- </form>
- </body>
- </html>
- //将一个表单的数据返回成JSON对象
- $.fn.serializeObject = function() {
- var o = {};
- var a = this.serializeArray();
- $.each(a, function() {
- if (o[this.name]) {
- if (!o[this.name].push) {
- o[this.name] = [ o[this.name] ];
- }
- o[this.name].push(this.value || '');
- } else {
- o[this.name] = this.value || '';
- }
- });
- return o;
- };
- $(document).ready(
- function() {
- jQuery.ajax( {
- type : 'GET',
- contentType : 'application/json',
- url : 'user/list',
- dataType : 'json',
- success : function(data) {
- if (data && data.success == "true") {
- $('#info').html("共" + data.total + "条数据。<br/>");
- $.each(data.data, function(i, item) {
- $('#info').append(
- "编号:" + item.id + ",姓名:" + item.username
- + ",年龄:" + item.age);
- });
- }
- },
- error : function() {
- alert("error")
- }
- });
- $("#submit").click(function() {
- var jsonuserinfo = $.toJSON($('#form').serializeObject());
- alert(jsonuserinfo);
- jQuery.ajax( {
- type : 'POST',
- contentType : 'application/json',
- url : 'user/add',
- data : jsonuserinfo,
- dataType : 'json',
- success : function(data) {
- alert("新增成功!");
- },
- error : function(data) {
- alert("error")
- }
- });
- });
- });
- @Controller
- @RequestMapping("/user")
- public class DemoController {
- private Logger logger = LoggerFactory.getLogger(DemoController.class);
- @RequestMapping(value = "/list", method = RequestMethod.GET)
- @ResponseBody
- public Map<String, Object> getUserList() {
- logger.info("列表");
- List<UserModel> list = new ArrayList<UserModel>();
- UserModel um = new UserModel();
- um.setId("1");
- um.setUsername("sss");
- um.setAge(222);
- list.add(um);
- Map<String, Object> modelMap = new HashMap<String, Object>(3);
- modelMap.put("total", "1");
- modelMap.put("data", list);
- modelMap.put("success", "true");
- return modelMap;
- }
- @RequestMapping(value = "/add", method = RequestMethod.POST)
- @ResponseBody
- public Map<String, String> addUser(@RequestBody UserModel model) {
- logger.info("新增");
- logger.info("捕获到前台传递过来的Model,名称为:" + model.getUsername());
- Map<String, String> map = new HashMap<String, String>(1);
- map.put("success", "true");
- return map;
- }
- }
重定向视图
- “redirect:index”
- view.setViewName("redirect:index");
- view.setView(new RedirectView("/index", false));
- RedirectView redirectView = new RedirectView("/index{id}");
- redirectView.setExpandUriTemplateVariables(false);
- redirectView.setExposeModelAttributes(false);
- view.setView(redirectView);
自定义拦截器详解
- package org.springframework.web.servlet;
- import Javax.servlet.http.HttpServletRequest;
- import Javax.servlet.http.HttpServletResponse;
- public interface HandlerInterceptor {
- // preHandle()方法在业务处理器处理请求之前被调用
- boolean preHandle(HttpServletRequest request,
- HttpServletResponse response,
- Object handler)
- throws Exception;
- // postHandle()方法在业务处理器处理请求之后被调用
- void postHandle(
- HttpServletRequest request, HttpServletResponse
- response, Object
- handler, ModelAndView modelAndView)
- throws Exception;
- // afterCompletion()方法在DispatcherServlet完全处理完请求后被调用
- void afterCompletion(
- HttpServletRequest request, HttpServletResponse
- response, Object
- handler, Exception ex)
- throws Exception;
- }
下面对代码中的三个方法进行解释。
preHandle():这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求request进行处理。如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器,或者是业务处理器去进行处理,则返回true;如果程序员决定不需要再调用其他的组件去处理请求,则返回false。
postHandle():这个方法在业务处理器处理完请求后,但是DispatcherServlet向客户端返回请求前被调用,在该方法中对用户请求request进行处理。
afterCompletion():这个方法在DispatcherServlet完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作。
下面通过一个例子来说明如何使用SpringMVC框架的拦截器。
现在要编写一个拦截器,拦截所有不在工作时间的请求,把这些请求转发到一个特定的静态页面,而不对它们的请求进行处理。
首先编写TimeInterceptor.Java,代码如下:
- package com.yjde.web.interceptor;
- import java.util.Calendar;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
- public class TimeInterceptor extends HandlerInterceptorAdapter {
- // 继承HandlerInterceptorAdapter类
- private int openingTime; // openingTime 属性指定上班时间
- private int closingTime; // closingTime属性指定下班时间
- private String outsideOfficeHoursPage;// outsideOfficeHoursPage属性指定错误提示页面的URL
- // 重写 preHandle()方法,在业务处理器处理请求之前对该请求进行拦截处理
- public boolean preHandle(HttpServletRequest request,
- HttpServletResponse response, Object handler) throws Exception {
- Calendar cal = Calendar.getInstance();
- int hour = cal.get(Calendar.HOUR_OF_DAY); // 获取当前时间
- if (openingTime <= hour && hour < closingTime) { // 判断当前是否处于工作时间段内
- return true;
- } else {
- response.sendRedirect(outsideOfficeHoursPage); // 返回提示页面
- return false;
- }
- }
- public void postHandle(HttpServletRequest request,
- HttpServletResponse response, Object o, ModelAndView mav)
- throws Exception {
- System.out.println("postHandle");
- }
- public void afterCompletion(HttpServletRequest request,
- HttpServletResponse response, Object o, Exception excptn)
- throws Exception {
- System.out.println("afterCompletion");
- }
- public int getOpeningTime() {
- return openingTime;
- }
- public void setOpeningTime(int openingTime) {
- this.openingTime = openingTime;
- }
- public int getClosingTime() {
- return closingTime;
- }
- public void setClosingTime(int closingTime) {
- this.closingTime = closingTime;
- }
- public String getOutsideOfficeHoursPage() {
- return outsideOfficeHoursPage;
- }
- public void setOutsideOfficeHoursPage(String outsideOfficeHoursPage) {
- this.outsideOfficeHoursPage = outsideOfficeHoursPage;
- }
- }
- // 可以看出,上面的代码重载了preHandle()方法,该方法在业务处理器处理请求之前被调用。在该方法中,首先获得当前的时间,判断其是否在
- // openingTime和closingTime之间,如果在,返回true,这样才会调用业务控制器去处理该请求;否则直接转向一个页面,返回false,这样该请求就不会被处理。
可以看出,上面的代码重载了preHandle()方法,该方法在业务处理器处理请求之前被调用。在该方法中,首先获得当前的时间,判断其是否在 openingTime和closingTime之间,如果在,返回true,这样才会调用业务控制器去处理该请求;否则直接转向一个页面,返回 false,这样该请求就不会被处理。
下面是在dispatcher-servlet.xml中对拦截器进行的配置,代码如下:
- <pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!--
- 使Spring支持自动检测组件,如注解的Controller
- -->
- <context:component-scan base-package="com.yjde.web.controller" />
- <bean id="viewResolver"
- class="org.springframework.web.servlet.view.InternalResourceViewResolver"
- p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
- <mvc:interceptors>
- <mvc:interceptor>
- <!--设置拦截的路径-->
- <mvc:mapping path="/login1.htm" />
- <mvc:mapping path="/login2.htm" />
- <bean class="com.yjde.web.interceptor.TimeInterceptor">
- <!--openingTime 属性指定上班时间-->
- <property name="openingTime">
- <value>12</value>
- </property>
- <!--closingTime属性指定下班时间-->
- <property name="closingTime">
- <value>14</value>
- </property>
- <!--outsideOfficeHoursPage属性指定提示页面的URL-->
- <property name="outsideOfficeHoursPage">
- <value>http://localhost:8080/SpringMVCInterceptor/jsp/outsideOfficeHours.jsp
- </value>
- </property>
- </bean>
- </mvc:interceptor>
- </mvc:interceptors>
- <bean id="messageSource"
- class="org.springframework.context.support.ResourceBundleMessageSource"
- p:basename="message">
- </bean>
- </beans>
国际化
一.基于浏览器请求的国际化实现:
首先配置我们项目的springservlet-config.xml文件添加的内容如下:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <!-- 国际化信息所在的文件名 --> <property name="basename" value="messages" /> <!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 --> <property name="useCodeAsDefaultMessage" value="true" /> </bean>
在com.demo.web.controllers包中添加GlobalController.java内容如下:
package com.demo.web.controllers; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.support.RequestContext; import com.demo.web.models.FormatModel; @Controller @RequestMapping(value = "/global") public class GlobalController { @RequestMapping(value="/test", method = {RequestMethod.GET}) public String test(HttpServletRequest request,Model model){ if(!model.containsAttribute("contentModel")){ //从后台代码获取国际化信息 RequestContext requestContext = new RequestContext(request); model.addAttribute("money", requestContext.getMessage("money")); model.addAttribute("date", requestContext.getMessage("date")); FormatModel formatModel=new FormatModel(); formatModel.setMoney(12345.678); formatModel.setDate(new Date()); model.addAttribute("contentModel", formatModel); } return "globaltest"; } }
这里展示模型还用系列(7)中的作为演示。
在项目中的源文件夹resources中添加messages.properties、messages_zh_CN.properties、messages_en_US.properties三个文件,其中messages.properties、messages_zh_CN.properties里面的"money", "date",为中文,messages_en_US.properties里面的为英文。
在views文件夹中添加globaltest.jsp视图,内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 下面展示的是后台获取的国际化信息:<br/> ${money}<br/> ${date}<br/> 下面展示的是视图中直接绑定的国际化信息:<br/> <spring:message code="money"/>:<br/> <spring:eval expression="contentModel.money"></spring:eval><br/> <spring:message code="date"/>:<br/> <spring:eval expression="contentModel.date"></spring:eval><br/> </body> </html>
运行测试:
更改浏览器语言顺序,刷新页面:
二.基于Session的国际化实现:
在项目的springservlet-config.xml文件添加的内容如下(第一种时添加的内容要保留):
<mvc:interceptors> <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 --> <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> </mvc:interceptors> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
更改globaltest.jsp视图为如下内容:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@taglib prefix="spring" uri="http://www.springframework.org/tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="test?langType=zh">中文</a> | <a href="test?langType=en">英文</a><br/> 下面展示的是后台获取的国际化信息:<br/> ${money}<br/> ${date}<br/> 下面展示的是视图中直接绑定的国际化信息:<br/> <spring:message code="money"/>:<br/> <spring:eval expression="contentModel.money"></spring:eval><br/> <spring:message code="date"/>:<br/> <spring:eval expression="contentModel.date"></spring:eval><br/> </body> </html>
更改GlobalController.java为如下内容:
package com.demo.web.controllers; import java.util.Date; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import org.springframework.web.servlet.support.RequestContext; import com.demo.web.models.FormatModel; @Controller @RequestMapping(value = "/global") public class GlobalController { @RequestMapping(value="/test", method = {RequestMethod.GET}) public String test(HttpServletRequest request,Model model, @RequestParam(value="langType", defaultValue="zh") String langType){ if(!model.containsAttribute("contentModel")){ if(langType.equals("zh")){ Locale locale = new Locale("zh", "CN"); request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); } else if(langType.equals("en")){ Locale locale = new Locale("en", "US"); request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); } else request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale()); //从后台代码获取国际化信息 RequestContext requestContext = new RequestContext(request); model.addAttribute("money", requestContext.getMessage("money")); model.addAttribute("date", requestContext.getMessage("date")); FormatModel formatModel=new FormatModel(); formatModel.setMoney(12345.678); formatModel.setDate(new Date()); model.addAttribute("contentModel", formatModel); } return "globaltest"; } }
运行测试:
三.基于Cookie的国际化实现:
把实现第二种方法时在项目的springservlet-config.xml文件中添加的
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
注释掉,并添加以下内容:
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
更改GlobalController.java为如下内容:
package com.demo.web.controllers; import java.util.Date; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.i18n.CookieLocaleResolver; //import org.springframework.web.servlet.i18n.SessionLocaleResolver; import org.springframework.web.servlet.support.RequestContext; import com.demo.web.models.FormatModel; @Controller @RequestMapping(value = "/global") public class GlobalController { @RequestMapping(value="/test", method = {RequestMethod.GET}) public String test(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam(value="langType", defaultValue="zh") String langType){ if(!model.containsAttribute("contentModel")){ /*if(langType.equals("zh")){ Locale locale = new Locale("zh", "CN"); request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); } else if(langType.equals("en")){ Locale locale = new Locale("en", "US"); request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); } else request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale());*/ if(langType.equals("zh")){ Locale locale = new Locale("zh", "CN"); //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); (new CookieLocaleResolver()).setLocale (request, response, locale); } else if(langType.equals("en")){ Locale locale = new Locale("en", "US"); //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,locale); (new CookieLocaleResolver()).setLocale (request, response, locale); } else //request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,LocaleContextHolder.getLocale()); (new CookieLocaleResolver()).setLocale (request, response, LocaleContextHolder.getLocale()); //从后台代码获取国际化信息 RequestContext requestContext = new RequestContext(request); model.addAttribute("money", requestContext.getMessage("money")); model.addAttribute("date", requestContext.getMessage("date")); FormatModel formatModel=new FormatModel(); formatModel.setMoney(12345.678); formatModel.setDate(new Date()); model.addAttribute("contentModel", formatModel); } return "globaltest"; } }
运行测试:
关于<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />3个属性的说明(可以都不设置而用其默认值):
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"> <!-- 设置cookieName名称,可以根据名称通过js来修改设置,也可以像上面演示的那样修改设置,默认的名称为 类名+LOCALE(即:org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE--> <property name="cookieName" value="lang"/> <!-- 设置最大有效时间,如果是-1,则不存储,浏览器关闭后即失效,默认为Integer.MAX_INT--> <property name="cookieMaxAge" value="100000"> <!-- 设置cookie可见的地址,默认是“/”即对网站所有地址都是可见的,如果设为其它地址,则只有该地址或其后的地址才可见--> <property name="cookiePath" value="/"> </bean>
四.基于URL请求的国际化的实现:
首先添加一个类,内容如下:
import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.LocaleResolver; public class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver { private Locale myLocal; public Locale resolveLocale(HttpServletRequest request) { return myLocal; } public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) { myLocal = locale; } }
然后把实现第二种方法时在项目的springservlet-config.xml文件中添加的
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
注释掉,并添加以下内容:
<bean id="localeResolver" class="xx.xxx.xxx.MyAcceptHeaderLocaleResolver"/>
“xx.xxx.xxx”是刚才添加的MyAcceptHeaderLocaleResolver 类所在的包名。
保存之后就可以在请求的URL后附上 locale=zh_CN 或 locale=en_US 如 http://xxxxxxxx?locale=zh_CN 来改变语言了,具体这里不再做演示了。
国际化部分的内容到此结束。