spring mvc处理表单提交

来源:互联网 发布:淘宝信息管理系统建设 编辑:程序博客网 时间:2024/04/29 07:46

1.表单数据的提交

<form action="/springmvc/user/new"><table><tr><td><input name="name"/></td><td><input name="age"/></td><td><input type="submit" value="提交"/></td></tr></table></form>


controller中处理表单提交的方法所接受的参数中,与表单对象name所对应的的字段都会被注入表单所提交的值,这里Person类中有name,age字段都会被注入值,形参name以及age也会被注入值
@RequestMapping(value="/user/new")public String login(String name, int age, Person person){return "/springmvc";}

2.表单数据的验证

public class Person {@Size(min=3, max=50, message="用户名长度不合适")private String name;private int age;}
如果需要对Person对象中的某些字段做验证:

在Controller中的login方法中Person前加上@Valid,那么在注入属性的时候会对其进行验证

在页面上面可以通过:

<sf:errors path="name" cssClass="error" />
来显示表单的错误信息


3.附件的上传

修改表单:

<form action="/springmvc/user/new" enctype="multipart/form-data"><table><tr><td><input name="name"/></td></tr><tr><td><input name="age"/></td></tr><tr><td><input name="picture" type="file"/></tr><tr><td><input type="submit" value="提交"/></td></tr></table></form>
multipart/form-data表示表单中含有附件,但是DispatcherServlet并不知道如何处理这种请求

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="500000" />
我们配置multipartResolver来处理请求中的附件流,bean的id不能变,因为DIspatcher通过bean id来找到该bean
@RequestMapping(value="login")public String login(MultipartFile pictrue, Person person, BindingResult bindingResult){try {validateImg(pictrue);saveImg(person.getName()+".jepg", pictrue);} catch (Exception e) {bindingResult.reject(e.getMessage());}return "/springmvc";}private void saveImg(String filename, MultipartFile image)throws IOException {File file = new File(webRootPath + "/resources/" + filename);FileUtils.writeByteArrayToFile(file, image.getBytes());}private void validateImg(MultipartFile pictrue) throws ImageFormatException {if(!"image/jpeg".equals(pictrue.getContentType())){throw new ImageFormatException("只能提交图片格式文件!");}}
处理多文件上传的问题我们可以在方法参数中添加对应页面标签name属性的参数名,也可以将HttpServletRequest对象强制转换为MultipartRequest类型,然后通过MultipartRequest.getFileMap()得到Map<String, MultipartFile>,然后分别保存每个提交的文件。

4.文件的下载

通过设置响应的头消息来实现文件的下载功能。

在请求处理的Controller的方法参数中添加参数HttpServletResponse response,spring会自动将response对象注入到参数中

@RequestMapping(value="download")public String download(HttpServletResponse response, String fileName) throws IOException{//告诉浏览器下载文件的格式,如果格式不固定可以不用设置,让浏览器自己判断response.setContentType("application/x-msdownload;");response.setHeader("Content-disposition", "attachment; filename=" + fileName.lastIndexOf(File.separator) + 1);OutputStream os = response.getOutputStream();File file = new File(fileName);//将文件中的内容写入outputsreamFileUtil.readFile(file,os);return null;}




原创粉丝点击