SpringMVC 文件上传 验证框架

springMVC

属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1(现在一般不用),Struts2(一般老项目使用)等。

文件上传

编写工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
public class FileUtil {

/**
* 创建目录
* @param path
*/
public static void createDir(String path){
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
}
}

html标签

1
<input type="file" name="imgFile" />

在Controller中编写方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//文件上传
@RequestMapping("/uploadImg.html")
public String uploadImg(User user, MultipartFile imgFile, HttpSession session){
System.out.println(session.getServletContext().getRealPath("upload"));
//获取上传文件的文件名字
System.out.println(imgFile.getOriginalFilename());
//获取保存文件的目录
String path = session.getServletContext().getRealPath("upload");
System.out.println(path);

//创建目录
FileUtil.createDir(path);

//文件保存路径
File outFile = new File(path, imgFile.getOriginalFilename());

try {
imgFile.transferTo(outFile);
} catch (IOException e) {
e.printStackTrace();
}
return "/index";
}

XML配置

1
2
3
4
5
<!--上传文件必备-->
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000" /> <!--单位字节-->
<property name="defaultEncoding" value="UTF-8" />
</bean>

文件上传必备jar包

1
2
3
4
5
6
7
8
9
10
11
<!--文件上传  必备1-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>

验证框架

必备jar包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--验证框架的jar包-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>

配合使用的注解(注解标记在实体类属性上)

@NotEmpty(message=””) (验证注解的元素值不为null且不为空,字符串长度不为0、集合大小不为0)
@Null(message=””) (被注释的元素必须为null)
@NotNull(message=””) (被注释的元素必须不为null)
@Length(min=””,max=””,message=””) ()
@AssertTrue(message=””) (被注释的元素必须为true)
@AssertFalse(message=””) (被注释的元素必须为false)
@Min(value,message=””) (被注释的元素必须是一个数字,其值必须大于等于指定的最小值)
@Max(value,message=””) (被注释的元素必须是一个数字,其值必须小于于等于指定的最大值)
@DecimalMin(value,message=””) (被注释的元素必须是一个数字,其值必须大于等于指定的最小值)
@DecimalMax(value,message=””) (被注释的元素必须是一个数字,其值必须小于等于指定的最大值)
@Size(max,min,message=””) (被注释的元素的大小必须在指定的范围内)
@Digits(integer=整数位数, fraction=小数位数,message=””) (验证注解的元素值的整数位数和小数位数上限)
@Past(message=””) (被注释的元素必须是一个过去的日期)
@Future(message=””) (被注释的元素必须是一个将来的日期)
@Pattern(value,message=””) (被注释的元素必须符合指定的正则表达式)

Controller代码示例

1
2
3
4
5
6
7
8
9
@RequestMapping("/saveUser.html")
//@valid注解标识的参数后方,必须紧跟BindingResult
public String saveUser(@Valid User u, BindingResult br){
if(br.hasErrors()){
return "error";
}
userService.addUser(new User("Simon"));
return "index";
}

ajax展示调用验证

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping("/addUserVerify")
@ResponseBody
public Object addUserVerify(@Valid SmbmsUser user, BindingResult br){
if(br.hasErrors()){
List<FieldError> fieldErrors = br.getFieldErrors();
//fieldErrors.get(0).getField(); 得到出现错误的属性名称
//fieldErrors.get(0).getDefaultMessage(); 得到错误消息
return fieldErrors;
}
return null;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var flag;

function abc() {
$.ajax({
type:"POST",//请求类型
url:"/addUserVerify",//请求的url
data:{userCode:$("#userCode").val(),userPassword:$("#userPassword").val()},//请求参数
dataType:"json",//ajax接口(请求url)返回的数据类型
async:false,
success:function(data){//data:返回数据(json对象)
if(data != null){
//在html页面创建一个标签 名字和错误的键名一致 然后循环放入错误消息
for(var i = 0; i < data.length; i++){
var temp = $("#"+data[i].field);
var msg = data[i].defaultMessage;
temp.next().html(msg);
}
flag = false;
}else{
flag = true;
}
}
});
return flag;
}