`
jinnianshilongnian
  • 浏览: 21445194 次
  • 性别: Icon_minigender_1
博客专栏
5c8dac6a-21dc-3466-8abb-057664ab39c7
跟我学spring3
浏览量:2407316
D659df3e-4ad7-3b12-8b9a-1e94abd75ac3
Spring杂谈
浏览量:2999341
43989fe4-8b6b-3109-aaec-379d27dd4090
跟开涛学SpringMVC...
浏览量:5632804
1df97887-a9e1-3328-b6da-091f51f886a1
Servlet3.1规范翻...
浏览量:258007
4f347843-a078-36c1-977f-797c7fc123fc
springmvc杂谈
浏览量:1593782
22722232-95c1-34f2-b8e1-d059493d3d98
hibernate杂谈
浏览量:249162
45b32b6f-7468-3077-be40-00a5853c9a48
跟我学Shiro
浏览量:5849042
Group-logo
跟我学Nginx+Lua开...
浏览量:698656
5041f67a-12b2-30ba-814d-b55f466529d5
亿级流量网站架构核心技术
浏览量:781144
社区版块
存档分类
最新评论

SpringMVC强大的数据绑定(1)——第六章 注解式控制器详解——跟着开涛学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.1、功能处理方法支持的参数类型

在继续学习之前,我们需要首先看看功能处理方法支持哪些类型的形式参数,以及他们的具体含义。

 一、ServletRequest/HttpServletRequest 和 ServletResponse/HttpServletResponse

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

 

二、InputStream/OutputStream 和 Reader/Writer

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

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

 

public void readerOrWriteBody(Reader reader, Writer writer)
        throws IOException {
    writer.write("hello");
}
 reader获取请求的内容区字符流,等价于request.getReader();

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.getParameter:访问请求参数区的数据,可以通过getHeader()访问请求头数据;

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永远不为null。

 

注意: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";
}
 如果提交的表单(包含username和password文本域),将自动将请求参数绑定到命令对象user中去。

 

六、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;
}
 从代码中我们可以总结出功能处理方法的返回值中的模型数据(如ModelAndView)会 合并 功能处理方法形式参数中的模型数据(如Model),但如果两者之间有同名的,返回值中的模型数据会覆盖形式参数中的模型数据。

 

七、Errors/BindingResult

@RequestMapping(value = "/error1")
public String error1(UserModel user, BindingResult result)

 

@RequestMapping(value = "/error2")
public String error2(UserModel user, BindingResult result, Model model) {
    

 

@RequestMapping(value = "/error3")
public String error3(UserModel user, Errors errors) 

 

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

 

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

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

 

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

 

八、其他杂项

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)将在后续章节详细讲解。

 

第二部分会介绍注解方式的数据绑定。

  • 大小: 54.5 KB
  • 大小: 8.4 KB
64
8
分享到:
评论
15 楼 yangpeihai 2012-10-24  
tao 哥,请教个问题,springMVC里面,你使用spring标签做页面展示吗?spring有没有类似jstl里面forEach的标签呢?找了好久,没找到,指点一下,谢谢!
  你们系统开发,是用什么标签库,自定义?
14 楼 jinnianshilongnian 2012-10-23  
longhumentmj 写道
楼主很强大,写的很详细,我想请教一个问题,上面这些参数是不是每一个方法都可以使用这么多参数?是要明确写在方法参数里面才可以使用是吧?

必须在spring的控制器方法中
13 楼 longhumentmj 2012-10-23  
楼主很强大,写的很详细,我想请教一个问题,上面这些参数是不是每一个方法都可以使用这么多参数?是要明确写在方法参数里面才可以使用是吧?
12 楼 jinnianshilongnian 2012-10-18  
piao_liu 写道
接着等待

谢谢 
11 楼 piao_liu 2012-10-18  
接着等待
10 楼 jinnianshilongnian 2012-10-17  
at1943 写道

似乎通过@Value注解+spel得到,但我想知道spring之外怎么通过applicationContext得到。

property-placeholder 是发生在bean工厂完成Bean定义加载 修改Bean定义搞定的

@Value可以

可以参考源码: 所有处理方法都是受保护的  因此我们访问不到 
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws BeansException {

StringValueResolver valueResolver = new PlaceholderResolvingStringValueResolver(props);

this.doProcessProperties(beanFactoryToProcess, valueResolver);
}

即默认无法获取这些。   可以考虑使用messageSource,因为property-placeholder 的目的就是修改Bean定义中的如${}占位符

可以参考刚刚写的
http://jinnianshilongnian.iteye.com/blog/1699685
9 楼 at1943 2012-10-17  
at1943 写道
jinnianshilongnian 写道
at1943 写道
jinnianshilongnian 写道
at1943 写道
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

这个不行 spring规定死了  你为什么那么做呢?

我想在model里加几个固定的属性,比如我想返回消息就直接model.setMessage("")而不是model.setattruble("message","vale"),我的想法很好把

这个真不好办  人家定义死了

想方便一下也不方便啊,再说把。
又来个新问题,通过<context:property-placeholder location="classpath:config.properties"/>在配置文件中读取的properties怎么用applicationContext获取到其中的值?

似乎通过@Value注解+spel得到,但我想知道spring之外怎么通过applicationContext得到。
8 楼 at1943 2012-10-17  
jinnianshilongnian 写道
at1943 写道
jinnianshilongnian 写道
at1943 写道
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

这个不行 spring规定死了  你为什么那么做呢?

我想在model里加几个固定的属性,比如我想返回消息就直接model.setMessage("")而不是model.setattruble("message","vale"),我的想法很好把

这个真不好办  人家定义死了

想方便一下也不方便啊,再说把。
又来个新问题,通过<context:property-placeholder location="classpath:config.properties"/>在配置文件中读取的properties怎么用applicationContext获取到其中的值?
7 楼 jinnianshilongnian 2012-10-16  
at1943 写道
jinnianshilongnian 写道
at1943 写道
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

这个不行 spring规定死了  你为什么那么做呢?

我想在model里加几个固定的属性,比如我想返回消息就直接model.setMessage("")而不是model.setattruble("message","vale"),我的想法很好把

这个真不好办  人家定义死了
6 楼 at1943 2012-10-16  
jinnianshilongnian 写道
at1943 写道
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

这个不行 spring规定死了  你为什么那么做呢?

我想在model里加几个固定的属性,比如我想返回消息就直接model.setMessage("")而不是model.setattruble("message","vale"),我的想法很好把
5 楼 jinnianshilongnian 2012-10-16  
飞天奔月 写道

• HttpEntity<?> parameters (Servlet-only) for access to the Servlet request HTTP headers and contents. The request stream will be converted to the entity body using message converters.

• org.springframework.web.servlet.mvc.support.RedirectAttributes (Servlet-only, @MVC 3.1-only) to specify the exact set of attributes to use in case of a redirect and also to add flash attributes (attributes stored temporarily on the server-side to make them available to the request after the redirect). RedirectAttributes is used instead of the implicit model if the method returns a "redirect:" prefixed view name or RedirectView.

• org.springframework.web.bind.support.SessionStatus status handle for marking form processing as complete (triggering the cleanup of session attributes that have been indicated by the SessionAttributes annotation at the handler type level).

• org.springframework.web.util.UriComponentsBuilder (Servlet-only, @MVC 3.1-only) for preparing a URL relative to the current request's host, port, scheme, context path, and the literal part of the servlet mapping.


这4个没讲

HttpEntity 当时准备放到如@RequestBody @ResponseBody中讲
RedirectAttributes  UriComponentsBuilder 等准备放到spring中的flash manager讲
4 楼 飞天奔月 2012-10-16  

• HttpEntity<?> parameters (Servlet-only) for access to the Servlet request HTTP headers and contents. The request stream will be converted to the entity body using message converters.

• org.springframework.web.servlet.mvc.support.RedirectAttributes (Servlet-only, @MVC 3.1-only) to specify the exact set of attributes to use in case of a redirect and also to add flash attributes (attributes stored temporarily on the server-side to make them available to the request after the redirect). RedirectAttributes is used instead of the implicit model if the method returns a "redirect:" prefixed view name or RedirectView.

• org.springframework.web.bind.support.SessionStatus status handle for marking form processing as complete (triggering the cleanup of session attributes that have been indicated by the SessionAttributes annotation at the handler type level).

• org.springframework.web.util.UriComponentsBuilder (Servlet-only, @MVC 3.1-only) for preparing a URL relative to the current request's host, port, scheme, context path, and the literal part of the servlet mapping.


这4个没讲
3 楼 飞天奔月 2012-10-16  
jinnianshilongnian 写道
at1943 写道
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

这个不行 spring规定死了  你为什么那么做呢?



可以尝试下 @InitBinder

除了 类型转换 可以做其他事情
2 楼 jinnianshilongnian 2012-10-16  
at1943 写道
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

这个不行 spring规定死了  你为什么那么做呢?
1 楼 at1943 2012-10-16  
我还是想知道怎么配置才能将入参变成一个自己定义的类似BindingAwareModelMap的对象

相关推荐

Global site tag (gtag.js) - Google Analytics