springmvc 注解/数据绑定

springmvc入门基础之注解和参数传递

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

Java代码   收藏代码
  1. public String requestOrResponse (  
  2.         ServletRequest servletRequest, HttpServletRequest httpServletRequest,  
  3.         ServletResponse servletResponse, HttpServletResponse httpServletResponse  
  4.     )  
 Spring Web MVC框架会自动帮助我们把相应的Servlet请求/响应(Servlet API)作为参数传递过来。

 

二、InputStream/OutputStream 和 Reader/Writer

Java代码   收藏代码
  1. public void inputOrOutBody(InputStream requestBodyIn, OutputStream responseBodyOut)  
  2.         throws IOException {  
  3. responseBodyOut.write("success".getBytes());  
  4. }  
requestBodyIn 获取请求的内容区字节流,等价于request.getInputStream();

responseBodyOut获取相应的内容区字节流,等价于response.getOutputStream()。

 

Java代码   收藏代码
  1. public void readerOrWriteBody(Reader reader, Writer writer)  
  2.         throws IOException {  
  3.     writer.write("hello");  
  4. }  
  reader 获取请求的内容区字符流,等价于request.getReader();

writer获取相应的内容区字符流,等价于response.getWriter()。

 

InputStream/OutputStream 和 Reader/Writer两组不能同时使用,只能使用其中的一组。

 

三、WebRequest/NativeWebRequest

WebRequest是Spring Web MVC提供的统一请求访问接口,不仅仅可以访问请求相关数据(如参数区数据、请求头数据,但访问不到Cookie区数据),还可以访问会话和上下文中的数据;NativeWebRequest继承了WebRequest,并提供访问本地Servlet API的方法。

Java代码   收藏代码
  1. public String webRequest(WebRequest webRequest, NativeWebRequest nativeWebRequest) {  
  2.     System.out.println(webRequest.getParameter("test"));//①得到请求参数test的值  
  3.     webRequest.setAttribute("name""value", WebRequest.SCOPE_REQUEST);//②  
  4.     System.out.println(webRequest.getAttribute("name", WebRequest.SCOPE_REQUEST));  
  5.     HttpServletRequest request =   
  6.         nativeWebRequest.getNativeRequest(HttpServletRequest.class);//③  
  7.     HttpServletResponse response =   
  8.         nativeWebRequest.getNativeResponse(HttpServletResponse.class);  
  9.         return "success";  
  10.     }  
   webRequest.getParameter:访问请求参数区的数据,可以通过getHeader()访问请求头数据;

② webRequest.setAttribute/getAttribute:到指定的作用范围内取/放属性数据,Servlet定义的三个作用范围分别使用如下常量代表:

            SCOPE_REQUEST :代表请求作用范围;

           SCOPE_SESSION :代表会话作用范围;

           SCOPE_GLOBAL_SESSION :代表全局会话作用范围,即ServletContext上下文作用范围。 

 nativeWebRequest.getNativeRequest/nativeWebRequest.getNativeResponse:得到本地的Servlet API。

 

四、HttpSession

Java代码   收藏代码
  1. public String session(HttpSession session) {  
  2.     System.out.println(session);  
  3.     return "success";  
  4. }  
 此处的session永远不为null。

 

注意:session访问不是线程安全的,如果需要线程安全,需要设置AnnotationMethodHandlerAdapter或RequestMappingHandlerAdapter的synchronizeOnSession属性为true,即可线程安全的访问session。

 

五、命令/表单对象

Spring Web MVC能够自动将请求参数绑定到功能处理方法的命令/表单对象上。

Java代码   收藏代码
  1. @RequestMapping(value = "/commandObject", method = RequestMethod.GET)  
  2. public String toCreateUser(HttpServletRequest request, UserModel user) {  
  3.     return "customer/create";  
  4. }  
  5. @RequestMapping(value = "/commandObject", method = RequestMethod.POST)  
  6. public String createUser(HttpServletRequest request, UserModel user) {  
  7.     System.out.println(user);  
  8.     return "success";  
  9. }  
 如果提交的表单(包含username和password文本域),将自动将请求参数绑定到命令对象user中去。

 

六、Model、Map、ModelMap

Spring Web MVC 提供Model、Map或ModelMap让我们能去暴露渲染视图需要的模型数据。

Java代码   收藏代码
  1. @RequestMapping(value = "/model")  
  2. public String createUser(Model model, Map model2, ModelMap model3) {  
  3.     model.addAttribute("a""a");  
  4.     model2.put("b""b");  
  5.     model3.put("c""c");  
  6.     System.out.println(model == model2);  
  7.     System.out.println(model2 == model3);  
  8.     return "success";}  

 虽然此处注入的是三个不同的类型(Model model, Map model2, ModelMap model3),但三者是同一个对象,如图6-12所示:



6-11

AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter将使用BindingAwareModelMap作为模型对象的实现,即此处我们的形参(Model model, Map model2, ModelMap model3)都是同一个BindingAwareModelMap实例。

 

此处还有一点需要我们注意:

Java代码   收藏代码
  1. @RequestMapping(value = "/mergeModel")  
  2. public ModelAndView mergeModel(Model model) {  
  3.     model.addAttribute("a""a");//①添加模型数据  
  4.     ModelAndView mv = new ModelAndView("success");  
  5.     mv.addObject("a""update");//②在视图渲染之前更新③处同名模型数据  
  6.     model.addAttribute("a""new");//③修改①处同名模型数据  
  7.     //视图页面的a将显示为"update" 而不是"new"  
  8.     return mv;  
  9. }  
 从代码中我们可以总结出功能处理方法的返回值中的模型数据(如ModelAndView)会 合并 功能处理方法形式参数中的模型数据(如Model),但如果两者之间有同名的,返回值中的模型数据会覆盖形式参数中的模型数据。

 

七、Errors/BindingResult

Java代码   收藏代码
  1. @RequestMapping(value = "/error1")  
  2. public String error1(UserModel user, BindingResult result)  

 

Java代码   收藏代码
  1. @RequestMapping(value = "/error2")  
  2. public String error2(UserModel user, BindingResult result, Model model) {  
  3.       

 

Java代码   收藏代码
  1. @RequestMapping(value = "/error3")  
  2. public String error3(UserModel user, Errors errors)   

 

以上代码都能获取错误对象。

 

Spring3.1之前(使用AnnotationMethodHandlerAdapter)错误对象必须紧跟在命令对象/表单对象之后,如下定义是错误的:

Java代码   收藏代码
  1. @RequestMapping(value = "/error4")  
  2. public String error4(UserModel user, Model model, Errors errors)  
  3.     }  
如上代码从Spring3.1开始(使用RequestMappingHandlerAdapter)将能正常工作,但还是推荐“错误对象紧跟在命令对象/表单对象之后”,这样是万无一失的。

 

Errors及BindingResult的详细使用请参考4.16.2数据验证。

 

八、HttpHeaders

1.在方法参数中加入@RequestHeader 
2.在类级别注入HttpServletRequest 
建议使用第二种方法,这样可避免每个方法都加入HttpHeaders参数 

  1. @Controller  
  2. @RequestMapping("/hello")  
  3. public class HelloController {  
  4.      @Autowired  
  5.      private HttpServletRequest request;  
  6.       
  7.      @RequestMapping(value="/printname/{name}", method=RequestMethod.GET)  
  8.      public String printName(@PathVariable String name,  
  9.               @RequestHeader HttpHeaders headers) {  
  10.           System.out.println("from request:" + request.getHeader("code"));  
  11.           System.out.println("from parameter:" + headers.getFirst("code"));  
  12.            
  13.           return "hello";  
  14.      }  
  15. }  

九、其他杂项

Java代码   收藏代码
  1. public String other(Locale locale, Principal principal)  

 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:     指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method:  指定请求的method类型, GET、POST、PUT、DELETE等;

2、 consumes,produces;

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

3、 params,headers;

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。


示例:

1、value  / method 示例

默认RequestMapping("....str...")即为value的值;

[java]  view plain copy
  1. @Controller  
  2. @RequestMapping("/appointments" 
  3. public class AppointmentsController  
  4.   
  5.     private final AppointmentBook appointmentBook;  
  6.       
  7.     @Autowired  
  8.     public AppointmentsController(AppointmentBook appointmentBook)  
  9.         this.appointmentBook appointmentBook;  
  10.      
  11.   
  12.     @RequestMapping(method RequestMethod.GET)  
  13.     public Map get()  
  14.         return appointmentBook.getAppointmentsForToday();  
  15.      
  16.   
  17.     @RequestMapping(value="/{day}"method RequestMethod.GET)  
  18.     public Map getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model)  
  19.         return appointmentBook.getAppointmentsForDay(day);  
  20.      
  21.   
  22.     @RequestMapping(value="/new"method RequestMethod.GET)  
  23.     public AppointmentForm getNewForm()  
  24.         return new AppointmentForm();  
  25.      
  26.   
  27.     @RequestMapping(method RequestMethod.POST)  
  28.     public String add(@Valid AppointmentForm appointment, BindingResult result)  
  29.         if (result.hasErrors())  
  30.             return "appointments/new" 
  31.          
  32.         appointmentBook.addAppointment(appointment);  
  33.         return "redirect:/appointments" 
  34.      
  35.  

value的uri值为以下三类:

A) 可以指定为普通的具体值;

B)  可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);

C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);


example B)

[java]  view plain copy
  1. @RequestMapping(value="/owners/{ownerId}"method=RequestMethod.GET)  
  2. public String findOwner(@PathVariable String ownerId, Model model)  
  3.   Owner owner ownerService.findOwner(ownerId);    
  4.   model.addAttribute("owner"owner);    
  5.   return "displayOwner"  
  6.  

example C)
[java]  view plain copy
  1. @RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}" 
  2.   public void handle(@PathVariable String version, @PathVariable String extension)      
  3.     // ...  
  4.    
  5.  

2 consumes / produces 示例

cousumes的样例:

[java]  view plain copy
  1. @Controller  
  2. @RequestMapping(value "/pets"method RequestMethod.POST, consumes="application/json" 
  3. public void addPet(@RequestBody Pet pet, Model model)      
  4.     // implementation omitted  
  5.  
方法仅处理request Content-Type为“application/json”类型的请求。

produces的样例:

[java]  view plain copy
  1. @Controller  
  2. @RequestMapping(value "/pets/{petId}"method RequestMethod.GET, produces="application/json" 
  3. @ResponseBody  
  4. public Pet getPet(@PathVariable String petId, Model model)      
  5.     // implementation omitted  
  6.  

方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

params / headers 示例

params的样例:

[java]  view plain copy
  1. @Controller  
  2. @RequestMapping("/owners/{ownerId}" 
  3. public class RelativePathUriTemplateController  
  4.   
  5.   @RequestMapping(value "/pets/{petId}"method RequestMethod.GET, params="myParam=myValue" 
  6.   public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model)      
  7.     // implementation omitted  
  8.    
  9.  

 仅处理请求中包含了名为“myParam”,值为“myValue”的请求;


headers的样例:

[java]  view plain copy
  1. @Controller  
  2. @RequestMapping("/owners/{ownerId}" 
  3. public class RelativePathUriTemplateController  
  4.   
  5. @RequestMapping(value "/pets"method RequestMethod.GET, headers="Referer=http://www.ifeng.com/" 
  6.   public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model)      
  7.     // implementation omitted  
  8.    
  9.  

 仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

上面仅仅介绍了,RequestMapping指定的方法处理哪些请求,下面一篇将讲解怎样处理request提交的数据(数据绑定)和返回的数据。


6.6.2、@RequestParam绑定单个请求参数值

@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。

Java代码   收藏代码
  1. public String requestparam1(@RequestParam String username)  

请求中包含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,表示得不到功能处理方法的参数名,此时我们需要如下方法进行入参:

 

Java代码   收藏代码
  1. public String requestparam2(@RequestParam("username") String username)  

 即通过@RequestParam("username")明确告诉Spring Web MVC使用username进行入参。

 

 

接下来我们看一下@RequestParam注解主要有哪些参数:

value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;

defaultValue:默认值,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties['java.vm.version']}”。

 

Java代码   收藏代码
  1. public String requestparam4(@RequestParam(value="username",required=false) String username)   

 表示请求中可以没有名字为username的参数,如果没有默认为null,此处需要注意如下几点:

 

     原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。

     Boolean包装类型类型:默认Boolean.FALSE,其他引用类型默认为null。

 

Java代码   收藏代码
  1. public String requestparam5(  
  2. @RequestParam(value="username", required=true, defaultValue="zhang") String username)   
  3.           

表示如果请求中没有名字为username的参数,默认值为“zhang”。

 

 

如果请求中有多个同名的应该如何接收呢?如给用户授权时,可能授予多个权限,首先看下如下代码:

Java代码   收藏代码
  1. public String requestparam7(@RequestParam(value="role") String roleList)  

如果请求参数类似于url?role=admin&rule=user,则实际roleList参数入参的数据为“admin,user”,即多个数据之间使用“,”分割;我们应该使用如下方式来接收多个请求参数:

Java代码   收藏代码
  1. public String requestparam7(@RequestParam(value="role") String[] roleList)     

 

Java代码   收藏代码
  1. public String requestparam8(@RequestParam(value="list") List<String> list)      

 到此@RequestParam我们就介绍完了,以上测试代码在cn.javass.chapter6.web.controller. paramtype.RequestParamTypeController中。

 

6.6.3、@PathVariable绑定URI模板变量值

@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。

 

Java代码   收藏代码
  1. @RequestMapping(value="/users/{userId}/topics/{topicId}")  
  2. public String test(  
  3.        @PathVariable(value="userId"int userId,   
  4.        @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)

Java代码   收藏代码
  1. @RequestMapping("/people/{firstName}/{lastName}/SSN")  
  2. public String find(Person person,  
  3.                    @PathVariable String firstName,  
  4.                    @PathVariable String lastName) {  
  5.     person.setFirstName(firstName);  
  6.     person.setLastName(lastName);  
  7.     
  8. }  


  这个在旧的版本中,要强制进行set,在新版本中,不用这样set了,可以这样: 
Java代码   收藏代码
  1. @RequestMapping("/people/{firstName}/{lastName}/SSN")  
  2. public String search(Person person) {  
  3.    // person.getFirstName() and person.getLastName() are populated  
  4.      
  5. }  


   

2) redirect中也可以和@PathVariable中一致了,原来的 
 
Java代码   收藏代码
  1. @RequestMapping(  
  2.     value="/groups/{group}/events/{year}/{month}/{slug}/rooms",  
  3.     method=RequestMethod.POST)  
  4. public String createRoom(  
  5.     @PathVariable String group, @PathVariable Integer year,  
  6.     @PathVariable Integer month, @PathVariable String slug) {  
  7.     // ...  
  8.     return "redirect:/groups/" + group + "/events/" + year + "/" + month + "/" + slug;  
  9. }  


  现在: 
 
Java代码   收藏代码
  1. @RequestMapping(  
  2.     value="/groups/{group}/events/{year}/{month}/{slug}/rooms",  
  3.     method=RequestMethod.POST)  
  4. public String createRoom(  
  5.     @PathVariable String group, @PathVariable Integer year,  
  6.     @PathVariable Integer month, @PathVariable String slug) {  
  7.     // ...  
  8.     return "redirect:/groups/{group}/events/{year}/{month}/{slug}";  
  9. }  

6.6.4、@CookieValue绑定Cookie数据值

@CookieValue用于将请求的Cookie数据映射到功能处理方法的参数上。

 

Java代码   收藏代码
  1. public String test(@CookieValue(value="JSESSIONID", defaultValue="") String sessionId)   

 

如上配置将自动将JSESSIONID值入参到sessionId参数上,defaultValue表示Cookie中没有JSESSIONID时默认为空。

Java代码   收藏代码
  1. public String test2(@CookieValue(value="JSESSIONID", defaultValue="") Cookie sessionId)         

传入参数类型也可以是javax.servlet.http.Cookie类型。

 

测试代码在CookieValueTypeController中。@CookieValue也拥有和@RequestParam相同的三个参数,含义一样。

6.6.5、@RequestHeader绑定请求头数据

@RequestHeader用于将请求的头信息区数据映射到功能处理方法的参数上。

Java代码   收藏代码
  1. @RequestMapping(value="/header")  
  2. public String test(  
  3.        @RequestHeader("User-Agent") String userAgent,  
  4.        @RequestHeader(value="Accept") String[] accepts)  
  5.           

如上配置将自动将请求头“User-Agent”值入参到userAgent参数上,并将“Accept”请求头值入参到accepts参数上。测试代码在HeaderValueTypeController中。

 

@RequestHeader也拥有和@RequestParam相同的三个参数,含义一样。

6.6.6、@ModelAttribute绑定请求参数到命令对象

@ModelAttribute一个具有如下三个作用:

①绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;

②暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;

③暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。

 

一、绑定请求参数到命令对象

如用户登录,我们需要捕获用户登录的请求参数(用户名、密码)并封装为用户对象,此时我们可以使用@ModelAttribute绑定多个请求参数到我们的命令对象。

 

Java代码   收藏代码
  1. public String test1(@ModelAttribute("user") UserModel user)  

和6.6.1一节中的五、命令/表单对象功能一样。只是此处多了一个注解@ModelAttribute("user"),它的作用是将该绑定的命令对象以“user”为名称添加到模型对象中供视图页面展示使用。我们此时可以在视图页面使用${user.username}来获取绑定的命令对象的属性。

 

绑定请求参数到命令对象支持对象图导航式的绑定,如请求参数包含“?username=zhang&password=123&workInfo.city=bj”自动绑定到user中的workInfo属性的city属性中。

Java代码   收藏代码
  1. @RequestMapping(value="/model2/{username}")  
  2. 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模板变量具有高优先权。

 

二、暴露表单引用对象为模型数据

Java代码   收藏代码
  1. @ModelAttribute("cityList")  
  2. public List<String> cityList() {  
  3.     return Arrays.asList("北京""山东");  
  4. }   

如上代码会在执行功能处理方法之前执行,并将其自动添加到模型对象中,在功能处理方法中调用Model 入参的containsAttribute("cityList")将会返回true。

Java代码   收藏代码
  1. @ModelAttribute("user")  //①  
  2. public UserModel getUser(@RequestParam(value="username", defaultValue="") String username) {  
  3. //TODO 去数据库根据用户名查找用户对象  
  4. UserModel user = new UserModel();  
  5. user.setRealname("zhang");  
  6.      return user;  
  7. }   

如你要修改用户资料时一般需要根据用户的编号/用户名查找用户来进行编辑,此时可以通过如上代码查找要编辑的用户。

也可以进行一些默认值的处理。

Java代码   收藏代码
  1. @RequestMapping(value="/model1"//②  
  2. public String test1(@ModelAttribute("user") UserModel user, Model model)   

此处我们看到①和②有同名的命令对象,那Spring Web MVC内部如何处理的呢:

(1首先执行@ModelAttribute注解的方法,准备视图展示时所需要的模型数据;@ModelAttribute注解方法形式参数规则和@RequestMapping规则一样,如可以有@RequestParam等;

2执行@RequestMapping注解方法,进行模型绑定时首先查找模型数据中是否含有同名对象,如果有直接使用,如果没有通过反射创建一个,因此②处的user将使用①处返回的命令对象。即②处的user等于①处的user。

 

三、暴露@RequestMapping方法返回值为模型数据

Java代码   收藏代码
  1. public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)  

大家可以看到返回值类型是命令对象类型,而且通过@ModelAttribute("user2")注解,此时会暴露返回值到模型数据(名字为user2)中供视图展示使用。那哪个视图应该展示呢?此时Spring Web MVC会根据RequestToViewNameTranslator进行逻辑视图名的翻译,详见【4.15.5、RequestToViewNameTranslator】一节。

 

此时又有问题了,@RequestMapping注解方法的入参user暴露到模型数据中的名字也是user2,其实我们能猜到:

3@ModelAttribute注解的返回值会覆盖@RequestMapping注解方法中的@ModelAttribute注解的同名命令对象。

 

四、匿名绑定命令参数

Java代码   收藏代码
  1. public String test4(@ModelAttribute UserModel user, Model model)  
  2. 或  
  3. public String test5(UserModel user, Model model)   

此时我们没有为命令对象提供暴露到模型数据中的名字,此时的名字是什么呢?Spring Web MVC自动将简单类名(首字母小写)作为名字暴露,如“cn.javass.chapter6.model.UserModel”暴露的名字为“userModel”。

Java代码   收藏代码
  1. public @ModelAttribute List<String> test6()  
  2. 或  
  3. public @ModelAttribute List<UserModel> test7()   

对于集合类型(Collection接口的实现者们,包括数组),生成的模型对象属性名为“简单类名(首字母小写)”+“List”,如List<String>生成的模型对象属性名为“stringList”,List<UserModel>生成的模型对象属性名为“userModelList”。

 

其他情况一律都是使用简单类名(首字母小写)作为模型对象属性名,如Map<String, UserModel>类型的模型对象属性名为“map”。

6.6.7、@SessionAttributes绑定命令对象到session

有时候我们需要在多次请求之间保持数据,一般情况需要我们明确的调用HttpSession的API来存取会话数据,如多步骤提交的表单。Spring Web MVC提供了@SessionAttributes进行请求间透明的存取会话数据。

Java代码   收藏代码
  1. //1、在控制器类头上添加@SessionAttributes注解  
  2. @SessionAttributes(value = {"user"})    //①  
  3. public class SessionAttributeController   
  4.   
  5. //2、@ModelAttribute注解的方法进行表单引用对象的创建  
  6. @ModelAttribute("user")    //②  
  7. public UserModel initUser()   
  8.   
  9. //3、@RequestMapping注解方法的@ModelAttribute注解的参数进行命令对象的绑定  
  10. @RequestMapping("/session1")   //③  
  11. public String session1(@ModelAttribute("user") UserModel user)  
  12.   
  13. //4、通过SessionStatus的setComplete()方法清除@SessionAttributes指定的会话数据  
  14. @RequestMapping("/session2")   //③  
  15. public String session(@ModelAttribute("user") UserModel user, SessionStatus status) {  
  16.     if(true) { //④  
  17.         status.setComplete();  
  18.     }  
  19.     return "success";  
  20. }   

@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

Java代码   收藏代码
  1. //1、RequestMappingHandlerAdapter首先调用ModelFactory的initModel方法准备模型数据:  
  2. modelFactory.initModel(webRequest, mavContainer, requestMappingMethod);  
  3. //2、调用@RequestMapping注解的功能处理方法  
  4. requestMappingMethod.invokeAndHandle(webRequest, mavContainer);  
  5. //3、更新/合并模型数据  
  6. modelFactory.updateModel(webRequest, mavContainer);   

2、ModelFactory.initModel

Java代码   收藏代码
  1. Map<String, ?> attributesInSession = this.sessionAttributesHandler.retrieveAttributes(request);  
  2. //1.1、将与@SessionAttributes注解相关的会话对象放入模型数据中  
  3. mavContainer.mergeAttributes(attributesInSession);  
  4. //1.2、调用@ModelAttribute方法添加表单引用对象  
  5. invokeModelAttributeMethods(request, mavContainer);  
  6. //1.3、验证模型数据中是否包含@SessionAttributes注解相关的会话对象,不包含抛出异常  
  7. for (String name : findSessionAttributeArguments(handlerMethod)) {  
  8.     if (!mavContainer.containsAttribute(name)) {  
  9.         //1.4、此处防止在@ModelAttribute注解方法又添加了会话对象  
  10.         //如在@ModelAttribute注解方法调用session.setAttribute("user", new UserModel());  
  11.         Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);  
  12.         if (value == null) {  
  13.             throw new HttpSessionRequiredException("Expected session attribute '" + name + "'");  
  14.         }  
  15.         mavContainer.addAttribute(name, value);  
  16. }   

3、ModelFactory.invokeModelAttributeMethods

Java代码   收藏代码
  1. for (InvocableHandlerMethod attrMethod : this.attributeMethods) {  
  2.     String modelName = attrMethod.getMethodAnnotation(ModelAttribute.class).value();   
  3.     //1.2.1、如果模型数据中包含同名数据则不再添加  
  4.     if (mavContainer.containsAttribute(modelName)) {  
  5.         continue;  
  6.     }  
  7.     //1.2.2、调用@ModelAttribute注解方法并将返回值添加到模型数据中,此处省略实现代码  
  8. }   

(4、requestMappingMethod.invokeAndHandle 调用功能处理方法,此处省略

5、ModelFactory.updateMode 更新模型数据

Java代码   收藏代码
  1. //3.1、如果会话被标识为完成,此时从会话中清除@SessionAttributes注解相关的会话对象  
  2. if (mavContainer.getSessionStatus().isComplete()){   
  3.     this.sessionAttributesHandler.cleanupAttributes(request);  
  4. }  
  5. //3.2、如果会话没有完成,将模型数据中的@SessionAttributes注解相关的对象添加到会话中  
  6. else {  
  7.     this.sessionAttributesHandler.storeAttributes(request, mavContainer.getModel());  
  8. }  
  9. //省略部分代码   

到此@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表达式结果映射到到功能处理方法的参数上。

Java代码   收藏代码
  1. public String test(@Value("#{systemProperties['java.vm.version']}") String jvmVersion)  

到此数据绑定我们就介绍完了,对于没有介绍的方法参数和注解(包括自定义注解)在后续章节进行介绍。接下来我们学习下数据类型转换吧。


AJAX与spring mvc交互

技术关键点是:

1、返回字符串,并且是ResponseBody

2、设置MIME type是 text/html

代码如下:

  1. @ResponseBody  
  2. @RequestMapping(value="/callJs",produces = "text/html; charset=UTF-8")  
  3. public String callJs()throws Exception{  
  4.     return "<script>parent.alert('Hello Js');</script>";  
  5.       
  6. }  
AJAX与spring mvc交互

(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包 

  1. <title>Spring MVC</title>  
  2. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>  
  3. <script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>  
  4. <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/user/index.js"></script>  
  5. </head>  
  6. <body>  
  7. <div id="info"></div>  
  8. <form action="add" method="post" id="form">  
  9. 编号:<input type="text" name="id"/>  
  10. 姓名:<input type="text" name="username"/>  
  11. 年龄:<input type="text" name="age"/>  
  12.   
  13. <input type="button" value="提交" id="submit"/>  
  14. </form>  
  15. </body>  
  16. </html>  


  1. //将一个表单的数据返回成JSON对象  
  2. $.fn.serializeObject = function() {  
  3.   var o = {};  
  4.   var a = this.serializeArray();  
  5.   $.each(a, function() {  
  6.     if (o[this.name]) {  
  7.       if (!o[this.name].push) {  
  8.         o[this.name] = [ o[this.name] ];  
  9.       }  
  10.       o[this.name].push(this.value || '');  
  11.     } else {  
  12.       o[this.name] = this.value || '';  
  13.     }  
  14.   });  
  15.   return o;  
  16. };  
  17.   
  18. $(document).ready(  
  19.     function() {  
  20.       jQuery.ajax( {  
  21.         type : 'GET',  
  22.         contentType : 'application/json',  
  23.         url : 'user/list',  
  24.         dataType : 'json',  
  25.         success : function(data) {  
  26.           if (data && data.success == "true") {  
  27.             $('#info').html("共" + data.total + "条数据。<br/>");  
  28.             $.each(data.data, function(i, item) {  
  29.               $('#info').append(  
  30.                   "编号:" + item.id + ",姓名:" + item.username  
  31.                       + ",年龄:" + item.age);  
  32.             });  
  33.           }  
  34.         },  
  35.         error : function() {  
  36.           alert("error")  
  37.         }  
  38.       });  
  39.       $("#submit").click(function() {  
  40.         var jsonuserinfo = $.toJSON($('#form').serializeObject());  
  41.         alert(jsonuserinfo);  
  42.         jQuery.ajax( {  
  43.           type : 'POST',  
  44.           contentType : 'application/json',  
  45.           url : 'user/add',  
  46.           data : jsonuserinfo,  
  47.           dataType : 'json',  
  48.           success : function(data) {  
  49.             alert("新增成功!");  
  50.           },  
  51.           error : function(data) {  
  52.             alert("error")  
  53.           }  
  54.         });  
  55.       });  
  56.     });  


  1. @Controller  
  2. @RequestMapping("/user")  
  3. public class DemoController {  
  4.   private Logger logger = LoggerFactory.getLogger(DemoController.class);  
  5.   
  6.   @RequestMapping(value = "/list", method = RequestMethod.GET)  
  7.   @ResponseBody  
  8.   public Map<String, Object> getUserList() {  
  9.     logger.info("列表");  
  10.     List<UserModel> list = new ArrayList<UserModel>();  
  11.     UserModel um = new UserModel();  
  12.     um.setId("1");  
  13.     um.setUsername("sss");  
  14.     um.setAge(222);  
  15.     list.add(um);  
  16.     Map<String, Object> modelMap = new HashMap<String, Object>(3);  
  17.     modelMap.put("total""1");  
  18.     modelMap.put("data", list);  
  19.     modelMap.put("success""true");  
  20.     return modelMap;  
  21.   }  
  22.   
  23.   @RequestMapping(value = "/add", method = RequestMethod.POST)  
  24.   @ResponseBody  
  25.   public Map<String, String> addUser(@RequestBody UserModel model) {  
  26.     logger.info("新增");  
  27.     logger.info("捕获到前台传递过来的Model,名称为:" + model.getUsername());  
  28.     Map<String, String> map = new HashMap<String, String>(1);  
  29.     map.put("success""true");  
  30.     return map;  
  31.   }  
  32. }  

重定向视图

  1. “redirect:index”
  2. view.setViewName("redirect:index");
  3. view.setView(new RedirectView("/index", false));
  4. RedirectView redirectView = new RedirectView("/index{id}");
    •         redirectView.setExpandUriTemplateVariables(false);
    •         redirectView.setExposeModelAttributes(false);
    •         view.setView(redirectView);

自定义拦截器详解

  1. package org.springframework.web.servlet;    
  2. import Javax.servlet.http.HttpServletRequest;   
  3. import Javax.servlet.http.HttpServletResponse;   
  4. public interface HandlerInterceptor {    
  5.      // preHandle()方法在业务处理器处理请求之前被调用   
  6.      boolean preHandle(HttpServletRequest request,   
  7. HttpServletResponse response,    
  8.      Object handler)   
  9.          throws Exception;    
  10.      // postHandle()方法在业务处理器处理请求之后被调用   
  11.      void postHandle(    
  12.              HttpServletRequest request, HttpServletResponse   
  13. response, Object    
  14.              handler, ModelAndView modelAndView)   
  15.              throws Exception;    
  16.      // afterCompletion()方法在DispatcherServlet完全处理完请求后被调用   
  17.      void afterCompletion(    
  18.              HttpServletRequest request, HttpServletResponse  
  19. response, Object    
  20.              handler, Exception ex)   
  21.              throws Exception;    
  22.    
  23.  }  

下面对代码中的三个方法进行解释。

preHandle():这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求request进行处理。如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器,或者是业务处理器去进行处理,则返回true;如果程序员决定不需要再调用其他的组件去处理请求,则返回false。

postHandle():这个方法在业务处理器处理完请求后,但是DispatcherServlet向客户端返回请求前被调用,在该方法中对用户请求request进行处理。

afterCompletion():这个方法在DispatcherServlet完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作。

下面通过一个例子来说明如何使用SpringMVC框架的拦截器。

现在要编写一个拦截器,拦截所有不在工作时间的请求,把这些请求转发到一个特定的静态页面,而不对它们的请求进行处理。

首先编写TimeInterceptor.Java,代码如下:

  1. package com.yjde.web.interceptor;  
  2.   
  3. import java.util.Calendar;  
  4.   
  5. import javax.servlet.http.HttpServletRequest;  
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.springframework.web.servlet.ModelAndView;  
  9. import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;  
  10.   
  11. public class TimeInterceptor extends HandlerInterceptorAdapter {  
  12.     // 继承HandlerInterceptorAdapter类  
  13.   
  14.     private int openingTime; // openingTime 属性指定上班时间  
  15.     private int closingTime; // closingTime属性指定下班时间  
  16.     private String outsideOfficeHoursPage;// outsideOfficeHoursPage属性指定错误提示页面的URL  
  17.   
  18.     // 重写 preHandle()方法,在业务处理器处理请求之前对该请求进行拦截处理  
  19.     public boolean preHandle(HttpServletRequest request,  
  20.             HttpServletResponse response, Object handler) throws Exception {  
  21.         Calendar cal = Calendar.getInstance();  
  22.         int hour = cal.get(Calendar.HOUR_OF_DAY); // 获取当前时间  
  23.         if (openingTime <= hour && hour < closingTime) { // 判断当前是否处于工作时间段内  
  24.             return true;  
  25.         } else {  
  26.             response.sendRedirect(outsideOfficeHoursPage); // 返回提示页面  
  27.             return false;  
  28.         }  
  29.     }  
  30.   
  31.     public void postHandle(HttpServletRequest request,  
  32.             HttpServletResponse response, Object o, ModelAndView mav)  
  33.             throws Exception {  
  34.         System.out.println("postHandle");  
  35.     }  
  36.   
  37.     public void afterCompletion(HttpServletRequest request,  
  38.             HttpServletResponse response, Object o, Exception excptn)  
  39.             throws Exception {  
  40.         System.out.println("afterCompletion");  
  41.     }  
  42.   
  43.     public int getOpeningTime() {  
  44.         return openingTime;  
  45.     }  
  46.   
  47.     public void setOpeningTime(int openingTime) {  
  48.         this.openingTime = openingTime;  
  49.     }  
  50.   
  51.     public int getClosingTime() {  
  52.         return closingTime;  
  53.     }  
  54.   
  55.     public void setClosingTime(int closingTime) {  
  56.         this.closingTime = closingTime;  
  57.     }  
  58.   
  59.     public String getOutsideOfficeHoursPage() {  
  60.         return outsideOfficeHoursPage;  
  61.     }  
  62.   
  63.     public void setOutsideOfficeHoursPage(String outsideOfficeHoursPage) {  
  64.         this.outsideOfficeHoursPage = outsideOfficeHoursPage;  
  65.     }  
  66.   
  67. }  
  68. // 可以看出,上面的代码重载了preHandle()方法,该方法在业务处理器处理请求之前被调用。在该方法中,首先获得当前的时间,判断其是否在  
  69. // openingTime和closingTime之间,如果在,返回true,这样才会调用业务控制器去处理该请求;否则直接转向一个页面,返回false,这样该请求就不会被处理。  

可以看出,上面的代码重载了preHandle()方法,该方法在业务处理器处理请求之前被调用。在该方法中,首先获得当前的时间,判断其是否在 openingTime和closingTime之间,如果在,返回true,这样才会调用业务控制器去处理该请求;否则直接转向一个页面,返回 false,这样该请求就不会被处理。

下面是在dispatcher-servlet.xml中对拦截器进行的配置,代码如下:

  1. <pre name="code" class="html"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"  
  4.     xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.             http://www.springframework.org/schema/context   
  9.             http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10.             http://www.springframework.org/schema/aop   
  11.             http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  12.             http://www.springframework.org/schema/tx   
  13.             http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  14.             http://www.springframework.org/schema/mvc   
  15.             http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  16.             http://www.springframework.org/schema/context   
  17.             http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  18.     <!--  
  19.         使Spring支持自动检测组件,如注解的Controller  
  20.     -->  
  21.     <context:component-scan base-package="com.yjde.web.controller" />  
  22.   
  23.     <bean id="viewResolver"  
  24.         class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  25.         p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />  
  26.     <mvc:interceptors>  
  27.         <mvc:interceptor>  
  28.             <!--设置拦截的路径-->  
  29.             <mvc:mapping path="/login1.htm" />  
  30.             <mvc:mapping path="/login2.htm" />  
  31.             <bean class="com.yjde.web.interceptor.TimeInterceptor">  
  32.                 <!--openingTime 属性指定上班时间-->  
  33.                 <property name="openingTime">  
  34.                     <value>12</value>  
  35.                 </property>  
  36.                 <!--closingTime属性指定下班时间-->  
  37.                 <property name="closingTime">  
  38.                     <value>14</value>  
  39.                 </property>  
  40.                 <!--outsideOfficeHoursPage属性指定提示页面的URL-->  
  41.                 <property name="outsideOfficeHoursPage">  
  42.                     <value>http://localhost:8080/SpringMVCInterceptor/jsp/outsideOfficeHours.jsp  
  43.                     </value>  
  44.                 </property>  
  45.             </bean>  
  46.         </mvc:interceptor>  
  47.     </mvc:interceptors>  
  48.     <bean id="messageSource"  
  49.         class="org.springframework.context.support.ResourceBundleMessageSource"  
  50.         p:basename="message">  
  51.     </bean>  
  52. </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>
复制代码

运行测试:

1

更改浏览器语言顺序,刷新页面:

2


二.基于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";
    }
    
}
复制代码

运行测试:

3

4

 

三.基于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";
    }
    
}
复制代码

运行测试:

5

6

关于<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 来改变语言了,具体这里不再做演示了。

 

国际化部分的内容到此结束。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值