文章目录
1 controller 参数绑定
获取请求参数中的value值(String类型),将参数转为controller方法中的形参类型,然后将转换后的值赋值给形参,这个过程就是参数绑定。
SpringMVC默认内置了24种参数解析组件ArgumentResolver
2 默认支持的参数类型
HttpServletRequest
通过request对象获取请求信息
HttpServletResponse
通过response处理响应信息
HttpSession
通过session对象得到session中存放的对象
InputStream、OutputStream
获取输入输出流对象,处理二进制信息
Reader、Writer
处理文本文件
Model/ModelMap
ModelMap继承自LinkedHashMap,Model是一个接口,它们的底层实现都是同一个类(BindingAwareModelMap),作用就是向页面传递数据,相当于Resquest的作用
2.1 demo
@RequestMapping(value = "helloReq",method ={RequestMethod.POST,RequestMethod.GET} )
public String helloRequest(HttpServletRequest request, HttpServletResponse response){
// 获取服务端的信息
String contextPath =request.getContextPath();
String servletPath = request.getServletPath();
String name = request.getServerName();
String method = request.getMethod();
StringBuffer URL=request.getRequestURL();
String addr= request.getRemoteAddr();
int port = request.getRemotePort();
String sessionId = request.getRequestedSessionId();
HttpSession session = request.getSession();
log.info("contextPath: "+contextPath+" servletPath: "+servletPath+"\n servletName: "+name
+" requestMethod: "+method+"\n URL: "+URL+" address: "+addr+"\n RemotePort: "+port+" sessionId: "+sessionId
+"\n session: "+session);
// 往服务端发送数据
String hello ="hello Request and Response ";
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=null;
try {
out= response.getWriter();
out.write(hello);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out!=null)
out.close();
}
return "hello";
}
页面会显示文本“hello Request and Response”
3 普通参数绑定
3.1 绑定简单参数类型
简单类型指的就是8种基本类型数据以及它们的包装类,还有String类型。
1. 直接绑定
ControllerDemo.java
@RequestMapping("paraBind1")
public String paraBinding1(int id){
log.info("简单参数直接绑定,获取的参数id:"+id);
return "hello";
}
hello.jsp
<a href="/demo/paraBind2?id=10">简单参数直接绑定</a>
直接绑定要求请求参数的key和controller方法中的形参名称一致
2. 注解绑定
当不一致时,使用@ResquestParam注解进行参数绑定
@RequestMapping("paraBind2")
public String paraBinding2(@RequestParam("item") int id){
log.info("简单参数通过注解绑定,获取的参数id:"+id);
return "hello";
}
<p><a href="/demo/paraBind2?item=20">简单参数,注解绑定</a></p>
3.2 绑定pojo
要求请求中的参数类型和pojo类中的属性名称保持一致
@RequestMapping("paraBind3")
public String paraBinding3(User user){
log.info("pojo参数绑定,获取的user:"+user);
return "hello";
}
<p><a href="/demo/paraBind3?id=20&name=pojo&password=root&address=address">pojo绑定</a></p>
输出结果
INFO [http-nio-8080-exec-8] - pojo参数绑定,获取的user:User{id=20, name='pojo', password='root', address='address'}
3.3 绑定包装类
public class QueryUser {
User user;
// 省略set、get、toString
// 没有set方法赋值会失败
@RequestMapping("paraBind4")
public String paraBinding4(QueryUser queryUser){
log.info("包装pojo参数绑定,获取的QueryUser:"+queryUser);
return "hello";
}
<form action="/demo/paraBind4" method="post">
用户名称:<input type="text" name="user.name"><br />
用户地址:<input type="text" name="user.address"><br />
<input type="submit" value="包装pojo绑定">
</form>
3.4 绑定批量简单类型数据
通过HTTP请求批量传递简单类型数据的情况,Controller方法中可以用String[]或者pojo的String[]属性接收(两种方式任选其一),但是不能使用集合接收。
3.5 绑定批量pojo
public class QueryUser {
User user;
List<User> users;
@Override
public String toString() {
return "QueryUser{" +
"user=" + user +
"users="+users+
'}';
}
<form action="/demo/paraBind6" method="post">
id1:<input type="text" name="users[0].id"><br />
id2:<input type="text" name="users[1].id"><br />
<input type="submit" value="批量pojo绑定">
</form>
3.7 自定义参数绑定
首先需要自定义类型转换器
测试
<p><a href="/demo/paraBind7?date=2018-11-20">date数据绑定</a></p>
@RequestMapping("paraBind7")
public String paraBinding7(Date date){
log.info("date 数据绑定:"+date);
return "hello";
}
4 json数据交互
4.1 新增依赖
使用fastjson完成json数据转成pojo数据
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
4.2 设置消息转换器
在配置文件中注册Json数据转换器,配置完成后在总配置文件中@Import(ConfigAdapter.class)
@Configuration
@EnableWebMvc
public class ConfigAdapter implements WebMvcConfigurer {
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 1、需要先定义一个·convert转换消息的对象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2、添加fastjson的配置信息,比如 是否要格式化返回json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3、在convert中添加配置信息.
fastConverter.setFastJsonConfig(fastJsonConfig);
// 4、将convert添加到converters当中.
converters.add(fastConverter);
}
}
4.3 测试
@Controller
public class JsonController {
@RequestMapping("kv2Json")
@ResponseBody
public User kv2Json(User user){
return user;
}
@RequestMapping("json2Json")
@ResponseBody
public User json2Json(@RequestBody User user){
return user;
}
}
<button onclick="sendJson()">json2json数据交互测试</button>
<script type="text/javascript">
function sendJson() {
$.ajax({
type:"post",
url:"${pageContext.request.contextPath }/json2Json",
data:'{id:"1",name:"json2Json"}',
dataType:"json",
contentType:"application/json;charset=utf-8",
success:function(result) {
alert("name:"+result.name+"\n id:"+result.id);
// alert(result.id + ":" + result.name+" data:"+result);
}
});
}
</script>
<button onclick="KV2Json()">kv2json数据交互测试</button>
<script type="text/javascript">
function KV2Json(){
$.ajax({
type:"post",
url:'${pageContext.request.contextPath }/kv2Json',
//输入是key/value时,默认就指定好了contentType了,不需要再指定了
//contentType:'application/json;charset=utf-8',
//data为key/value形式
data:'name=kv2json测试&address=kv',
dataType:"json",
success:function(result){
alert("name:"+result.name+"\n address:"+result.address);
}
});
}
</script>