1. 程式人生 > >Spring--MVC--如何書寫MVC的控制層Controller

Spring--MVC--如何書寫MVC的控制層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; } }