SpringMvc的文件上传下载:

文件上传

单文件上传

1.底层使用的是Apache fileupload组件进行上传的功能,Springmvc 只是对其进行了封装,简化开发,

pom.xml

<!--    apache fileupload-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

2.JSP页面处理

  • inpu的type设置为file

  • form表单的method设置为post

  • form表单的enctype设置为multipar/form-data

    一:单文件:

JSP

<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-07
Time: 16:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="img"/>
<input type="submit" value="提交"/>
</form>
<img src="${src}">
</body>
</html>

Handler

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException; @Controller
@RequestMapping("/file")
public class fileHandler {
@PostMapping("/upload")
public String upload(@RequestParam("img")MultipartFile img, HttpServletRequest request) {
if(img.getSize()>0){
String path =request.getSession().getServletContext().getRealPath("file");
String fileName =img.getOriginalFilename();
File file =new File(path,fileName);
try {
img.transferTo(file);
request.setAttribute("src","/file/"+fileName);
} catch (IOException e) {
e.printStackTrace();
} }
return "upload";
}
}

配置解析器:

<!--    配置转换器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

二:多文件:

@PostMapping("/uploads")
public String uploads(@RequestParam("imgs")MultipartFile[] imgs, HttpServletRequest request) {
List<String> pathlist = new ArrayList<>();
for (MultipartFile img : imgs) {
if (img.getSize() > 0) {
String path = request.getSession().getServletContext().getRealPath("file");
String fileName = img.getOriginalFilename();
File file = new File(path, fileName);
try {
img.transferTo(file);
pathlist.add("/file/" + fileName);
} catch (IOException e) {
e.printStackTrace();
} }
}
request.setAttribute("list",pathlist);
return "upload";
}
<form action="/file/uploads" method="post" enctype="multipart/form-data">
file1:<input type="file" name="imgs"><br>
file1:<input type="file" name="imgs"><br>
<input type="submit" value="提交">
</form>
<c:forEach items="${list}" var="path">
<img src="${path}" width="300px">
</c:forEach>

文件下载

@GetMapping("/downLoad")
public void downLoad(String fileName, HttpServletRequest request, HttpServletResponse response){
if(fileName!=null){
String path = request.getSession().getServletContext().getRealPath("file");
File file =new File(path,fileName);
OutputStream outputStream=null;
if(file.exists()){
//设置下载文件
response.setContentType("application/force-downlocad");
//设置文件名
response.setHeader("Content-Dispoition","attachment;filename"+fileName);
try {
outputStream=response.getOutputStream();
outputStream.write(FileUtils.readFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} }

Spring Mvc 数据校验的组件

有两种:

  • 基于Vaildator接口进行校验

  • 使用Annotation JSR-303标准校验

    使用Vaildator接口会复杂点,开发者要自己定义规则,而Annotation JSR-303则是要开发者添加对应的校验注解即可。

    基于Validator的接口*

    1.创建实体类:

    package com.southwind.entity;
    
    import lombok.Data;
    
    @Data
    public class Student {
    // private Integer id;
    // private String name;
    // private Integer age;
    private String name;
    private String password;
    }

    2.自定义数据校验器StudentValidator实现Validator接口,重写接口的抽象方法,加入校验规则。

    package com.southwind.validation;
    
    import com.southwind.entity.Student;
    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.validation.Validator; public class StudentValidator implements Validator { @Override
    public boolean supports(Class<?> aClass) {
    return Student.class.equals(aClass);
    } @Override
    public void validate(Object o, Errors errors) {
    ValidationUtils.rejectIfEmpty(errors,"name",null,"姓名不能为空");
    ValidationUtils.rejectIfEmpty(errors,"password",null,"密码不能为空");
    }
    }

3.业务方法:

package com.southwind.controller;

import com.southwind.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
@RequestMapping("/validatior") public class ValidatiorHandler {
//先数据绑定
@GetMapping("/login")
public String login(Model model){
model.addAttribute(new Student());
return "login";
}
@RequestMapping("/login")
public String login(@Validated Student student, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "login";
}else {
return "login";
}
}
}
package com.southwind.validation;

import com.southwind.entity.Student;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator; public class StudentValidator implements Validator { @Override
public boolean supports(Class<?> aClass) {
return Student.class.equals(aClass);
} @Override
public void validate(Object o, Errors errors) {
ValidationUtils.rejectIfEmpty(errors,"name",null,"姓名不能为空");
ValidationUtils.rejectIfEmpty(errors,"password",null,"密码不能为空");
}
}

Annotation JSR-303

Hibernater Validator,通过注解完成校验

名称 说明
@Null 被标注的元素必须为 null
@NotNull 被标注的元素必须不为 null
@AssertTrue 被标注的元素必须为 true
@AssertFalse 被标注的元素必须为 false
@Min(value) 被标注的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被标注的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMax(value) 被标注的元素必须是一个数字,其值必须大于等于指定的最大值
@DecimalMin(value) 被标注的元素必须是一个数字,其值必须小于等于指定的最小值
@size 被标注的元素的大小必须在指定的范围内
@Digits(integer,fraction) 被标注的元素必须是一个数字,其值必须在可接受的范围内;integer 指定整数精度,fraction 指定小数精度
@Past 被标注的元素必须是一个过去的日期
@Future 被标注的元素必须是一个将来的日期
@Pattern(value) 被标注的元素必须符合指定的正则表达式

配置:

pom.xml

<!--    JSP303-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.6.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.4.1.Final</version>
</dependency>
<mvc:annotation-driven></mvc:annotation-driven>

业务页面:

@GetMapping("/register")
public String register(Model model){
model.addAttribute(new Account());
return "register";
}
@PostMapping("/register")
public String register(@Valid Account account,BindingResult bindingResult ){
if(bindingResult.hasErrors()){
return "register";
}else {
return "success";
} }

实体类:

package com.southwind.entity;

import lombok.Data;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; @Data
public class Account {
@NotEmpty(message = "用户名不能为空")
private String userName;
@Size(min = 6,max = 20,message = "长度为5到20位")
private String password;
@Email(regexp = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?",message = "请输入正确的表达式")
private String email;
@Pattern(regexp = "\\d{3}-\\d{8}|\\d{4}-\\{7,8}",message = "请输入正确的表达式")
private String phone; }

页面:

<%--
Created by IntelliJ IDEA.
User: 郝泾钊
Date: 2022-04-07
Time: 19:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1> 用户登录</h1>
<form:form modelAttribute="account" action="/validatior/register">
用户名:<form:input path="userName"></form:input><form:errors path="userName"></form:errors><br>
密码:<form:input path="password"></form:input><form:errors path="password"></form:errors><br>
邮箱:<form:input path="email"></form:input><form:errors path="email"></form:errors><br>
电话:<form:input path="phone"></form:input><form:errors path="phone"></form:errors><br>
<input type="submit" value="提交">
</form:form>
</body>
</html>

SpringMVC的文件、数据校验(Vaildator、Annotation JSR-303)的更多相关文章

  1. SpringMvc中的数据校验

    SpringMvc中的数据校验 Hibernate校验框架中提供了很多注解的校验,如下: 注解 运行时检查 @AssertFalse 被注解的元素必须为false @AssertTrue 被注解的元素 ...

  2. springMVC使用JSR303数据校验

    JSR303注解 hibernate validate是jsr 303的一个参考实现,除支持所有的标准校验注解外,他还支持扩展注解 spring4.0拥有自己独立的数据校验框架,同时支持jsr 303 ...

  3. 【SpringMVC学习06】SpringMVC中的数据校验

    这一篇博文主要总结一下springmvc中对数据的校验.在实际中,通常使用较多是前端的校验,比如页面中js校验,对于安全要求较高的建议在服务端也要进行校验.服务端校验可以是在控制层conroller, ...

  4. SpringMVC——数据转换 & 数据格式化 & 数据校验

    一.数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方 法的入参实例传递给 WebDataBinderFactory 实例,以创 建 DataBinder ...

  5. Spring MVC @InitBinder 数据绑定 & 数据格式化 & 数据校验

    1 数据绑定 2 数据格式化 修改绑定的字段等等操作 日期 - 接收表单日期字符串格式内容.,在实体类加入@DateTimeFormat 数值 原理: DefautFormattingConversi ...

  6. SpringMVC框架下数据的增删改查,数据类型转换,数据格式化,数据校验,错误输入的消息回显

    在eclipse中javaEE环境下: 这儿并没有连接数据库,而是将数据存放在map集合中: 将各种架包导入lib下... web.xml文件配置为 <?xml version="1. ...

  7. SpringMVC 数据转换 & 数据格式化 & 数据校验

    数据绑定流程 1. Spring MVC 主框架将 ServletRequest 对象及目标方法的入参实例传递给 WebDataBinderFactory 实例,以创建 DataBinder 实例对象 ...

  8. SpringBoot入门 (十一) 数据校验

    本文记录学习在SpringBoot中做数据校验. 一 什么是数据校验 数据校验就是在应用程序中,对输入进来得数据做语义分析判断,阻挡不符合规则得数据,放行符合规则得数据,以确保被保存得数据符合我们得数 ...

  9. Hibernate数据校验简介

    我们在业务中经常会遇到参数校验问题,比如前端参数校验.Kafka消息参数校验等,如果业务逻辑比较复杂,各种实体比较多的时候,我们通过代码对这些数据一一校验,会出现大量的重复代码以及和主要业务无关的逻辑 ...

  10. springMVC数据校验与单文件上传

    spring表单标签:    <fr:from/> 渲染表单元素    <fr:input/>输入框组件    <fr:password/>密码框组件标签    & ...

随机推荐

  1. 图文并茂解释开源许可证GPL、BSD、MIT、Mozilla、Apache和LGPL的区别

    世界上的开源许可证(Open Source License)大概有上百种,而我们常用的开源软件协议大致有GPL.BSD.MIT.Mozilla.Apache和LGPL. 从下图中可以看出几种开源软件协 ...

  2. [Polkadot] 波卡链学习笔记

    前言 早已听闻波卡链大名,但从未真正静下心来了解.最近难得有些属于自己的时间了,故将学习到的记录下来. 介绍 相信大家对波卡链都有些许了解,在这我就长话短说,简单介绍一下. Polkadot是由Web ...

  3. 06#Web 实战:实现可滑动的标签页

    实现效果图 本随笔只是记录一下大概的实现思路,如果感兴趣的小伙伴可以通过代码和本随笔的说明去理解实现过程.我的 Gitee 和 GitHub 地址.注意哦:这个只是 PC 上的标签页,手机端的没用,因 ...

  4. OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 / cairo.so.2

    解决办法 下载 gtk3-runtime-3.24.29-2021-04-29-ts-win64.exe后安装. 记得勾选添加bin目录到环境变量: 这样就不会缺失dll了,当然可能需要重启IDE才能 ...

  5. 解决win7连接蓝牙耳机播放设备找不到的问题

    前言 这个问题其实就是蓝牙驱动问题, 而用第三方软件安装驱动,如驱动精灵安装蓝牙驱动,可能会不出现缺失驱动问题,但是一些功能会受到限制(win7系统与其蓝牙驱动不兼容). 解决办法 去 Inter官网 ...

  6. Django基础笔记5(Session)

    Session cookie:保存在客户端浏览器上的键值对 session:保存在服务器端的数据       保持会话 def index(req): v = req.session.get('use ...

  7. 【Java SE进阶】Day06 线程、同步

    一.线程 1.多线程原理 流程图 内存图解说明 创建线程的方式 继承Thread类 实现 Runnable接口 2.继承Thead类 3.实现Runnable接口 实现接口,重写run方法 最终均需要 ...

  8. mysql报错:【系统出错。发生系统错误 1067。进程意外终止。】解决

    目录 问题描述 错误排查 1.检查3306端口是否被占用 2.使用window事件查看器 总结 问题描述 使用管理员cmd,任务管理器均无法启动mysql. 报错提示信息:系统出错.发生系统错误 10 ...

  9. WCH以太网相关芯片资料总结

    网络产品线产品分类 1.接口控制类.CH395Q           http://www.wch.cn/search?t=all&q=395CH395LCH392F            h ...

  10. Jmeter——循环控制器中实现Counter计数器的次数重置

    近期在使用Jmeter编写个辅助测试的脚本,用到了多个Loop Controller和Counter. 当时想的思路就是三个可变的数量值,使用循环实现:但第三个可变值的数量次数,是基于第二次循环中得到 ...