In the previous article to introduce spring Learning Notes 1 of the IOC to explain as much as possible use of annotations and Java code, then the focus of this article to introduce spring Learning Notes 2 form data validation, file Upload instance code, specific content, please refer to this article!
I. Verification of form data
When the user registers, needs to fill in the account number, the password, the mailbox as well as the mobile phone numbers, all must fill in, and needs conforms to certain format. For example, the account needs 32, the mailbox must be in line with the mailbox format, mobile phone number must be 11 digits. You can validate information at registration, or write a tool class to validate it, and see how to implement form data validation with simple annotations in SPRINGMVC.
Below the javax.validation.constraints package, multiple annotations are defined. Like what:
@NotNull: The value of the annotation element must not be null. Note: The form does not fill in any data submitted directly, does not mean null, but an empty string.
@Size: The annotated element must be a string, a collection, or an array, and the length should conform to 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, below the org.hibernate.validator.constraints package, more annotations are defined. Like what:
@Email: Match Email format.
@URL: Matches the URL format.
Let's take a look at how to use it in SPRINGMVC.
1, first in the Pom.xml file to 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 just defined the validation API, you must add the implementation of the API, such as Org.hibernate.validator, otherwise it will be an error.
2. Add annotations to the properties of the class, taking User.java as an example.
public class User implements Serializable {
@Size (min =, max = +, message = "UUID should be 32-bit string")
private String ID ;
@Size (min = 1, max =, message = "Account length should be between 1-32 digits")
private String username;
@NotEmpty (message = "Password cannot be null")
private String password;
@NotEmpty (message = "Email cannot be empty")
@Email (message = "Incorrect email format")
private String Email;
@Size (min = one, max = one, message = "Cell phone number length is 11 digits")
private String cellphone;
Message: If the form data validation fails, you can display error messages.
3, the Usercontroller in the application of the verification function, add @valid annotation can be.
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 User, Errors Errors) {//@Valid, the user object applies a checksum if
(Errors.haserrors ()) {//If form validation fails, return to the registration page
"register"; c12/>}
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, the preparation of JSP files, display pages to 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"%>
The final effect is as follows:
Second, file upload
In spring, file uploads are simple and require only 3 steps.
1, if we configure the Dispartcherservlet inherited Abstractannotationconfigdispatcherservletinitializer words, overload customizeregistration () method to configure the specific details of the multipart.
@Override
protected void Customizeregistration (Servletregistration.dynamic registration) {
// Limit the size of the uploaded file to no more than 2MB, the entire request does not exceed 4M, all uploaded files will be written to the disk
registration.setmultipartconfig (new Multipartconfigelement ("/tmp/ Uploads ", 2097152, 4194304, 0));
2, configure the multipart parser.
Configure the multipart parser
@Bean public
multipartresolver Multipartresolver () throws IOException {return
new Standardservletmultipartresolver ();
}
3, processing multipart request. Information such as user-uploaded files can be represented by byte[] arrays, but the multipartfile interfaces provided by spring are more recommended. It provides more functionality, such as getting file names, file sizes, file types, and so on.
@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: Writes 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 picture?</label>
<input Type= "File" name= "icon" accept= "Image/jpeg, image/png" value= "Select File"/> <button type=
"Submit" > OK </ Button>
1, Reference: Spring Combat (4th edition).
2, GitHub address: Https://github.com/everseeker0307/register.
The above is a small set to introduce the Spring Learning Note 2 form data validation, file Upload instance code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!