SpringMVC request parameter binding

What is a request parameter binding

Request parameter format

  The default is the key / value format, for example: http: xxxx id = 1 & type = 2?

Data request type parameter value

  Are string types various values

Target type request parameter values ​​to bind

  Controller class method parameter , such as a simple type, POJOs type, set type and the like.

SpringMVC built parameter parsing component

  The default built-in 24 kinds of parameters to resolve the component (ArgumentResolver)

What is the parameter binding?

  The query string is the parameter value the value after obtaining, in for type conversion , the converted value is then assigned to the Controller class formal parameters of the method , this process is the binding parameters

 

 Parameter Type (Servlet API support) supported by default

Controller method parameter may be added at any time following types of parameters, the processing adapter automatically identifies and assignment.

  • HttpServletRequest
    • Object acquisition request information by the request
  • HttpServletResponse
    • Response processing in response to information
  • HttpSession
    • Gets the object stored in the session by session objects
  • InputStream、OutputStream
  • Reader、Writer
  • Model/ModelMap
    • ModelMap inherited from LinkedHashMap, Model is an interface, the underlying implementation thereof is the same class ( BindingAwareModelMap ), the role is transmitted to the data page, corresponding to the role of the Request, the following

Binding simple data types

Simple type parameter binding way

  Simple type refers to the eight basic data types and their packaging, and String.

  In SpringMVC, for java simple type of parameters, parameter binding There are two recommended ways:

  1. Direct Binding
  2. Binding annotations

Direct Binding

Claim

  http request parameter key and controller methods consistent parameter name

Request URL

  http://localhose:8080/xxx/findItem?id=1

  key request id parameter is

Controller Methods

  Controller's parameter is Interger id, which request parameters and key agreement, the success of direct binding

@RequestMapping (value = "/ the findItem" )
     public String the findItem (Integer ID) { 
         System.out.println ( "request parameters received are:" + ID);
         return "Success" ; 
    }

Binding annotations

Claim

  Inconsistent parameter name of the request parameter key and controller methods require the use of @RequestParam annotation to request parameters bound to succeed.

Request URL

  http://localhost:8080/xxx/findItem?itemId=1

  Request parameter key is itemId

Controller Methods

  Controller's parameter is Integer id, inconsistent parameters and request it, you need to use annotations to bind succeeds @RequestParam

     @RequestMapping (value = "/ the findItem" )
     // binding by simple type annotation @RequestParam 
    public String the findItem (@RequestParam ( "itemId" ) Integer ID) { 
          System.out.println ( "request parameters received are:" + ID);
           return "Success" ; 
    }

RequestParam notes Introduction

  value : Parameter name, i.e. the name reference request parameters, such as the value = "itemId" indicates that the request parameter name parameter value passed in itemId

  required : if necessary, the default is true, meaning the request parameter must have a response that would otherwise be reported;

    http Status 400 - Required Integer parameter 'xxx' is not present

  defaultValue : Default, indicates the default value when a request is not the same name if the parameter

@ RequestMapping (value = "/ findItem" )
     // Bind simple types by @RequestParam comment
     // learning @RequestParam notes of value, required, defaultValue property 
    public String findItem ( 
            @RequestParam (value = "itemId", required = to true , defaultValue = "2" ) ID Integer) { 

         System.out.println ( "request parameters received are:" + ID);
           return "Success" ; 
    }

Binding POJO type

Claim

  Parameter type controller method is POJO type.

  Required form parameter names and POJO class attribute names consistent.

Request URL

  http://localhost:8080/xxx/updateItem?id=!&name=iphone&price=1000

Controller Methods

POJO definitions:

 

Controller Methods

@RequestMapping("/updateItem")
    public String updateItem(Integer id,Items item) {
        
         System.out.println("接收到的请求参数是:"+ id);
         System.out.println("接收到的请求参数是:"+ item);
        return "success";
    }

绑定包装POJO

   包装POJO类,依然是一个POJO,只是说为了方便沟通,将POJO中包含另一个POJO的这种类,称之为包装POJO。

包装对象

public class ItemQueryVO {
    //商品信息
    private Items item;
}

页面定义(item-list.jsp)

查询条件:
        <table width="100%" border=1>
            <tr>
                <td>商品名称:<input type="text" name="items.name" /></td>
                <td><input type="submit" value="查询" /></td>
            </tr>
        </table>

Controller方法

 

 测试方法:断点跟踪,查看vo中的item对象是否有值

使用简单类型数组接收参数

要求

  通过HTTP请求批量传递简单类型数据的情况,Controller方法中可以用String[]或者POJO的String[]属性接收(二选一),但是不能使用集合接收

请求URL

  http://localhost:8080/xxx/deleteItem?id=1&id=2&id=3

Controller方法

    @RequestMapping("/deleteItem")
    public String deleteitem(Integer[] itemId){
        
        return "success";
    }

使用POJO类型集合或数组接收参数

要求

  批量传递的请求参数,最终要使用List<POJO>来接收,那么这个List<POJO>必须放在另一个POJO类中。

接收商品列表的POJO

public class ItemQueryVO {

    // 商品信息
    private Item item;
    // 其他信息

    // 商品信息集合
    private List<Items> itemsList;
}

请求URL

  http://localhost:8080/xxx/batchUpdateItem?itemsList[0].id=1&itemsList[0].name=iphone&itemsList[0].price=1000&itemsList[1].id=2&itemsList[1].name=华为&items[1].price=5000

Controller

    @RequestMapping("/batchUpdateItem")
    public String batchUpdateItem(ItemQueryVO vo) {
        return "success";
    }

自定义参数绑定

请求URL

  http://localhost:8080/xxx/saveItem?date=2019-12-4

Controller方法

    @RequestMapping("/saveItem")
    public String saveItem(String date){
        System.out.println("接收到的请求参数是:"+ date);
        return "success";
    }

但是如何将date参数的类型有String改为Date,则报错

自定义Converter

public class DateConverter implements Converter<String, Date> {

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

配置Converter

在springmvc.xml中,进行以下配置

    <!-- 加载注解驱动 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!-- 转换器配置 -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.cyb.ssm.controller.converter.DateConverter"/>
            </set>
        </property>
    </bean>

Guess you like

Origin www.cnblogs.com/chenyanbin/p/11980465.html