In the previous article, I introduced the detailed explanation of Spring Learning Notes 1's IOC and try to use annotations and java code as much as possible. Next, this article focuses on introducing Spring Learning Notes 2's form data verification and file upload example code. For details, please refer to this article!
1. Form data verification
When registering, users need to fill in their account, password, email and mobile phone number, which are required and must meet certain formats. For example, the account needs to be less than 32 digits, the email must meet the email format, and the mobile phone number must be an 11 digit number, etc. You can use verification information at the time of registration, or write a tool class specifically for verification; let’s take a look at how to implement form data verification through simple annotations in SpringMVC.
Under the javax.validation.constraints package, multiple annotations are defined. for example:
@NotNull: The value of the annotated element must not be null. Note: If you do not fill in any data in the form, it does not mean that it is null, but an empty string.
@Size: The annotated element must be a String, collection, or array, and the length must meet the given range.
@Past: The value of the annotated element must be a past time.
@Digits: The annotated element must be a number, and its value must have a specified number of digits.
@Pattern: The value of the annotated element must match the given regular expression
In addition, more annotations are defined under the org.hibernate.validator.constraints package. for example:
@Email: Match email format.
@URL: Match the url format.
Let’s take a look at how to use it in SpringMVC.
1. First load the required one in the pom.xml file
<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 verification API, and the implementation of the API must be added, such as org.hibernate.validator, otherwise an error will be reported.
2. Add annotations to the properties of the class, taking 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-32-bit") private String username;@NotEmpty(message = "Password cannot be empty") private String password;@NotEmpty(message = "email cannot be empty")@Email(message = "email cannot be empty") private String email;@Size(min = 11, max = 11, message = "The length of the mobile phone number is 11 digits") private String cellphone;} message: If form data verification fails, an error message can be displayed.
3. Apply the verification function in the UserController and add the @Valid annotation.
Take UserController.java as an example:
@Controller@RequestMapping("/user")public class UserController {private UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@RequestMapping(value = "/register", method = RequestMethod.POST)public String processRegistration(@Valid User user, Errors errors) { //@Valid, the user object applies the 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);redirect:/user/" + user.getUsername();}} 4. Write a jsp file and display the page, taking 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" %><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"><%-- If form data verification fails, error message is displayed-%><sf:errors path="*" element="div" cssClass="errors"/><br /><table align="center"><tr><td>UserName: </td><td><sf:input path="username" cssErrorClass="errors"/></td><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>
The final effect is as follows:
2. File upload
In Spring, uploading files is simple and only takes 3 steps.
1. If the DispartcherServlet we configure inherits the AbstractAnnotationConfigDispatcherServletInitializer, overload the customizeRegistration() method to configure the specific details of the multipart.
@Overrideprotected void customizeRegistration(ServletRegistration.Dynamic registration) {//Limit the uploaded file size to no more than 2MB, the entire request does not exceed 4M, and all uploaded files must be written to disk registration.setMultipartConfig(new MultipartConfigElement("/tmp/uploads", 2097152, 4194304, 0));} 2. Configure the multipart parser.
//Configure multipart resolver @Beanpublic MultipartResolver multipartResolver() throws IOException {return new StandardServletMultipartResolver();} 3. Process multipart request. For information such as files uploaded by users, you can use the byte[] array to represent it, but it is recommended that the MultipartFile interface provided by Spring is recommended. It provides more functions, such as getting file name, file size, file type, etc.
@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 files to the system.
Write a page test to see if the file in the specified file directory has been uploaded successfully.
<form method="post" enctype="multipart/form-data"><label>Upload avatar image?</label><input type="file" name="icon" accept="image/jpeg, image/png" value="select file"/><button type="submit">Confirm</button></form>
1. References: Spring Practical Practice (4th Edition).
2. Github address: https://github.com/everseeker0307/register.
The above is the form data verification and file upload example code of Spring Learning Notes 2 introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!