Objective
Understanding Spring MVC
Learning objects
Https://github.com/spring-projects/spring-mvc-showcase
Learn to Harvest
1. Custom Annotations
The following is the annotation interface
Target (value={elementtype.field, elementtype.method, Elementtype.parameter}) @Retention (retentionpolicy.runtime) @ Documentedpublic @interface Maskformat {String value ();}
The following is the use of annotations
@MaskFormat ("(# # #) ###-####")
Private String masked;
2. requestmapping annotations
- Class and method can be decorated, the corresponding URL is added by the level
- Get/post method can be specified
@Controller @requestmapping ("/data") public class Requestdatacontroller {@RequestMapping (value= "param", method= Requestmethod.get) public @ResponseBody string Withparam (@RequestParam string foo) { //corresponding URL /data/param?foo= Barreturn "obtained ' foo ' query parameter value '" + foo + "'";} @RequestMapping (value= "path/{var}", method=requestmethod.get) public @ResponseBody String withpathvariable (@ Pathvariable String var) {//corresponds to Url/data/path/barreturn ' obtained ' var ' path variable value ' "+ var +" ' ";}} @Controllerpublic class Mappingcontroller { @RequestMapping ("/mapping/path") public @ResponseBody String Bypath () {//the Most common return "Mapped by path!";} @RequestMapping (value= "/mapping/path/*", method=requestmethod.get) public @ResponseBody String Bypathpattern ( HttpServletRequest Request) {//pattern matches to a set of Urlreturn "Mapped by path pattern ('" + Request.getrequesturi () + "')";}}
3. Java beans are the underlying object classes, each of which can be added by annotations or used for JSON conversions
@XmlRootElementpublic class JavaBean { @NotNull private String fruit;
@NotEmpty//non-empty private String name; @Min (21)//limit the value range private int age; @DateTimeFormat (iso=iso. Date) @Past //must be in the past time, on the contrary, futureprivate date birthDate; @MaskFormat ("(# #) ###-####")// custom Format private String phone; @NumberFormat (style=style.percent) Private BigDecimal PERCENT; Public JavaBean () { //constructor method 1}public JavaBean (String foo) {//constructor Method 2this.foo = foo;} @Overridepublic String tostring () {///java Bean as the most basic object class, typically refactoring the ToString method return "JavaBean {foo=[" + foo + "], fruit=[" + F Ruit + "]}";}} Some scenarios (such as the calling Interface) can be reversed from the Java Bean definition by serializing the object back to the string json = maputils.getstring (params, "json"); JavaBean Abean = Jsonutil.toobject (json, javabean.class);
SummarizeIn the face of a new language, combine the simple demo to learn the main grammar and features to understand the applicable scenarios. Through the code structure of the instance, think about how to deal with it if you build a new project from 0
Spring Learning (i)--spring MVC