SpringMVC之绑定请求参数

绑定基本类型和String

请求参数名称与方法形参名称一致即可

@RequestMapping(path = "/test1")
public String test1(String username, String password) {
   System.out.printf("username=%s, password=%s\n", username, password);
   return null;
}

请求参数:

username:abc
password:1234

绑定JavaBean(含List和Map)

请求参数名称与Bean属性名称一致

@RequestMapping(path = "/test2")
public String test2(User user) {
    System.out.println(user);
    return null;
}

User:

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
    private Role role;
    private List<Role> list;
    private Map<String, Role> map;
}

Role:

public class Role {
    private int id;
    private String name;
}

请求参数:

username:abc
password:1234
role.name:角色名称
list[0].name:角色1
list[1].name:角色2
map['one'].name:角色one
map['two'].name:角色two
birthday:2020-03-30

自定义类型转换器

  1. 实现Converter接口:
public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return simpleDateFormat.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("StringToDate转换失败");
        }
    }
}
  1. Spring配置文件:
<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.ttpfx.converter.StringToDateConverter"/>
        </set>
    </property>
</bean>

解决中文乱码问题

使用SpringMVC过滤器,指定编码为UTF-8格式,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>

相关文章

开发过程中是不可避免地会出现各种异常情况的,例如网络连接...
说明:使用注解方式实现AOP切面。 什么是AOP? 面向切面编程...
Spring MVC中的拦截器是一种可以在请求处理过程中对请求进行...
在 JavaWeb 中,共享域指的是在 Servlet 中存储数据,以便在...
文件上传 说明: 使用maven构建web工程。 使用Thymeleaf技术...
创建初始化类,替换web.xml 在Servlet3.0环境中,Web容器(To...