SpringBoot的Controller中@Controller和@RestController的区别
@Controller
@Controller主要是配合SpringBoot的Template模板使用,使用了该注解后,方法返回的是html或jsp等视图的名称,跳转到html页面,配合配置的view使用,如果要返回json等数据,需要在方法前添加@ResponseBody注解
@CrossOrigin
@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
public String test(@RequestParam("student_username") String student_username,@RequestParam("student_password") String student_password){
System.out.println(student_username);
System.out.println(student_password);
JSONObject object = new JSONObject();
object.put("msg","ok");
object.put("name","timemachine");
object.put("age",20);
HashMap<String,Object> map = new HashMap<>();
map.put("1","A");
map.put("2","B");
map.put("3","C");
map.put("4","D");
object.put("map",map);
return object.toJSONString();
}
@RequestMapping("/registry")
public String registry(){
return "registry";
}
上面的代码中test方法使用了@ResponseBody,返回的是数据,用于编写api接口。
而registry方法则会跳转到Template下的registry.html页面,具体页面由你配置的view决定。
@RestController
@RestController则相当于@Controller+@ResponseBody,方法不需要再使用@ResponseBody返回的为数据。
如:
@RequestMapping("/userlist")public List<Map<String,Object>> userlist(){
String sql = "select * from user";
List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}