1 Preface
In the history of the simplest Spring MVC tutorial (ix), we have implemented the image upload and display function, then, in this blog post, we further to the entity class (person) in the field "name" and the controller (PersonController) in the method Updatepersonlist as an example, the verification function of the parameters is realized.
2 Annotation Example-parameter check
The usual, first give the project structure diagram:
Before giving the code, let's clear the steps for parameter validation:
- The jar package to import the parameter check;
- Configure the attributes on the entity that require validation;
- In the Controller method with annotations @Valid explicitly open the check;
- After the error is verified, the error message is passed;
- Returns the error page and prompts for an error message.
The jar packages required for parameter checking can be downloaded in the various dependencies of the Spring MVC framework and then imported into "External Libraries".
First step: Modify the Entity Class (person) to explicitly verify the properties
PackageSpring.mvc.domain;ImportJavax.validation.constraints.Size;/** * Created by D-fructose on 2017/1/30. * * Public class person { PrivateInteger ID;@Size(min =6, max = A, message ="Name must be greater than 6 characters, less than 12 characters!" ")PrivateString name;PrivateInteger age;PrivateString Photopath;//Picture storage path PublicIntegergetId() {returnId } Public void setId(Integer ID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicIntegerGetage() {returnAge } Public void Setage(Integer Age) { This. Age = Age; } PublicStringGetphotopath() {returnPhotopath; } Public void Setphotopath(String Photopath) { This. Photopath = Photopath; }@Override PublicStringtoString() {return "person{"+"Id="+ ID +", Name= '"+ name +' \ '+", age="+ Age +'} '; }}
Step two: Turn on the check function in the controller (PersonController) method updatepersonlist
PackageSpring.mvc.controller;ImportOrg.apache.commons.io.FileUtils;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;ImportOrg.springframework.validation.BindingResult;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.multipart.MultipartFile;ImportSpring.mvc.domain.Person;ImportSpring.mvc.service.PersonService;ImportJavax.annotation.Resource;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.validation.Valid;ImportJava.io.File;ImportJava.io.IOException;ImportJava.util.List;ImportJava.util.Map;/** * Created by D-fructose on 2017/1/30. * *@Controller Public class personcontroller { @ResourcePersonservice PS;//Inject service layer @RequestMapping(Value ="/person/all") PublicStringFindAll(map<string, object> model) {//Declare model to pass datalist<person> personlist = Ps.findall (); Model.put ("Personlist", personlist);//Through this step, the JSP page will have access to the Personlist return "/person/jpersonlist";//Jump to Jpersonlist page}@RequestMapping("/person/tocreatepersoninfo") PublicStringTocteatepersoninfo() {//Jump to New page return "/person/jpersoncreate"; }@RequestMapping("/person/toupdatepersoninfo") PublicStringToupdatepersoninfo(Integer ID, model model) {//Jump to modify pagePerson P = ps.get (ID);//Get the record you want to modify, and reset the value of the pageModel.addattribute ("P", p);//Put data into response return "/person/jpersonupdate"; }@RequestMapping("/person/updatepersonlist") PublicStringupdatepersonlist(HttpServletRequest request, @Valid person P, Bindingr Esult Bindingresult, model model, @Requestparam("Photo") Multipartfile photefile)throwsIOException {//Update personnel information if(P.getid () = =NULL) {Ps.insert (P);//Call Service layer method, insert data}Else{if(Bindingresult.haserrors ()) {//Determine if the check has found an errorModel.addattribute ("Bindingresult", Bindingresult); Model.addattribute ("P", p);return "/person/jpersonupdate";//Checksum error, return error page, error prompt} String dir = Request.getsession (). Getservletcontext (). Getrealpath ("/") +"/upload/"; String fileName = Photefile.getoriginalfilename ();//Original file nameString extname = filename.substring (Filename.lastindexof ("."));//ExtensionFileName = filename.substring (0, Filename.lastindexof (".") + system.nanotime () + extname;//Prevent file name collisionsFileutils.writebytearraytofile (NewFile (dir + fileName), photefile.getbytes ());//write files to the upload directoryP.setphotopath ("/upload/"+ FileName); Ps.update (P);//Call the Service layer method to update the data}return "Redirect:/person/all.action";//Turn to People list action}@RequestMapping("/person/deletebyid") PublicStringDeletebyid(Integer ID) {//Delete a single recordPs.deletebyid (ID);return "Redirect:/person/all.action";//Turn to People list action}@RequestMapping("/person/deletemuch") PublicStringDeletemuch(String ID) {//Bulk Delete records for(String DelId:id.split (",") {Ps.deletebyid (Integer.parseint (delid)); }return "Redirect:/person/all.action";//Turn to People list action}}
Step three: Modify the jpersonupdate.jsp page to display error messages
<%--Created by IntelliJ idea. User: Dimension C fructose Date: 1/time: 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><!--where the Modelattribute property is used to receive the object set in Model, it must be set, otherwise it will report 500 error--<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;" >Modify people Information</div> <div Style="padding:10px;" >Error message:<fond color="Red"><sf:errors path="*"/></fond> </div> <table> <tr> <TD>Name:</td> <TD><sf:input path="name"/><sf:errors path="name"/></td> </tr> <tr> <TD>Age:</td> <TD><sf:input path="Age"/></td> </tr> <tr> <TD>Image:</td> <TD><input type="file" name="Photo" value=""/ ></td> </tr> <tr> <TD colspan="2"><input type="Submit" name="Btnok" value="Save" /></td> </tr> </table></sf:form></body></html>
The simplest Spring MVC tutorial in history (10)