@RestController和@ResponseBody的使用

使用说明

如果在类上使用@RestController 可以省略类上的@Controller和方法上的ResponseBody

类上@RestController等同于 类上的@Controller 和ResponseBody

package top.withlevi.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import top.withlevi.pojo.User;

/**
 * @Author Levi Zhao
 * @Date 9/10/2021 10:11 PM
 * @Version 1.0
 */

//@Controller
@RestController
public class UserController {

//    @RequestMapping(value = "/u1",produces = "application/json;charset=utf-8") 第一种解决方式
    @RequestMapping("/u1")
//    @ResponseBody  // 不会走视图解析器会直接返回一个字符串
    public String test01() throws JsonProcessingException {
        // jackson, ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        
        // 创建对象
        User user = new User(1,"你好世界",29);

        return mapper.writeValueAsString(user);
    }
}

posted @ 2021-09-11 11:32  withLevi  阅读(456)  评论(0编辑  收藏  举报