Spring learning notes 2-form data verification, file upload, spring learning notes
In the previous section Spring Study Notes 1--IOC: Try to use annotations and java code. The overall framework of the project has been set up and IOC and mybatis are introduced. Section 2 describes form data verification and file upload in SpringMVC. Visit https://github.com/everseeker0307/register.
1. form data verification
When registering a user, you must enter the account, password, email address, and mobile phone number. For example, the account must be within 32 characters, the mailbox must conform to the mailbox format, and the mobile phone number must be 11 characters. You can use the verification information at registration, or write a tool class to verify the form data through simple annotations in SpringMVC.
Multiple annotations are defined under the javax. validation. constraints package. For example:
@ NotNull:The value of the element to be annotated must not be null. Note: directly submit the form without entering any data. It does not mean it is null, but a null string.
@ Size:The element to be annotated must be a String, set, or array, and the length must conform to the specified range.
@ Past:The value of the element to be annotated must be a previous time.
@ Digits:The element to be annotated must be a number and its value must have a specified number of digits.
@ Pattern:The value of the element to be annotated must match the given regular expression.
In addition, more annotations are defined under the org. hibernate. validator. constraints package. For example:
@ Email:Match the email format.
@ URL:Match the url format.
The following describes how to use spring MVC.
1. First load the required
<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>
It should be noted that javax. validation only defines the validation API and must add the API implementation, such as org. hibernate. validator. Otherwise, an error is reported.
2. Add annotations to the class attributes. Take User. java as an example.
Public class User implements Serializable {@ Size (min= 32, max = 32, message = "uuid should be a 32-Bit String ")Private String id;@ Size (min= 1, max = 32, message = "the account length should be between 1 and 32 characters ")Private String username;@ NotEmpty (message= "The password cannot be blank ")Private String password;@ NotEmpty (message= "Email cannot be blank") @ Email (message = "Incorrect email format ")Private String email;@ Size (min= 11, max = 11, message = "11-digit mobile phone number ")Private String cellphone ;}
Message: if the form data verification fails, the error message is displayed.
3. Apply the verification function in UserController and add the @ Valid annotation. Take UserController. java as an example:
@ 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, Errors errors) {// @ Valid, user object application verification function if (errors. hasErrors () {// if form verification fails, return to the registration page 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. Compile a jsp file and display the page. Take register. jsp as an example:
<% @ 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 "%> <Sf: form method = "POST" action = "/register/user/register" commandName = "user"> <% -- If form data verification fails, show error message -- %> <sf: errors path = "*" element = "div" cssClass = "errors"/> <br/><Table align = "center"> <tr> <td> UserName: </td> <sf: input path = "username" cssErrorClass = "errors"/> </td> </tr> <td> Password: </td> <sf: password path = "password" cssErrorClass = "errors"/> </td> </tr> <td> Email: </td> <sf: input path = "email" cssErrorClass = "errors"/> </td> </tr> <td> CellPhone: </td> <sf: input path = "cellphone" cssErrorClass = "errors"/> </td> </tr> </table> <br/> <input type = "submit" value = "Register "/> </sf: form> </body>
The final result is as follows:
Ii. File Upload
In Spring, file upload is simple, and only three steps are required.
1. If the configured DispartcherServlet inherits AbstractAnnotationConfigDispatcherServletInitializer, reload the customizeRegistration () method to configure the details of multipart.
@ Override protected void customizeRegistration (ServletRegistration. dynamic registration) {// the size of the uploaded file cannot exceed 2 MB, and the entire request cannot exceed 4 MB. All uploaded files must be written to the disk registration. setMultipartConfig (new MultipartConfigElement ("/tmp/uploads", 2097152,419 4304, 0 ));}
2. Configure the multipart parser.
// Configure the multipart parser @ Bean public MultipartResolver multipartResolver () throws IOException {return new StandardServletMultipartResolver ();}
3. Process multipart requests. You can use byte [] arrays to represent files uploaded by users. However, we recommend the MultipartFile interface provided by Spring. It provides more functions, such as obtaining file names, file sizes, and file types.
@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) method: Write the File to the system.
Write a page to test whether the file in the specified file directory has been uploaded successfully.
<Form method = "post" enctype = "multipart/form-data"> <label> upload an avatar image? </Label> <input type = "file" name = "icon" accept = "image/jpeg, image/png "value =" select file "/> <button type =" submit "> OK </button> </form>
1. References: Spring practice (version 4th ).
2. github address: https://github.com/everseeker0307/register.