Spring學習筆記2——表單資料驗證、檔案上傳,spring學習筆記

來源:互聯網
上載者:User

Spring學習筆記2——表單資料驗證、檔案上傳,spring學習筆記

    在上一章節Spring學習筆記1——IOC: 盡量使用註解以及java代碼中,已經搭建了項目的整體架構,介紹了IOC以及mybatis。第二節主要介紹SpringMVC中的表單資料驗證以及檔案上傳,歡迎訪問https://github.com/everseeker0307/register。

 

一、表單資料驗證

    使用者註冊時,需要填寫帳號、密碼、郵箱以及手機號,均為必填項,並且需要符合一定的格式。比如帳號需要32位以內,郵箱必須符合郵箱格式,手機號必須為11位號碼等。可以採用在註冊時驗證資訊,或者專門寫一個工具類用來驗證;來看下在SpringMVC中如何通過簡單的注釋實現表單資料驗證。

    在javax.validation.constraints包下面,定義了多個註解。比如:

    @NotNull: 所註解元素的值必須不能為null。註:表單中不填寫任何資料直接提交,並不意味著為null,而是Null 字元串。

    @Size: 所註解的元素必須為String、集合或者數組,並且長度要符合給定的範圍。

    @Past: 所註解的元素的值必須是一個過去的時間。

    @Digits: 所註解的元素必須是數字,並且它的值必須有指定的位元。

    @Pattern: 所註解的元素的值必須匹配給定的Regex

    另外,在org.hibernate.validator.constraints包下面,定義了更多的註解。比如:

    @Email: 匹配email格式。

    @URL: 匹配url格式。

 

    下面看一下在SpringMVC中如何使用。

    1、首先在pom.xml檔案中載入需要的

        <dependency>            <groupId>javax.validation</groupId>            <artifactId>validation-api</artifactId>            <version>1.1.0.Final</version>        </dependency>        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-validator</artifactId>            <version>5.2.4.Final</version>        </dependency>

需要注意的是,javax.validation只是定義了校正API,必須添加API的實現才行,比如org.hibernate.validator,否則會報錯。

    2、在類的屬性上添加註解,以User.java為例。

public class User implements Serializable {    @Size(min = 32, max = 32, message = "uuid應該為32位字串")    private String id;    @Size(min = 1, max = 32, message = "帳號長度應該在1-32位之間")    private String username;    @NotEmpty(message = "密碼不可為空")    private String password;    @NotEmpty(message = "email不可為空")    @Email(message = "email格式不正確")    private String email;    @Size(min = 11, max = 11, message = "手機號長度為11位")    private String cellphone;}

    message: 如果表單資料驗證失敗,可以顯示的錯誤資訊。

    3、在UserController中應用校正功能,添加@Valid註解即可。以UserController.java為例:

@Controller@RequestMapping("/user")public class UserController {    private UserService userService;    @Autowired    public UserController(UserService userService) {        this.userService = userService;    }    @RequestMapping(value = "/register", method = RequestMethod.POST)    public String processRegistration(@Valid User user, Errors errors) {    //@Valid,user對象應用校正功能        if (errors.hasErrors()) {   //如果表單驗證失敗,返回註冊頁面            return "register";        }        if (user.getId() == "")            user.setId(UUID.randomUUID().toString().replaceAll("-", ""));        if (user.getRegDate() == 0)            user.setRegDate(new Date().getTime());        userService.addUser(user);        return "redirect:/user/" + user.getUsername();    }}

    4、編寫jsp檔案,展示頁面,以register.jsp為例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %><%@ page session="false" %><html lang="en"><head>    <title>Register</title>    <link rel="stylesheet"          type="text/css"          href="<c:url value="/resources/style.css" />" ></head><body><sf:form method="POST" action="/register/user/register" commandName="user">    <%-- 如果表單資料驗證失敗,顯示錯誤資訊 --%>    <sf:errors path="*" element="div" cssClass="errors"/><br />    <table align="center">        <tr>            <td>UserName: </td>            <td><sf:input path="username" cssErrorClass="errors"/></td>        </tr>        <tr>            <td>Password: </td>            <td><sf:password path="password" cssErrorClass="errors"/></td>        </tr>        <tr>            <td>Email: </td>            <td><sf:input path="email" cssErrorClass="errors"/></td>        </tr>        <tr>            <td>CellPhone: </td>            <td><sf:input path="cellphone" cssErrorClass="errors"/></td>        </tr>    </table><br />    <input type="submit" value="Register"/></sf:form></body></html>

    最終效果如下:

 

二、檔案上傳

    在Spring中,檔案上傳很簡單,只需要3步即可。

    1、如果我們配置的DispartcherServlet繼承了AbstractAnnotationConfigDispatcherServletInitializer的話,重載customizeRegistration()方法來配置multipart的具體細節。

    @Override    protected void customizeRegistration(ServletRegistration.Dynamic registration) {        //限制上傳檔案的大小不超過2MB,整個請求不超過4M,所有上傳的檔案都要寫到磁碟中        registration.setMultipartConfig(new MultipartConfigElement("/tmp/uploads", 2097152, 4194304, 0));    }

  2、配置multipart解析器。

    //配置multipart解析器    @Bean    public MultipartResolver multipartResolver() throws IOException {        return new StandardServletMultipartResolver();    }

    3、處理multipart請求。對於使用者上傳的檔案等資訊,可以用byte[]數組來表示,但更推薦Spring提供的MultipartFile介面。它提供了更多功能,比如擷取檔案名稱、檔案大小、檔案類型等。

@RequestMapping(value = "/{username}", method = RequestMethod.POST)public String showUserInfo(@RequestPart("icon") MultipartFile icon) throws IOException {        icon.transferTo(new File("/Users/pingping/Projects/IdeaProjects/spring/register/src/main/webapp/uploads/" + icon.getOriginalFilename()));        return "user";}

    transferTo(File dest)方法: 將檔案寫入到系統中。

    寫個頁面測試,看指定的檔案目錄下檔案是否已上傳成功。

<form method="post" enctype="multipart/form-data">    <label>上傳頭像圖片?</label>    <input type="file" name="icon" accept="image/jpeg, image/png" value="選擇檔案"/>    <button type="submit">確定</button></form>

 

1、參考文獻:Spring實戰(第4版)。

2、github地址:https://github.com/everseeker0307/register。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.