SpringMVC parameter binding study summary [] before and after the end of the data transfer parameters

Controller as SpringMVC layer (action equivalent servlet and the struts) designed to process the page number requested, then the data is again returned to the user through a view, the data thus be seen that front and rear ends of the transmission parameters relative importance springmvc, article springmvc will summarize the argument in how to receive front page, that springmvc the parameter binding issue.
@

1. binding mechanism

Form submission data is k = v format, SPRINGMVC parameter binding process parameter request to submit a form, the method in the controller as a parameter of binding, but note that submitted the form name and the controller method the parameter names are the same

2. Supported data types

springmvc, there is support for the default type of binding, visible springmvc framework of a strong framework is strong ~ ~. That is, the direct parameter defines the default type of object methods supported in the controller, it can use the following objects.

HttpServletRequest object
HttpServletResponse object
HttpSession Object
Model / ModelMap objects

Basic data types supported data types, packaging, string type, entity type (the JavaBean), the aggregate data type (List, map collections, etc.), then the following will specifically analysis.

2.1, the basic data types, string

In fact, I have the following test classes including basic data types, packaging, type a string!
controller test code

@Controller
@RequestMapping("/param")
public class ParamController {
    @RequestMapping("/testBaseParam")
    public String testParam(String username,int password,Integer san){
        System.out.println("testParam执行了...");
        System.out.println("用户名:"+username);
        System.out.println("密码:"+password);
        System.out.println("密码:"+san);
        return "success";
    }

index.jsp test code

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>测试基础类型</h3>
    <a href="param/testBaseParam?username=刘备胎&password=123&san=456">请求参数绑定</a>
</body>
</html>

Operating results
Here Insert Picture Description
Again, note the name and submit the form parameter name must be the same, otherwise bind fails
Here Insert Picture Description
basic data types, packaging, string type summary: 1, submit the form name and the name of the parameter must be the same. 2, strictly case-sensitive

2.2, entity type (the JavaBean)

The first case: the entity class Normal

dao test code

//实现可序列化接口
public class Account implements Serializable{
//Account数据库字段
    private String username;
    private String password;
    private Double money;


...省去getset方法和toString方法

controller test code

//请求参数绑定把数据封装到JavaBean的类中
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("saveAccount执行了...");
        System.out.println(account);
        return "success";
    }

Used herein index.jsp forwards to param.jsp, code is as follows:

<jsp:forward page="param.jsp"></jsp:forward>

param.jsp test code as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    把数据封装Account类中
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

Test results
Here Insert Picture Description
first case Summary: Note to submit the form name and the name of the parameter must be the same bind failure - stressed n times ~

The second case: the entity class contains object attributes

dao test code, attention Account entity class contains User object properties

//实现可序列化接口
public class Account implements Serializable{
//Account数据库字段
    private String username;
    private String password;
    private Double money;
//User对象属性
    private User user;
    
...省去getset方法和toString方法

User entity class code

//实现可序列化接口
public class User implements Serializable{
    private String uname;
    private Integer age;
    private Date date;

...省去getset方法和toString方法

controller test code has not changed, so it does not stick out.
param.jsp test code as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    把数据封装Account类中
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>
        用户姓名:<input type="text" name="user.uname" /><br/>
        用户年龄:<input type="text" name="user.age" /><br/>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

Test results
Here Insert Picture Description
Observant students may have found, date attribute is null, because I did not give the date by value in the jsp it is null.
Summarized the second case: the entity class contains object attributes this case, front and rear end transmission format parameters jsp: entity object corresponding to the entity class attribute field.

2.3, aggregate data type (List, map collections, etc.)

Test dao class code:

 //实现可序列化接口 
public class Account implements Serializable{
//Account数据库字段
    private String username;
    private String password;
    private Double money;
//集合对象属性
    private List<User> list;
    private Map<String,User> map;
  
...省去getset方法和toString方法

controller test code

//请求参数绑定把数据封装到带集合类型的JavaBean的类中
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account){
        System.out.println("saveAccount执行了...");
        System.out.println(account);
        return "success";
    }

param.jsp test code as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
     把数据封装Account类中,类中存在list和map的集合
    <form action="param/saveAccount" method="post">
        姓名:<input type="text" name="username" /><br/>
        密码:<input type="text" name="password" /><br/>
        金额:<input type="text" name="money" /><br/>

        用户姓名:<input type="text" name="list[0].uname" /><br/>
        用户年龄:<input type="text" name="list[0].age" /><br/>

        用户姓名:<input type="text" name="map['one'].uname" /><br/>
        用户年龄:<input type="text" name="map['one'].age" /><br/>
        <input type="submit" value="提交" />
    </form>

</body>
</html>

Test results
Here Insert Picture Description
are summarized: Type jsp set format: list [0] property.

3. Chinese garbled solve the parameters of the request

After the above tests, some students may occur Chinese garbage problem, which is normal, because we do not set up a similar request.setCharacterEncoding("UTF-8")operation, in order to prevent Chinese garbled solve, we can set up a unified global coding filter.
Spring filter class configuration provided 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>

4. custom type converter

既然springmvc强大到提供默认支持很多类型,但是还是存在瑕疵,例如我们在保存date日期类型的数据时,springmvc只支持2019/9/18 该种格式,如果换成2019-8-18 则将报错,那我也不能光说不做鸭,下面我就再来踩一次坑,让大家LookLook,这里会报The server cannot or will not process the request due to something that is perceived to be a client error异常,不过没事,我也写了专门决绝该异常的一篇文章,点击进入,不扯了,开始测试
jsp关键代码

 用户生日:<input type="date" name="user.date" /><br/>

报错效果:
Here Insert Picture Description
为了跟有力的证明我刚说的springmvc只支持2019/9/18 该种格式,如果换成2019-8-18 则将报错,那么我就把jsp关键代码更改了一下,把type=date改成了type=text,如下

    用户生日:<input type="text" name="user.date" /><br/>

效果如下
Here Insert Picture Description
我们想想,表单提交的任何数据类型全部都是字符串类型,但是后台定义Integer类型,数据也可以封装上,说明Spring框架内部会默认进行数据类型转换。如果想自定义数据类型转换,该怎么实现呢?

4.1创建一个普通类实现Converter接口

1、创建一个普通类实现Converter接口,并添加相应格式转换方法,代码如下

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

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

/**
 * 把字符串转换日期
 */
public class StringToDateConverter implements Converter<String,Date>{

    /**
     * String 传入进来字符串
     */
    public Date convert(String source) {
        // 判断
        if(source == null){
            throw new RuntimeException("请您传入数据呐");
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        try {
            // 把字符串转换日期
            return df.parse(source);
        } catch (Exception e) {
            throw new RuntimeException("完蛋~数据类型转换出现错误");
        }
    }

}

4.2Springmvc.xml中配置自定义类型转换器

  1. 注册自定义类型转换器,在springmvc.xml配置文件中编写配置
<!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.gx.utils.StringToDateConverter"/>
            </set>
        </property>
    </bean>


    <!-- 开启SpringMVC框架注解的支持 -->
    <mvc:annotation-driven conversion-service="conversionService"/>

效果如下:
Here Insert Picture Description
自定义类型转换器步骤总结
1、创建一个普通类实现Converter接口,并添加相应格式转换方法
2、注册自定义类型转换器,在springmvc.xml配置文件中编写配置

After ten million Do not forget to configure in the registration drive in the notes , which is this one

 <mvc:annotation-driven conversion-service="conversionService"/>

5, the last parameter binding study summary

Here Insert Picture Description

If this article there is a little bit of help to you, then please point a chant praise, thank you ~

Finally, if there is insufficient or is not correct, please correct me criticism, grateful! If you have questions please leave a message, the absolute first time to reply!

I welcome you to focus on the public number, to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/yichunguo/p/11974573.html
Recommended