SpringMVC: parameter binding

Parameter binding

The processor adapter needs to bind the http request key / value data to the Handler method parameter before executing the Handler.

In springmvc, the data submitted by the receiving page is received through the method parameters, not the member variables defined in the controller class!

Types supported by default

Adding the following types of parameter processing adapters to the processor parameters will recognize and assign values ​​by default.

1. HttpServletRequest: Get request information through the request object

2. HttpServletResponse: processing response information through response

3. HttpSession: get the objects stored in the session through the session object

4. Model / ModelMap: ModelMap is the implementation class of the Model interface. Data is passed to the page through Model or ModelMap, and the model data is filled into the request field. as follows:

//调用service查询商品信息
Items item = itemService.findItemById(id);
model.addAttribute("item", item);

The page obtains the attribute value of the item object through $ {item.XXXX}.

Using Model has the same effect as ModelMap. If you use Model directly, springmvc will instantiate ModelMap.

Simple data types: integer, string, single / double precision, Boolean

Use @RequestParam to bind simple type parameters:

If you do not use @RequestParam, the parameter name of the request is required to be the same as the name of the formal parameter of the controller method to bind successfully. 

If you use @RequestParam, there is no need to limit the parameter name of the request and the parameter name of the controller method. 

value: the parameter name, that is, the name of the request parameter entered in the parameter, such as value = "item_id" indicates that the value of the parameter named item_id in the request parameter area will be passed in

required: Whether it is required, the default is true, indicating that the request must have the corresponding parameters, no parameters are passed in, and the following error is reported:

You can use defaultvalue to set the default value, even if required = true, you can not pass the parameter value.

sing

1. Simple pojo

Correspond to the attribute name in the pojo object and the attribute name passed in. If the parameter name passed in is the same as the attribute name in the object, set the parameter value in the pojo object:

页面定义如下:

<input type="text" name="name"/>
<input type="text" name="price"/>
Contrller方法定义如下:

@RequestMapping("/editItemSubmit")
public String editItemSubmit(Items items)throws Exception{
    System.out.println(items);

The request parameter name is the same as the pojo attribute name, and the request parameter will be automatically assigned to the pojo attribute.

2. Packaging pojo

If the naming is similar to the object. Attribute in struts, the pojo object needs to be an attribute of a wrapper object, and the wrapper object is used as a formal parameter in the action.

包装对象定义如下:

Public class QueryVo {
    private Items items; 
}
页面定义:

<input type="text" name="items.name" />
<input type="text" name="items.price" />
注意:items和包装pojo中的属性一致即可。
Controller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
    System.out.println(queryVo.getItems());

post garbled

Add post garbled filter in web.xml 

<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>

get garbled

1. Modify the tomcat configuration file to add the coding to be consistent with the engineering coding, as follows:

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

2. Another method to re-encode the parameters:

String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8"); //ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

Custom parameter binding

For the pojo object in the controller parameter, if there is a date type in the attribute, custom parameter binding is required.

Transfer the requested date data string to a date type, and the date type to be converted remains the same as the type of the date attribute in pojo.

Therefore, the custom parameter binding converts the date string to the java.util.Date type, and a custom parameter binding component needs to be injected into the processor adapter.

//自定义日期参数转换类
public class CustomDateConverter implements Converter<String,Date>{
	@Override
	public Date convert(String source) {	
		//实现 将日期串转成日期类型(格式是yyyy-MM-dd HH:mm:ss)		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		
		try {
			//转成直接返回
			return simpleDateFormat.parse(source);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//如果参数绑定失败返回null
		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">
        <list>
            <!-- 日期类型转换 -->
            <bean class="org.haiwen.controller.converter.CustomDateConverter"/>
        </list>
    </property>
</bean>

Collection class

1. String array

页面选中多个checkbox向controller方法传递:

<input type="checkbox" name="item_id" value="001"/>
<input type="checkbox" name="item_id" value="002"/>
<input type="checkbox" name="item_id" value="002"/>
传递到controller方法中的格式是:001,002,003
Controller方法中可以用String[]接收,定义如下:

public String deleteitem(String[] item_id)throws Exception{
    System.out.println(item_id);
}

2、List

Objects are stored in the List, and the defined List is placed in the packaging class, and the action is received by the packaging object. 

public class QueryVo { 
    //包装类中定义List对象,并添加get/set方法如下:
}
页面定义如下:

<tr>
   <td><input type="text" name=" itemsList[0].id" value="${item.id}"/></td>
   <td><input type="text" name=" itemsList[0].name" value="${item.name }"/></td>
   <td><input type="text" name=" itemsList[0].price" value="${item.price}"/></td>
</tr>
<tr>
   <td><input type="text" name=" itemsList[1].id" value="${item.id}"/></td>
   <td><input type="text" name=" itemsList[1].name" value="${item.name }"/></td>
   <td><input type="text" name=" itemsList[1].price" value="${item.price}"/></td>
</tr>
上边的静态代码改为动态jsp代码如下:

<c:forEach items="${itemsList }" var="item" varStatus="s">
    <tr>
        <td><input type="text" name="itemsList[${s.index }].name" value="${item.name }"/></td>
        <td><input type="text" name="itemsList[${s.index }].price" value="${item.price }"/></td>
        .....
    </tr>
</c:forEach>
Contrller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
    System.out.println(queryVo.getItemList());
}

3、Map

Define the Map object in the packaging class, and add the get / set method, the action uses the packaging object to receive.

public class QueryVo {
private Map<String, Object> itemInfo = new HashMap<String, Object>();
    //get/set方法...
}
页面定义如下:

<tr>
    <td>学生信息:</td>
        <td>
        姓名:<inputtype="text"name="itemInfo['name']"/>
        价格:<inputtype="text"name="itemInfo['price']"/>
        ...
    </td>
</tr>
Contrller方法定义如下:

public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{
    System.out.println(queryVo.getStudentinfo());
}
Published 202 original articles · praised 37 · 30,000+ views

Guess you like

Origin blog.csdn.net/lovecuidong/article/details/103632357