史上最簡單的 Spring MVC 教程(十)

來源:互聯網
上載者:User

標籤:result   type   font   聲明   hidden   rar   設定   .net   顯示   

1 前言

在史上最簡單的 Spring MVC 教程(九)中,咱們已經實現了圖片的上傳及顯示功能,那麼接下來,在本篇博文中,咱們更進一步,以實體類(Person)中的欄位“name”和控制器(PersonController)中的方法 updatePersonList 為例,實現參數的校正功能。

2 註解樣本 - 參數校正

老規矩,首先給出項目結構圖:

在給出代碼之前, 咱們先明確參數校正的步驟:

  • 匯入參數校正的 jar 包;
  • 在實體上配置需要校正的屬性;
  • 在控制器的方法中用註解 @Valid 明確開啟校正;
  • 校正錯誤後,傳遞錯誤資訊;
  • 返回錯誤頁面,並提示錯誤資訊。

其中,參數校正所需的 jar 包可以在Spring MVC架構的各種依賴包 中進行下載,然後匯入到“External Libraries”之中。

第一步:修改實體類(Person),明確需要校正的屬性

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個字元,小於12個字元!")    private String name;    private Integer age;    private String photoPath;  // 圖片儲存路徑    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 中開啟校正功能

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. */@Controllerpublic class PersonController {    @Resource    PersonService ps;    // 注入 service 層    @RequestMapping(value = "/person/all")    public String findAll(Map<String, Object> model) {     // 聲明 model 用來傳遞資料        List<Person> personList = ps.findAll();        model.put("personList", personList);              // 通過這一步,JSP 頁面就可以訪問 personList        return "/person/jPersonList";                    // 跳轉到 jPersonList 頁面    }    @RequestMapping("/person/toCreatePersonInfo")    public String toCteatePersonInfo() {  // 跳轉新增頁面        return "/person/jPersonCreate";    }    @RequestMapping("/person/toUpdatePersonInfo")    public String toUpdatePersonInfo(Integer id, Model model) {  // 跳轉修改頁面        Person p = ps.get(id);             // 獲得要修改的記錄,重新設定頁面的值        model.addAttribute("p", p);         // 將資料放到 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);   // 調用 Service 層方法,插入資料        } else {            if(bindingResult.hasErrors()){          // 判斷校正是否發現錯誤                model.addAttribute("bindingResult", bindingResult);                model.addAttribute("p",p);                return "/person/jPersonUpdate";     // 校正錯誤,返回錯誤頁面,進行錯誤提示            }            String dir = request.getSession().getServletContext().getRealPath("/") + "/upload/";            String fileName = photeFile.getOriginalFilename();                  // 原始的檔案名稱            String extName = fileName.substring(fileName.lastIndexOf("."));     // 副檔名            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);   // 調用 Service 層方法,更新資料        }        return "redirect:/person/all.action";        // 轉向人員列表 action    }    @RequestMapping("/person/deleteById")    public String deleteById(Integer id) {  // 刪除單條記錄        ps.deleteById(id);        return "redirect:/person/all.action";        // 轉向人員列表 action    }    @RequestMapping("/person/deleteMuch")    public String deleteMuch(String id) {  // 大量刪除記錄        for (String delId : id.split(",")) {            ps.deleteById(Integer.parseInt(delId));        }        return "redirect:/person/all.action";        // 轉向人員列表 action    }}

第三步:修改 jPersonUpdate.jsp 頁面,用於展示錯誤資訊

<%--  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 屬性用於接收設定在 Model 中的對象,必須設定,否則會報 500 的錯誤 --><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;">        錯誤資訊:<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>

史上最簡單的 Spring MVC 教程(十)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.