绑定基本类型和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
自定义类型转换器
- 实现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转换失败");
}
}
}
- 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>
原文地址:https://www.cnblogs.com/ttpfx/p/14596814.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。