首先看一下都有哪些绑定数据的注解:
1.@RequestParam,绑定单个请求数据,可以是URL中的数据,表单提交的数据或上传的文件;
2.@PathVariable,绑定URL模板变量值;
3.@Cookieva lue,绑定Cookie数据;
4.@RequestHeader,绑定请求头数据;
5.@ModelValue,绑定数据到Model;
6.@SessionAttributes,绑定数据到Session;
7.@RequestBody,用来处理Content-Type不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
8.@RequestPart,绑定“multipart/data”数据,与@RequestParam不同的是它可以指定绑定“multipart/data”数据的类型;
下面我们来看如何使用:
1.@RequestParam:
为了验证文件绑定我们需要先做以下工作:
a.把commons-fileupload-1.3.1.jar和commons-io-2.4.jar两个jar包添加到我们项目。
b.配置我们项目中的springservlet-config.xml文件使之支持文件上传,内容如下:
复制代码
复制代码
其中maxUploadSize用于限制上传文件的最大大小,也可以不做设置,这样就代表上传文件的大小木有限制。defaultEncoding用于设置上传文件的编码格式,用于解决上传的文件中文名乱码问题。
下面就看具体如何使用:
添加一个DataBindController,里面有2个paramBind的action分别对应get和post请求:
复制代码
package com.demo.web.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = "/databind")
public class DataBindController {
@RequestMapping(value="/parambind", method = {RequestMethod.GET})
public ModelAndView paramBind(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("parambind");
return modelAndView;
}
@RequestMapping(value="/parambind", method = {RequestMethod.POST})
public ModelAndView paramBind(HttpServletRequest request, @RequestParam("urlParam") String urlParam, @RequestParam("formParam") String formParam, @RequestParam("formFile") MultipartFile formFile){
//如果不用注解自动绑定,我们还可以像下面一样手动获取数据
String urlParam1 = ServletRequestUtils.getStringParameter(request, "urlParam", null);
String formParam1 = ServletRequestUtils.getStringParameter(request, "formParam", null);
MultipartFile formFile1 = ((MultipartHttpServletRequest) request).getFile("formFile");
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("urlParam", urlParam);
modelAndView.addObject("formParam", formParam);
modelAndView.addObject("formFileName", formFile.getOriginalFilename());
modelAndView.addObject("urlParam1", urlParam1);
modelAndView.addObject("formParam1", formParam1);
modelAndView.addObject("formFileName1", formFile1.getOriginalFilename());
modelAndView.setViewName("parambindresult");
return modelAndView;
}
}
复制代码