@controller 只是使用這個註解類,那麼只是說明這個類可以被spring掃到並加入到bean中,這個時候,類內部的方法返回String類目參數,會進行頁面的跳轉,直接跳轉到String頁面
@Controller
@RequestMapping("/user2")
public class UserController2 {
//使用了@controller註解,這種可以放在頁面跳轉上
@RequestMapping(value="/hello")
public String hello(HttpServletRequest request,Model model) {
return "hello";
}
}
如果要在這個類中進行一些restAPI或者json數據的返回,那麼需要在方法上面增加@ResponseBody註解如:下面的會以json數據格式進行返回
如,下面的方法返回hello字符串,說明會跳轉到hello.html頁面上去
@Controller
@RequestMapping("/user2")
public class UserController2 {
@RequestMapping(value="/getUserLikeName")
public @ResponseBody List<UserDo> getUserLikeName(HttpServletRequest request,Model model) {
String name = request.getParameter("name");
List<UserDo> userDoList = new ArrayList<UserDo>();
userDoList = userService.getUserInfoLikeName(name);
return userDoList;
}
}
@RestController
這個註解集合了@Controller和@ResponseBody,也就是所有的方法都會按照json格式返回,如下面的代碼不會跳轉到hello.html而是在頁面直接輸出hello字符串,也就是方法上不用加@responseBody也會輸出json格式的內容,但這種註解方式,不適合用於頁面跳轉
@RestController
@RequestMapping("/user2")
public class UserController2 {
//使用了@controller註解,這種可以放在頁面跳轉上
@RequestMapping(value="/hello")
public String hello(HttpServletRequest request,Model model) {
return "hello";
}
}
轉載自: http://blog.csdn.net/uestc_lxp/article/details/53447345