springMVC中的controller層


MVC控制層的作用:接收客戶端的請求,然后調用Service層業務邏輯,獲取到數據,傳遞數據給視圖層(客戶端)用於視覺呈現。
實現步驟
1.在類上使用@Controller注解
作用: 告訴springmvc的dispatcherServlet這是一個Controller然后被dispatcherServlet的上下文所管理,並且完成它的依賴注入
2.在類上使用@RequestMapping注解
例如:@RequestMapping(“/user”)
作用: Controller負責處理的,根目錄下的URL ,/user/** 下的所有路徑都會被Controller所攔截
3.在方法上使用 @RequestMapping
例如:@RequestMapping(value = “login.do”, method = RequestMethod.POST)
作用:使該方法負責處理/user/login.do 這個url 並且是由post方法方法傳遞過來的請求
4.在方法的參數前綁定@RequestParam/@PathVariable/@Param注解
作用:負責把請求傳入的參數,綁定到方法中的參數上,使方法中的參數值為請求傳入的參數值
例如這條請求:/user/login.do?username=”admin” &password=”admin”
相關代碼

@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private IUserService iUserService;
本方法負責處理/user/login.do 這個url 並且是由post方法方法傳遞過來的請求
@RequestMapping(value = "login.do", method = RequestMethod.POST)
自動序列化成json
@ResponseBody
public ServerResponse<User> login(@RequestParam("username")String username, @RequestParam("password")String password, HttpSession session) {

ServerResponse<User> response = iUserService.login(username, password);

if (response.isSuccess()) {
session.setAttribute(Const.CURRENT_USER, response.getData());
}
return response;
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM