@ResponseBody annotation and response.getWriter().write()

Foreword:

When we first started learning SpringMVC, we often had a lot of doubts about some of the annotations used. Today, let’s talk about the annotation @ResponseBody

1. The role of @ResponseBody:

The function of the @responseBody annotation is to convert the object returned by the controller method into a specified format through an appropriate converter, and then write it to the response object. Usually we use it to return JSON data or XML data. After using this annotation, Will try the processor again, but directly write the data to the input stream, his effect is equivalent to outputting the data in the specified format through the response object.

Look at the specific use:
background controller:

@ResponseBody
    @RequestMapping(value = "/test")
    public User sayHello(String username, String password, User user){
        System.out.println("username"+username+" and password:"+password);
        System.out.println("username:"+user.getUsername()+" | password:"+user.getPassword());
        return user;
    }

Front-end page: I use ajax submission here, specify the dataType as json, and the data received from the background will be converted into json objects

<div class="container">
    <form class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="inputEmail" class="sr-only">Username</label>
        <input type="text" id="username" name="username" class="form-control" placeholder="Username" required autofocus>
        <br>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="text" id="password" name="password" class="form-control" placeholder="Password" required>
        <br>
    </form>
    <button class="btn btn-lg btn-primary btn-block" onclick="submitForm();">提交</button>
</div>
<script type="text/javascript">
    function submitForm() {
        var username = $("#username").val();
        var password = $("#password").val();

        console.log(username);
        $.ajax({
            url: "/test/test",
            type: "post",
            data: {
                "username": username,
                "password": password
            },
            dataType:"json",
            success: function (data) {
                console.log(data);
                console.log(typeof data);
                alert(data.username);
            }
        })
    }

</script>

The results are as follows:
Insert picture description here
Insert picture description here


二、response.getWriter().write():

At this point, we rewrite a background controller:

@RequestMapping(value = "/test2")
    public void sayHello2(HttpServletResponse response,User user) throws IOException {
        response.getWriter().write(JSONObject.toJSON(user).toString());
    }

Let's take a look at the results:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41071754/article/details/111383258