1 前言
在史上最簡單的 Spring MVC 教程(九)中怖现,咱們已經(jīng)實(shí)現(xiàn)了圖片的上傳及顯示功能蹂随,那么接下來十嘿,在本篇博文中,咱們更進(jìn)一步岳锁,以實(shí)體類(Person)中的字段“name”和控制器(PersonController)中的方法 updatePersonList 為例绩衷,實(shí)現(xiàn)參數(shù)的校驗(yàn)功能。
2 注解示例 - 參數(shù)校驗(yàn)
老規(guī)矩激率,首先給出項(xiàng)目結(jié)構(gòu)圖:
在給出代碼之前咳燕, 咱們先明確參數(shù)校驗(yàn)的步驟:
- 導(dǎo)入?yún)?shù)校驗(yàn)的 jar 包;
- 在實(shí)體上配置需要校驗(yàn)的屬性乒躺;
- 在控制器的方法中用注解 @Valid 明確開啟校驗(yàn)招盲;
- 校驗(yàn)錯(cuò)誤后,傳遞錯(cuò)誤信息嘉冒;
- 返回錯(cuò)誤頁面宪肖,并提示錯(cuò)誤信息。
其中健爬,參數(shù)校驗(yàn)所需的 jar 包可以在Spring MVC框架的各種依賴包 中進(jìn)行下載,然后導(dǎo)入到“External Libraries”之中么介。
第一步:修改實(shí)體類(Person)娜遵,明確需要校驗(yàn)的屬性
package spring.mvc.domain;
import javax.validation.constraints.Size;
/**
* Created by 維C果糖 on 2017/1/30.
*/
public class Person {
private Integer id;
@Size(min = 6, max = 12, message = "姓名必須大于6個(gè)字符,小于12個(gè)字符壤短!")
private String name;
private Integer age;
private String photoPath; // 圖片存儲(chǔ)路徑
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhotoPath() {
return photoPath;
}
public void setPhotoPath(String photoPath) {
this.photoPath = photoPath;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
第二步:在控制器(PersonController)的方法 updatePersonList 中開啟校驗(yàn)功能
package spring.mvc.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import spring.mvc.domain.Person;
import spring.mvc.service.PersonService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Created by 維C果糖 on 2017/1/30.
*/
@Controller
public class PersonController {
@Resource
PersonService ps; // 注入 service 層
@RequestMapping(value = "/person/all")
public String findAll(Map<String, Object> model) { // 聲明 model 用來傳遞數(shù)據(jù)
List<Person> personList = ps.findAll();
model.put("personList", personList); // 通過這一步设拟,JSP 頁面就可以訪問 personList
return "/person/jPersonList"; // 跳轉(zhuǎn)到 jPersonList 頁面
}
@RequestMapping("/person/toCreatePersonInfo")
public String toCteatePersonInfo() { // 跳轉(zhuǎn)新增頁面
return "/person/jPersonCreate";
}
@RequestMapping("/person/toUpdatePersonInfo")
public String toUpdatePersonInfo(Integer id, Model model) { // 跳轉(zhuǎn)修改頁面
Person p = ps.get(id); // 獲得要修改的記錄慨仿,重新設(shè)置頁面的值
model.addAttribute("p", p); // 將數(shù)據(jù)放到 response
return "/person/jPersonUpdate";
}
@RequestMapping("/person/updatePersonList")
public String updatePersonList(HttpServletRequest request,
@Valid Person p,
BindingResult bindingResult,
Model model,
@RequestParam("photo") MultipartFile photeFile) throws IOException { // 更新人員信息
if (p.getId() == null) {
ps.insert(p); // 調(diào)用 Service 層方法,插入數(shù)據(jù)
} else {
if(bindingResult.hasErrors()){ // 判斷校驗(yàn)是否發(fā)現(xiàn)錯(cuò)誤
model.addAttribute("bindingResult", bindingResult);
model.addAttribute("p",p);
return "/person/jPersonUpdate"; // 校驗(yàn)錯(cuò)誤纳胧,返回錯(cuò)誤頁面镰吆,進(jìn)行錯(cuò)誤提示
}
String dir = request.getSession().getServletContext().getRealPath("/") + "/upload/";
String fileName = photeFile.getOriginalFilename(); // 原始的文件名
String extName = fileName.substring(fileName.lastIndexOf(".")); // 擴(kuò)展名
fileName = fileName.substring(0, fileName.lastIndexOf(".")) + System.nanoTime() + extName; // 防止文件名沖突
FileUtils.writeByteArrayToFile(new File(dir + fileName), photeFile.getBytes()); // 寫文件到 upload 目錄
p.setPhotoPath("/upload/" + fileName);
ps.update(p); // 調(diào)用 Service 層方法,更新數(shù)據(jù)
}
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
@RequestMapping("/person/deleteById")
public String deleteById(Integer id) { // 刪除單條記錄
ps.deleteById(id);
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
@RequestMapping("/person/deleteMuch")
public String deleteMuch(String id) { // 批量刪除記錄
for (String delId : id.split(",")) {
ps.deleteById(Integer.parseInt(delId));
}
return "redirect:/person/all.action"; // 轉(zhuǎn)向人員列表 action
}
}
第三步:修改 jPersonUpdate.jsp 頁面跑慕,用于展示錯(cuò)誤信息
<%--
Created by IntelliJ IDEA.
User: 維C果糖
Date: 2017/1/30
Time: 22:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>PersonList</title>
</head>
<body>
<!-- 其中万皿,modelAttribute 屬性用于接收設(shè)置在 Model 中的對(duì)象,必須設(shè)置核行,否則會(huì)報(bào) 500 的錯(cuò)誤 -->
<sf:form enctype="multipart/form-data"
action="${pageContext.request.contextPath}/person/updatePersonList.action"
modelAttribute="p"
method="post">
<sf:hidden path="id"/>
<div style="padding:20px;">
修改人員信息
</div>
<div style="padding:10px;">
錯(cuò)誤信息:<fond color="red"><sf:errors path="*"/></fond>
</div>
<table>
<tr>
<td>姓名:</td>
<td><sf:input path="name"/><sf:errors path="name"/></td>
</tr>
<tr>
<td>年齡:</td>
<td><sf:input path="age"/></td>
</tr>
<tr>
<td>圖片:</td>
<td><input type="file" name="photo" value=""/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="btnOK" value="保存"/></td>
</tr>
</table>
</sf:form>
</body>
</html>
此外牢硅,還有一點(diǎn)值得大家注意,那就是:在前九篇的博文中芝雪,咱們?cè)跇?gòu)建項(xiàng)目的時(shí)候减余,在“WEB-INF”目錄下建立了一個(gè)名為“l(fā)ib”的目錄,并將項(xiàng)目所需的 jar 都導(dǎo)入其中惩系,在這里位岔,其實(shí)不同 IDE 有不同的使用方法,例如在 Eclipse 中堡牡,我們就需要把 jar 包導(dǎo)入到 “l(fā)ib”目錄抒抬;但如果是 IntelliJ IDEA,我們則不需要建立“l(fā)ib”目錄悴侵,直接到 jar 包導(dǎo)入到“External Libraries”中即可瞧剖。