springMVC学习2

参数绑定

默认支持的参数类型

@Override
public Item queryItemById(int id) {
    Item item = this.itemMapper.selectByPrimaryKey(id);
    return item;
}

http://127.0.0.1:8080/springmvc-web/itemEdit.action?id=1

Id包含在Request对象中。可以从Request对象中取id

想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法

@RequestMapping("/itemEdit")
public ModelAndView queryItemById(HttpServletRequest request) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    modelAndView.addObject("item", item);
    // 设置逻辑视图
    modelAndView.setViewName("itemEdit");
    return modelAndView;
}

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值

Model/ModelMap

除了ModelAndView以外,还可以使用Model来向页面传递数据,

Model是一个接口,在参数里直接声明model即可。

如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。

不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。

@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, Model model) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    // ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    // modelAndView.addObject("item", item);
    // 设置逻辑视图
    // modelAndView.setViewName("itemEdit");

    // 把商品数据放在模型中
    model.addAttribute("item", item);

    return "itemEdit";
}

ModelMap

ModelMap是Model接口的实现类,也可以通过ModelMap向页面传递数据

使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。

@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, ModelMap model) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    // ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    // modelAndView.addObject("item", item);
    // 设置逻辑视图
    // modelAndView.setViewName("itemEdit");

    // 把商品数据放在模型中
    model.addAttribute("item", item);
    return "itemEdit";
}

绑定简单类型

当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。

这样,从Request取参数的方法就可以进一步简化。

@RequestMapping("/itemEdit")
public String queryItemById(int id, ModelMap model) {
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);
    // 把商品数据放在模型中
    model.addAttribute("item", item);
    return "itemEdit";
}

支持的数据类型

参数类型推荐使用包装数据类型,因为基础数据类型不可以为null

整形:Integer、int

字符串:String

单精度:Float、float

双精度:Double、double

布尔型:Boolean、boolean

说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0

请求url:http://localhost:8080/xxx.action?id=2&status=false

处理器方法:public String editItem(Model model,Integer id,Boolean status)

@RequestParam

使用@RequestParam常用于处理简单类型的绑定,否则参数必须和前台的name一样

value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数    区中的名字为itemId的参数的值将传入

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错 HTTP Status 400 - Required Integer parameter 'XXXX' is not present

defaultValue:默认值,表示如果请求中没有同名参数时的默认值

@RequestMapping("/itemEdit")
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,
        ModelMap modelMap) {
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);
    // 把商品数据放在模型中
    modelMap.addAttribute("item", item);
    return "itemEdit";
}

如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接受数据,也可以使用pojo接收数据。

要求:pojo对象中的属性名和表单中input的name属性一致。

请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性

void updateItemById(Item item);  接口

使用updateByPrimaryKeySelective(item)方法,忽略空参数

@Override
public void updateItemById(Item item) {
    this.itemMapper.updateByPrimaryKeySelective(item);
}
@RequestMapping("/updateItem")
public String updateItem(Item item) {
    // 调用服务更新商品
    this.itemService.updateItemById(item);
    // 返回逻辑视图
    return "success";
}

注意:提交的表单中不要有日期类型的数据,否则会报400错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。

解决post乱码问题

提交发现,保存成功,但是保存的是乱码

在web.xml中加入:spring-web.jar

<!-- 解决post乱码问题 -->
<filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!-- 设置编码参是UTF8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

对于get请求中文参数出现乱码解决方法有两个

修改tomcat配置文件添加编码与工程编码一致,如下

<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

另外一种方法对参数进行重新编码:

String userName new 
String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

使用包装的pojo接收商品信息的查询条件

public class QueryVo {
    private Item item;
set/get。。。
}

接收查询条件

// 绑定包装数据类型
    @RequestMapping("/queryItem")
    public String queryItem(QueryVo queryVo) {
        System.out.println(queryVo.getItem().getId());
        System.out.println(queryVo.getItem().getName());
        return "success";
    }

自定义参数绑定

在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式。

由于日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。

前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器

适配器上自定义转换器Converter进行参数绑定。

一般使用<mvc:annotation-driven/>注解驱动加载处理器适配器,可以在此标签上进行配置。

自定义Converter

//Converter<S, T>
//S:source,需要转换的源的类型
//T:target,需要转换的目标类型
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        try {
            // 把字符串转换为日期类型
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(source);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 如果转换的时候出现异常则返回空
        return null;
    }
}

配置Converter

我们同时可以配置多个的转换器

<!-- 配置注解驱动 -->
<!-- 如果配置此标签,可以不用配置... -->
<mvc:annotation-driven conversion-service="conversionService" />

<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.springmvc.converter.DateConverter" />
        </set>
    </property>
</bean>

配置方式2(了解)

<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="webBindingInitializer" ref="customBinder"></property>
</bean>

<!-- 自定义webBinder -->
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
    <property name="conversionService" ref="conversionService" />
</bean>

<!-- 转换器工厂配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.springmvc.convert.DateConverter" />自定义转换
        </set>
    </property>
</bean>

注意:此方法需要独立配置处理器映射器、适配器     不再使用<mvc:annotation-driven/>

springmvc与struts2不同

1、  springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过滤器。

2、  springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递

        参数是通过类的属性,只能设计为多例。

3、  Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和

        视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过request域传输到页面。Jsp视图解析器默认使用jstl。

猜你喜欢

转载自www.cnblogs.com/escapist/p/9050519.html