SpringMVC的基础知识整理(5)注解开发和参数绑定

常用的注解学习
参数绑定(简单类型、pojo、集合类型)
自定义参数绑定(掌握)

Spring参数绑定过程
从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上。
springmvc中,接收页面提交的数据是通过方法形参来接收。而不是在controller类定义成员变量接收!!!!
SpringMVC的基础知识整理(5)注解开发和参数绑定

默认支持的类型
直接在controller方法形参上定义下边类型的对象,就可以使用这些对象。在参数绑定过程中,如果遇到下边类型直接进行绑定。
    HttpServletRequest
        通过request对象获取请求信息
    HttpServletResponse
        通过response处理响应信息
    HttpSession
        通过session对象得到session中存放的对象
    Model/ModelMap
        model是一个接口,modelMap是一个接口实现 。
        作用:将model数据填充到request域。

简单类型
通过@RequestParam对简单类型的参数进行绑定。
    (1)要求请求中传入key/value类型的参数的参数名称和controller方法的形参名称一致,方可绑定成功;
    (2)如果不想要键值对的key和contruller方法形参名一致,可以使用注解 @RequestParam,通过required属性指定参数是否必传;如果传入参数为空,则取默认值defaultValue的值填充。
    @RequestMapping(value = "/editItems", method = { RequestMethod.POST,RequestMethod.GET })
    public String editItems(Model model,@RequestParam(value = "id", required = true, defaultValue="1")  Integer items_id )  throws Exception {}
pojo绑定
    页面表单中各种文本框的name值和对应pojo类的属性名要一致,只需在controller的方法中形参定义为pojo类的类型即可绑定对应参数到该pojo的属性中;

不管表单是get、post提交方式,还是超链接,默认都是 key/value 的形式提交的,contentType="application/x-www-form-urlencoded"

注意:形参中既有简单类型又有pojo类型,没关系,参数绑定互不影响。

-------------------------------------------------------------------------------------------------------------------------------------------------------

乱码问题
GET请求乱码解决方法有两个:
    (1)修改tomcat配置文件添加编码与工程编码一致,如下:(但不推荐)
        <Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
                   connectionTimeout="20000"
                   redirectPort="8443" />
    (2)另外一种方法对参数进行重新编码:
        ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
        String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8");
POST乱码解决:
    在web.xml添加post乱码filter

<filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    以上可以解决post请求乱码问题。

转载于:https://my.oschina.net/oszzq/blog/2961581