【ssm框架】Controller层之参数自动绑定

来源:互联网 发布:易建联卧推体测数据 编辑:程序博客网 时间:2024/06/07 12:20

SSM框架中,controller作为控制层,是前台后台的交界处,管理着前台请求的映射,后台处理完请求后又将结果返回给前台。


@Controller@RequestMapping(“/console”)public class A extends BaseController{       @RequestMapping(“/A”)       publicvoid A(){              System.out.println(“aaa”);}}

Controller层的使用方法如下:

①   在spring-mvc.xml中配置指明要扫描的controller所在位置
<context:component-scan base-package="XXXX ">
    <context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

②   通过@Controller注解将一个类标记为Controller组件。

③   通过@RequestMapping注解,将前台请求映射到对应cotroller的对应方法。比如上面那个例子,如果前台请求/console/A,那么这个请求将由A方法来进行处理。

 

参数自动绑定

在以往,前台传过来的参数,我们都要通过request.getParamter(“XXX”)一个一个去获取,如果参数多达数十个,那么这个方法将显得非常臃肿。所幸springMVC提供了强大的参数自动绑定功能,比如

@Controller@RequestMapping(“/console”)public class A extends BaseController{       @RequestMapping(“/A”)       publicvoid A(String name,String password,Date birthday){              System.out.println(name+“”+password+””+birthday);}}

如果前台访问/console/A?name=mk&password=1234556&birthday=2017-09-02,这时候springMVC将自动帮我们将传入的参数往我们的方法参数里面填(如果同名)。如果遇到传的参数没有在方法参数中,springMVC将会报错,无法找到匹配的方法。然而这种方法在参数多达数十个的情况下,方法名将变得很长,有没有更简单的方法呢?当然有。

public class User{       privateString name;       privateString password;       privateDate birthday;       //省略set和get}@Controller@RequestMapping(“/console”)public class A extends BaseController{       @RequestMapping(“/A”)       publicvoid A(User user){              System.out.println(“aaa”);}}

这时候前台无论是只传入name,又或者传入name,password,birthday,都会自动封装到user这个对象中供我们调用(名称需要对应),非常方便。


自定义类型转换

在所有的controller中,有时候我们需要做一些类型转换,比如说前台传过来的时间通常是字符串格式,比如2017-09-02,框架并不会自动帮我们将它转成Date类型,因此在参数自动绑定的时候就会报错。怎么让前台传过来的String类型的时间能够自动转换为Date类型呢?我们需要自己写一个数据绑定,将字段中String类型的时间能够转换为Date类型。这个通常写在BaseController中,所有的Controller都继承它。

public class User{       privateString name;       privateString password;       privateDate birthday;       //省略set和get}@Controller@RequestMapping(“/console”)public class A extends BaseController{       @RequestMapping(“/A”)       publicvoid A(User user){              System.out.println(“aaa”);}}