@Controller 用於標記在一個類上,表示一個SpringMVC Controller對象。通過Spring使用掃描機制查找應用程序中所有基於註解的控制器類。分發處理器會掃描使用了Controller註解的類的方法是否使用了RequestMapping註解,只有使用了RequestMapping註解的方法纔是真正處理請求的處理器。
@Controller
public class UserController {
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(){
return "index"; // 跳轉到index頁面
}
}
@RequestMapping 是一個用來處理請求地址映射的註解,可用於類或方法上。用於類上表示類中的所有響應請求的方法都是以該地址作爲父路徑。value:(*)請求的實際地址。method:(*)請求類型,GET、POST等。consumes:指定請求體內容類型(Content-Type)如application/json, text/html。produces: 指定響應內容類型,僅當request請求頭中的(Accept)中包含該指定類型才返回。params:指定request中必須包含某些參數值是,才讓該方法處理。headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(HttpServletRequest request, HttpServletResponse response){
return "註冊成功";
}
@RequestParam 在處理方法傳參處使用 @RequestParam 可以把請求參數傳遞給請求方法。value:參數名。required:是否必須有該參數(默認爲 true), 若不存在,將拋出異常。
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@RequestParam("username") String username,@RequestParam("password") String password) {
return "註冊成功";
}
@RequestBody 是作用在形參列表上,用於將前臺發送過來固定格式的數據【xml格式 或者 json等】封裝爲對應的 JavaBean 對象,封裝時使用到的一個對象是系統默認配置的 HttpMessageConverter進行解析,然後封裝到形參上。
@RequestMapping("/login", method = RequestMethod.POST)
public String login(@RequestBody User loginUuser) {
return "登錄成功";
}
@ResponseBody 該註解用於方法返回的對象,將JavaBean通過適當的HttpMessageConverter轉換爲指定json、xml等格式後,寫入到Response對象的body數據區。
@RequestMapping("/logout", method = RequestMethod.POST)
@ResponseBody
public Object login() {
return new User("username","password");
}
@ModelAttribute 被ModelAttribute註釋的方法會在此controller每個方法執行前被執行,因此對於一個controller映射多個URL的用法來說,要謹慎使用。
@ModelAttribute
public String beforeMethod(){
System.out.println("beforeMethod執行了");
return "hello";
}
轉發、重定向 SpringMVC控制轉發和重定向是通過設置跳轉頁面的拼接參數。
@RequestMapping(value="/login", method=RequestMethod.POST)
public String register(HttpServletRequest request, HttpServletResponse response){
String name = request.getParameter("name");
request.setAttribute("username", name);
return "forward:/test"; //服務端轉發到地址爲"/test"的處理方法上
}
@RequestMapping(value="/login", method=RequestMethod.POST)
public String register(HttpServletRequest request, HttpServletResponse response){
return "redirect:/test"; //讓客戶端重定向到地址"/test"
}
@RequestMapping(value="/test", method=RequestMethod.POST)
@ResponseBody
public String register(HttpServletRequest request, HttpServletResponse response){
String username = request.getParameter("username");
return "success";
}
@RestController 註解的類表示所有方法返回的是請求體數據,不是跳轉指定的頁面。等同於Controller+ResponseBody註解
@RestController
public class UserController {
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String login(){
return "index"; // 返回"index"數據
}
}
等同於如下效果
@Controller
public class UserController {
@RequestMapping(value = "/login",method = RequestMethod.POST)
@ResponseBody
public String login(){
return "index"; // 跳轉到index頁面
}
}