The role of @ResponseBody and @RequestBody and @PathVariable

1. @ResponseBody

@Respo Jump path, but after adding @ResponseBody, the returned result will not be parsed as a jump path, but will be written directly into the HTTP response body. For example, if you obtain json data asynchronously and add @ResponseBody, the json data will be returned directly. @RequestBody inserts the HTTP request body into the method and writes the request body to an object using an appropriate HttpMessageConverter.

The function of @ResponseBody is to convert the javabean type data returned by the backend with return into json type data. (The backend transmits data to the frontend)

Case:

Front-end asynchronous request:

function loginAction() {

    // 获取用户输入的账号和密码
    var name = $('#count').val();
    var password = $('#password').val();

    $.ajax({
        url : 'account/login',
        type : 'post',
        // data对象中的属性名要和服务端控制器的参数名一致 login(name, password)
        data : {
            'name' : name,
            'password' : password
        },
        dataType : 'json',
        success : function(result) {
            if (result.state == 0) {
                // 登录成功,设置cookie并跳转edit.html
                addCookie('userId', result.data.id);
                addCookie('nick', result.data.nick);
                location.href = 'edit.html';
            } else {
                // 登录失败
                var msg = result.message;
                $('#sig_in').next().html(msg);
                $('#sig_in').next().css("color", "red");
            }
        },
        error : function(e) {
            alert("系统异常");
        }
    });
    $('#password').val("");
}

Backend business logic:

@RequestMapping("/login")
@ResponseBody
public Object login(String name, String password, HttpSession session) {
    user = userService.checkLogin(name, password);
    session.setAttribute("user", user);
    return new JsonResult(user);
}

Second, @RequestBody

@RequestBody acts on the formal parameter list and is used to encapsulate fixed-format data [xml format or json, etc.] sent from the front desk into the corresponding JavaBean object. One object used during encapsulation is the system's default configured HttpMessageConverter for parsing. Then encapsulate it into formal parameters.

The function of @RequestBody is to convert the json format data transmitted from the front end into a self-defined javabean object (the front end passes data to the back end)

For example, the backend business logic above can be changed to:

@RequestMapping("/login.do")
@ResponseBody
public Object login(@RequestBody User loginUuser, HttpSession session) {
    user = userService.checkLogin(loginUser);
    session.setAttribute("user", user);
    return new JsonResult(user);
}

三、@PathVariable

The function of @PathVariable is to obtain the dynamic parameters in the url, which is often used in RestFul style programming. In this way, the front-end can write parameters in the url
. For example: to obtain user information through id, the front-end url can be expressed as

http://localhost:8080/getUser/1 This 1 is the user ID you want to query

The backend receives this dynamic parameter through @PathVariable

    @GetMapping("/getUser/{id}")
    public User getUser(@PathVariable("id") String id){
        return userService.getUserById(id);
    }

Guess you like

Origin blog.csdn.net/weixin_64443786/article/details/132758347