1. 程式人生 > >SpringMVC參數綁定

SpringMVC參數綁定

包裝類 tac trac rri 信息 ID 需要 character let

一、參數綁定原理

1、什麽是參數綁定?

前臺頁面通常會有數據提交給後臺進行處理(如提交表單),參數綁定的作用就是將這些數據正確地交給Controller進行處理。

2、參數綁定的實現

在springMVC中提交請求的參數是通過方法的形參來接收的,從客戶端請求的key/value數據,經過參數綁定,將key/value數據綁定到Controller的形參上,然後Controller就可以直接使用該形參了。

技術分享圖片

二、參數綁定支持

1、默認支持的類型

SpringMVC 有支持的默認參數類型,我們直接在形參上給出這些默認類型的聲明,就能直接使用了。如下:

HttpServletRequest 類型

HttpServletResponse 類型

HttpSession 類型

Model/ModelMap 類型 

Controller:

    @RequestMapping("/default")
    public String index(HttpServletRequest request, 
            HttpServletResponse response, 
            HttpSession session, 
            Model model, 
            ModelMap modelMap) {
        request.setAttribute("request", "request類型");
        session.setAttribute(
"session", "session類型"); model.addAttribute("model", "model類型"); modelMap.addAttribute("modelMap", "modelMap類型"); return "success"; }

success.jsp

<body>
${request}
${session}
${model}
${modelMap}
</body>

結果:

技術分享圖片

2、基本數據類型(對應的包裝類型)綁定

int(Integer)、short(Short)、long(Long)、float(Float)、

double(Double)、byte(Byte)、char(Character)、boolean(Boolean)、String

controller:

    // springmvc可以直接接收基本數據類型和String,可以自動進行類型轉換
    // Controller方法接收的參數的變量名稱必須等於頁面中input標簽中name屬性值
    @RequestMapping("/updateitem1")
    public String update1(Integer id, String name, Float price, String detail) throws Exception {
        Items items = new Items();
        items.setId(id);
        items.setName(name);
        items.setPrice(price);
        items.setDetail(detail);
        itemsService.updateItems(items);
        return "success";
    }

editForm.jsp

<form id="itemForm"    action="${pageContext.request.contextPath }/updateitem1.action" method="post">
        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名稱</td>
                <td><input type="text" name="name" value="${item.name }" /></td>
            </tr>
            <tr>
                <td>商品價格</td>
                <td><input type="text" name="price" value="${item.price }" /></td>
            </tr>
            <tr>
                <td>商品簡介</td>
                <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交" />
                </td>
            </tr>
        </table>

    </form>

註意:表單中input的name值和Controller方法裏的參數變量名保持一致,就能完成數據綁定。當然也可以不一致,不一致就必須使用@RequestParam 註解來完成。例如:

    @RequestMapping("/updateitem1")
    public String update1(Integer id, @RequestParam("name")String username, Float price, String detail) throws Exception {
        // code 
    }

使用註解 @RequestParam ,我們可以使用任意形參,但是註解裏面的 value 屬性值要和表單的name屬性值一樣。

3、實體類(POJO)類型綁定

SpringMVC提供了一個更加智能、更少代碼的綁定方式,就是實體類綁定。相比上面的一種方式,可以不需在Controller中使用set方法設置實體類屬性。要求:前臺頁面中如input中name屬性值必須等於實體類對應的屬性

實體類User.java

package cn.itheima.pojo;

import java.util.Date;

public class User {
    private Integer id;

    private String username;

    private Date birthday;

    private String sex;

    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }
}

頁面editItem.jsp

<form id="itemForm"    action="${pageContext.request.contextPath }/updateitem2.action" method="post">
        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名稱</td>
                <td><input type="text" name="name" value="${item.name }" /></td>
            </tr>
            <tr>
                <td>商品價格</td>
                <td><input type="text" name="price" value="${item.price }" /></td>
            </tr>
            <tr>
                <td>商品簡介</td>
                <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交" />
                </td>
            </tr>
        </table>

    </form>

Controller:

    // springmvc可以直接接收pojo類型,這樣比上面接收基本類型更快捷,要求input標簽中name屬性值必須等於pojo中屬性名稱
    @RequestMapping("/updateitem2")
    public String update2(Items items) throws Exception {
        itemsService.updateItems(items);
        return "success";
    }

註:實體類User中有個屬性為birthday,類型為Date,頁面中input框傳入的birthday是String類型,傳遞給Controller必須轉換為Date。這時候必須使用“自定義轉換器”。

如editItem.jsp中表單裏增加一個商品生產日期:

<form id="itemForm"    action="${pageContext.request.contextPath }/updateitem2.action" method="post">
        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名稱</td>
                <td><input type="text" name="name" value="${item.name }" /></td>
            </tr>
            <tr>
                <td>商品價格</td>
                <td><input type="text" name="price" value="${item.price }" /></td>
            </tr>
            
            <tr>
                <td>商品生產日期</td>
                <td><input type="text" name="createtime"
                    value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
            </tr>
            <tr>
                <td>商品簡介</td>
                <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交" />
                </td>
            </tr>
        </table>

    </form>

自定義轉換器:

package cn.itheima.controller.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;

/**
 * S - source:源
 * T - target:目標
 * @author Administrator
 *
 */
public class CustomGlobalStrToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        try {
            Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(source);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在SpringMvc.xml中配置自定義轉換器

     <!-- 註解驅動:自動配置最新版的處理器映射器和處理器適配器 -->
     <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    
     <!-- 註:一定要將自定義的轉換器配置到註解驅動上 -->
     <!-- 轉換器配置 -->
     <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.itheima.controller.converter.CustomGlobalStrToDateConverter"/>
            </set>
        </property>
     </bean>

4、數組類型參數綁定

使用場景:有時候對於一些數據需要批量處理,如批量刪除,這時候需要用到數組類型的綁定。

QueryVO.java

package cn.itheima.vo;

import java.util.List;

import cn.itheima.pojo.Items;

public class QueryVO {// 批量刪除使用
    private Integer[] ids;public Integer[] getIds() {
        return ids;
    }
    public void setIds(Integer[] ids) {
        this.ids = ids;
    }
}

itemList.jap

<form action="${pageContext.request.contextPath }/delAll.action" method="post">
查詢條件:
<table width="100%" border=1>
<tr>
<td>商品名稱:<input type="text" name="items.name"></td>
<td>商品價格:<input type="text" name="items.price"></td>
<td><input type="submit" value="批量刪除"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
    <td></td>
    <td>商品名稱</td>
    <td>商品價格</td>
    <td>生產日期</td>
    <td>商品描述</td>
    <td>操作</td>
</tr>
<c:forEach items="${itemList}" var="item">
<tr>
    <!-- name屬性值要和QueryVO中接收的屬性名稱一致 -->
    <td>
        <input type="checkbox" name="ids" value="${item.id}"/>
    </td>
    <td>${item.name}</td>
    <td>${item.price}</td>
    <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
    <td>${item.detail}</td>
    
    <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>

Controller

    @RequestMapping("/delAll")
    public String delAll(QueryVO vo) throws Exception {
        // 如果批量刪除,一堆input框,那麽可以提交數組
        System.out.println(vo);
        return "";
    }

5、List類型參數綁定

使用場景:批量修改Items信息

QueryVO.java

package cn.itheima.vo;

import java.util.List;

import cn.itheima.pojo.Items;

public class QueryVO {// 批量修改操作
    private List<Items> itemsList;
    
    public List<Items> getItemsList() {
        return itemsList;
    }
    public void setItemsList(List<Items> itemsList) {
        this.itemsList = itemsList;
    }
}

Controller

    @RequestMapping("/updateAll")
    public String updateAll(QueryVO vo) throws Exception {
        System.out.println(vo);
        return "";
    }

itemList.jsp

<c:forEach items="${itemList}" var="item" varStatus="status">
<tr>
    <!-- name屬性值要和QueryVO中接收的屬性名稱一致 -->
    <td>
        <input type="checkbox" name="ids" value="${item.id}"/>
        <input type="hidden" name="itemsList[${status.index}].id" value="${item.id}"/>
    </td>
    <td><input type="text" name="itemsList[${status.index}].name" value="${item.name}"/></td>
    <td><input type="text" name="itemsList[${status.index}].price" value="${item.price}"/></td>
    <td><input type="text" name="itemsList[${status.index}].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
    <td><input type="text" name="itemsList[${status.index}].detail" value="${item.detail}"/></td>
    
    <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

SpringMVC參數綁定