spring mvc is the foundation of spring boot
Create profile package
view
html, jsp, vue and thymleaf templates can be used (advantages: dynamic content has default values, url resources can use relative paths, and each tag can have placeholders)
profilePage.html (under profile package)
Excerpt of important contents:
<form th:action="@{/profile}" method="post"> //A form that can be accessed using the post method <input id="twitterhandler" type="text"/> <input id="email" type="text"/> <input id="birthDate" type="text"/> </form>
@{} you can construct a complete path, that is, put the path of the server context on the parameter
controller
Create profileController (under profile package)
start
package masterspringmvc4.Package name; //Declare the name of the package import org.springframework.stereotype.Controller;//Introducing controller package import org.springframwork.web.bind.annotation.RequestMapping;//Introducing requestMapping package
The controller is actually to turn the page into a url resource of a virtual path
Content excerpt
@RequestMapping("/profile") public String displayProfile(){ return "profile/profilePage"; }
Generally, the automatic completion is profile / profilepage html, for example: the prefix in the typeleafproperties class is classpath: / templates /, and the suffix is html, so you need to write view under the templates package to use the thymeleaf template
DTO
At this time, although you can access localhost:8080/profile, you can access profile / profilepage HTML, but there is no function in the form. You need to map the behavior for the post URL
Create a data transfer object DTO named profileform to match the field description verification rules in the form
profileform (under profile package)
package masterspringmvc4.profile; //Declare the name of the package import java.time.LocalDate; import java.util.ArrayList; import java.util.List; //Introduce some data types public class ProfileForm{ private String twitterHandle; private String email; private LocalDate birthDate; private List<String>tastes=new ArrayList<>(); //... Omit the getter & setter method for data binding (automatically obtain id data from mvc container and fill it in), and spring boot has the function of automatic completion }
The date api in Java 8 – Java time. Localdate is better than the previous Java util. Date is more detailed and uses an immutable data structure
java.time.LocalDate is just a date, Java time. Localtime is accurate to time, Java time. Time zone in zoneddatetime
In order for spring to bind the form field to DTO, you need to create a profile page Add some metadata to HTML
<form th:action="@{/profile}" th:object="${profileForm}" method="post"> <input th:field="${profileform.twitterhandler}" id="twitterhandler" type="text"/> <input th:field="${profileform.email}" id="email" type="text"/> <input th:field="${profileform.birthDate}" id="birthDate" type="text"/> </form>
In fact, we add the th:object attribute to the form (bind an object to the controller) and the th:field attribute to all input fields (bind the actual input fields to the attributes of the form bean)
In order for th:object to run, you need to add a parameter of ProfileForm type to the method of request mapping
@RequestMapping("/profile") public String displayProfile(){ return "profile/profilePage"; } @RequestMapping(value="/profile",method=RequestMethod.POST) //This is the mapping of the post method, which will be called naturally when the form is submitted public String saveProfile(ProfileForm profileForm){ //Parameters without ProfileForm type cannot be accessed normally return "redirect:/profile";//Redirect back after saving the form content }
Submitting a form with incorrect data, such as submitting a date value, actually cannot run, prompting a 400 error and no useful log. The log configuration in springboot is very simple. Just log level. {package} = debug add to application In the properties file, {package} is the fully qualified name of a class or package in the application, and debug is the log level. Search it yourself
If you want to debug the application, you can add logging level. org. springframework. web=DEBUG,org. springframework. Web is the basic package of mvc, so you can see the debugging information generated by spring web
In order to let users know the correct format of the input date, you can add the dateFormat attribute in the profile controller
@ModelAttribute("dateFormat") public String LocaleFormat(Locale locale){ return USLocalDateFormatter.getPattern(locale); }
@The model attribute annotation allows us to expose an attribute to a web page, similar to model Addattribute() method. At this time, add a placeholder in the date input field of the html page
<input th:field="${profileform.birthDate}" id="birthDate" type="text" th:field="${dateFormat}"/> <label for="birthDate">Birth Date</label>
check
In order to prevent users from entering illegal or empty information, some verification logic is added to the profileForm
newly added:
import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constrains.NotNull; import javax.validation.constrains.Past; import javax.validation.constrains.Size; public class ProfileForm{ @Size(min=2) //Not less than two characters private String twitterHandle; @Email @NotEmpty private String email; //Must be in email format and not empty @NotNull private Date birthDate; @NotEmpty private List<String> tastes=new ArrayList<>(); }
The annotation of these verification restrictions comes from JSR-303 specification, which specifies the verification function of bean s in detail. The most popular implementation is hibernate validator, which has been included in spring boot
In order to run the verification function, the controller needs to declare that it must get a legal model when the form is submitted, and add javax. XML to the parameters representing the form validation. The valid annotation can be implemented
@RequestMapping(value="/profile",method=RequestMethod.POST) public String saveProfile(@Valid ProfileForm profileForm,BindingResult bindingResult){ if(bindingResult.hasErrors()){ return "profile/profilePage"; //Do not redirect when containing error information } return "redirect:/profile"; }
After that, add the error reporting place in the html page
<ul th:if="${#fields.hasErrors('*')}" class="erroelist"> <li th:each="err:${#fields. Errors ('*')} "th: text =" ${err} "> input error</li> </ul>
This will traverse each error in the form and display it in the list
The @ NotEmpty check for the user will prevent the submission of the form, so it will not be displayed in the error report
In order to make the error message more intuitive, you can customize the error message (not detailed)
The client verification function can verify the form in advance to avoid excessive load on the server caused by always incorrect requests (not detailed)