@PathVarable注釈実践


                   ,      @PathVariable               
くり一つ:
package com.annotation;

/**
 * @Author: Vimonster
 * @Date: Created in 2020/8/2 9:38
 * @motto:           ,          、
 * @Version: $version$
 * @Description:
 */
public class User {

    private String id;

    private String userName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", userName='" + userName + '\'' +
                '}';
    }
}
1.  私たちが取得したい値が要求経路に含まれている場合、@PathVarableで要求経路から私たちが欲しいパラメータを取得し、要求方法のパラメータを受信する前に、@PathVarableで指定して取得したいURLに対応するパラメータの名前を指定します。つまり、私たちが必要とするパラメータを取得することができます。
2.  受信パラメータがオブジェクトである場合は、指定対象の属性名とURLに対応するパスフィールド名が同一でないと自動的にマッピングされます。
 
コードを見て、より直感的に:
package com.annotation;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: Vimonster
 * @Date: Created in 2020/8/2 9:29
 * @motto:           ,          、
 * @Version: $version$
 * @Description: @PathVariable  
 */
@Controller
@RequestMapping("testPath")
public class PathVariableController {

    /**
     *                    ,      @PathVariable               ,
     *            ,  @PathVariable         URL         ,      
     *      ,     
     * localhost:8080/springmvc/testPath/user/1/lilei/monster
     *
     *               id = 1  name = lilei
     *
     * @param id
     * @param name
     * @return
     */
    @RequestMapping("/user/{id}/{userName}/monster")
    public String test01(@PathVariable(value = "id") String id, @PathVariable("userName") String name) {

        System.out.println(id + " : " + name);

        return "hello springmvc";
    }

    /**
     *                      URL                
     *      :
     *              User     id -> {id}
     *              User     userName -> {userName}
     * @param user
     * @return
     */
    @RequestMapping("/user1/{id}/{userName}/monster")
    public String test01(User user) {

        System.out.println(user);

        return "hello springmvc";
    }

}


===   test    localhost:8080/springmvc/testPath/user/1/lilei/monster    ===
1 :   

===   test1    localhost:8080/springmvc/testPath/user1/1/lilei/monster    ===
User{id='1', userName='  '}