@RestController注解的使用
-
当我们对所有的方法都加上@ResponseBody注解时让方法返回Json数据这样会很麻烦,而且会使代码显得十分的冗余。
-
这时在类上加上@RestController注解会使该控制层中的所有方法都都有@ResponseBody注解的作用,使用这个注解会使该类的所有方法都返回Json数据
package com.shxy.controller;
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 java.util.HashMap;
import java.util.Map;
@Controller
@RestController
public class ResponseBodyController {
@RequestMapping("/getMap")
public Map getMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("code","200");
map.put("msg","ok");
return map;
}
}
在config配置类上加上@EnableWebMvc注解
package com.shxy.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan("com.shxy.controller")
@EnableWebMvc
public class SpringMVCConfig {
}