Java - Spring MVC data binding

1.URL Mapping (URL mapping)

URL Mapping refers to the URL and Controller method binding.
By URL and method binding, SpringMVC can be exposed to the external service through Tomcat.

1) @GetMapping binding Get request

@GetMapping("/g")
@ResponseBody
public String getMapping(){
    return "This is get method";
}

 

2) @PostMapping binding request Post

@PostMapping("/p")
@ResponseBody
public String postMapping(){
    return "This is post mathod";
}

Post time and then access request, we can use the form or forms Postman
form form:

<div>
    <form action="/p" method="post">
        <input type="submit" value="submit">
    </form>
</div>

postman:

 

 

 

3) @RequestMapping general bindings

(1) if defined directly on the class, which is the logical treatment class for all the following URL prefix increase

@Controller
@RequestMapping("/test")
public class URLMappingController {
    @GetMapping("/g")
    @ResponseBody
    public String getMapping(){
        return "This is get method";
    }

    @PostMapping("/p")
    @ResponseBody
    public String postMapping(){
        return "This is post mathod";
    }
}

Then the access paths need to add the following prefixes:

 

 

 (2) may also be directly PostMapping as defined above In a particular method, function and GetMapping

@Controller
public class URLMappingController {
//    @GetMapping("/g")
    @RequestMapping("/g")
    @ResponseBody
    public String getMapping(){
        return "This is get method";
    }
}

If this definition will not distinguish between the post method or get method:

 

 

DETAILED request may be specified by way of the following ways: 

public class URLMappingController {
//    @GetMapping("/g")
    @RequestMapping(value = "/g",method = RequestMethod.GET)
    @ResponseBody
    public String getMapping(){
        return "This is get method";
    }
}

 

Method parameter receiving 2.Controller

In the spring to accept the request parameters, there are two approaches:
  . A method of using the parameters received Controller
  b receive data using Java Bean.

(1) Controller accepts method parameters

@Controller
public class URLMappingController {
    @PostMapping("/p")
    @ResponseBody
    public String postMapping(String name,String password){
        return name + ":" + password;
    }
}

access:

 

 

 Note that:
public String postMapping (String name, String password)
entered here is digital, received a string, which is a strong spring to help us complete the transfer.
But the strong turn problems that may arise.

get the parameters passed in the url splicing is:
For example: localhost:? 8080 / g name = kebi & password = 123456

@Controller
public class URLMappingController {
    @GetMapping("/g")
    @ResponseBody
    public String getMapping(String name, String password){
        return name + ":" + password;
    }
}

 

 

If we pass parameters when:
localhost: 8080 / G nameOld = KEBI & password = 123456?
Such rules do not meet the definition of a URL, although no error.
If you change it to this:
localhost:? 8080 / G nameo_ld & password = 123456 = KEBI
the Java side will not meet the naming conventions:
public String Getmapping (name_old String, String password)
so you can use the mapping annotation:
public String Getmapping (@RequestParam ( " name_old ") String nameOld, String password )

 

 

 

(2) using the Java Bean to accept the request parameters

If a request which was introduced to 100 parameters, then use the Controller will now tedious, so we can encapsulate all parameters to an object,
so that the above object management a lot easier.
Create a User entity classes:

public class User {
    private String name;
    private String password;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Then using the object parameters may be received:

@PostMapping("/p1")
@ResponseBody
public String postMapping1(User user){
    return user.getName() + ": " + user.getPassword();
}

 

 

When we request that the URL, spring MVC will automatically create a solid object and the User object parameter is filled to the parameter of the same name.

public String postMapping1 (User user, String name)
If we define an outside entity class in the same parameters, then filled in when SpringMVC

 

 

As long as the same name is the URL parameter will be assigned either parameter entity class or custom parameters.

 

3. receive a composite form data

List composite data using an array or the reception request
using the parameter set to the default value @RequestParam
using Map object receives the request parameters and precautions
absolute path relative paths do:

 

 

 Generally when submitting data, it may not be easy:

 

 

 When there are multiple check button, you may submit more than one data

<form action="./apply" method="post">
    <h3>您的姓名</h3>
    <input name="name" class="text"  style="width: 150px">
    <h3>您正在学习的技术方向</h3>
    <select name="course" style="width: 150px">
        <option value="java">Java</option>
        <option value="h5">HTML5</option>
        <option value="python">Python</option>
        <option value="php">PHP</option>
    </select>
    <div>
        <h3>您的学习目的:</h3>
        <input type="checkbox" name="purpose" value="1">of the typethe INPUT<Employment Looking for work
        ="checkbox" name="purpose" value="2">工作要求
        <input type="checkbox" name="purpose" value="3">兴趣爱好
        <input type="checkbox" name="purpose" value="4">其他
    </div>
    <div style="text-align: center;padding-top:10px" >
        <input type="submit" value="提交" style="width:100px">
    </div>
</form>

(1) using the received list

@PostMapping("/apply")
@ResponseBody
public String apply(String name,String course,Integer[] purpose){
    System.out.println(name);
    System.out.println(course);
    for (Integer p: purpose){
        System.out.println(p);
    }
    return "apply test";
}

We can also set the default value:
public String the Apply (@RequestParam (defaultValue = "ANON") String name, String Course,, Integer [] Purpose)
so that if the front does not pass parameter, then the default value will be used ANON.

(2) receiving a set of List

public String apply (String name, String course, @RequestParam List <Integer> purpose)
need only increase @RequestParam annotations, spring was aware of the need to use List collection for storage.

In fact, you can also use the object receives:

public class Form {
    private String name;
    private String course;
    private List<Integer> purpose;
}

Writing manner similar to the above controller.

@PostMapping("/apply")
@ResponseBody
public String apply(Form form){
    System.out.println(form.getName());
    System.out.println(form.getCourse());
    for (Integer p: form.getPurpose()){
        System.out.println(p);
    }
    return "apply test";
}

(3) using the Map Notes

When receiving data using a map, Map will be unable to receive complex data.

 

4. associated object assignment

The object name associated objects placed in front of the parameter name of the form, you can assign to the associated object.

 

 

 

public class Form {
    private String name;
    private String course;
    private List<Integer> purpose;
    private UserInfo userInfo=new UserInfo();
}

public class UserInfo {
    private String name;
    private String mobile;
    private String address;
}

Forms pass parameters need to pay attention:

<h3>收货人</h3>
<input name="userInfo.name" class="text"  style="width: 150px">
<h3>联系电话</h3>
<input name="userInfo.mobile" class="text"  style="width: 150px">
<h3>收货地址</h3>
<input name="userInfo.address" class="text"  style="width: 150px">   

Such data can be removed.

 

The date data type conversion

1) @DateTimeFormat comment

If the previous transmission time parameters:
<INPUT type = "text" name = "date">
Background date object receives directly, as certainly strong turn fail:
public String postMapping (String name, String password, a Date date)

 

 

 400 error is usually due to the strong turn failure.
@DateTimeFormat can use this annotation, pattern indicates the reception format:
public String postMapping (String name, String password, @DateTimeFormat (pattern = "the MM-dd-YYYY") a Date DATE)
which was the object of the package is also feasible:

Encapsulates the object of also possible:
 public  class the User {
     Private String name;
     Private String password;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date date;
}

But also we need to add @DateTimeFormat this comment.

@PostMapping("/p")
@ResponseBody
public String postMapping(User user){
    System.out.println(user.getName());
    System.out.println(user.getPassword());
    System.out.println(DateFormat.getDateInstance().format(user.getDate()));
    return "date test";
}

 

2) Converter Global converter

If every time I need time to comment, that's too much trouble.
So we can set a global default time converter.

(1) Create a converter

This new package converter, and a converter class MyDateConverter:

/*
* Date Points implement converter has three:
* 1. To achieve this interface Converter
* 2.Converter <String, Date> there are two paradigms
* 3. must implement this interface convert
* */

public  class MyDateConverter the implements Converter <String, a Date> {
     public a Date Convert (String S) {   // S input string representing 
        the SimpleDateFormat SDF = new new the SimpleDateFormat ( "the MM-dd-YYYY" );
         the try {
            D DATE = sdf.parse (S);   // format conversion 
            return D;
        } The catch (a ParseException E) {
             return  null ;   // if the format of the input string not directly return null 
        }
    }
}

(2) register to use

In the applicationContext.xml configuration:

<-! FormattingConversionServiceFactoryBean notice which converts class custom MVC there ->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <! - Conversion class definition ->
    <property name="converters">
        <set>
            <bean class="com.ikidana.springmvc.converter.MyDateConverter"/>
        </set>
    </property>
</bean>

<mvc:annotation-driven conversion-service="conversionService"/>

spring mvc type conversion in the face of the event date type, will be used to convert MyDateConverter this class.

 

So if both use @DateTimeFormat this comment, and uses global converter, then who is subject to the?
For SpringMVC, once the date corresponding to an increase of the converter, then use the converter priority class to handle, and notes directly ignored.

Guess you like

Origin www.cnblogs.com/yangmingxianshen/p/12521520.html