控制器Controller
控制器Controller
- 控制器復雜提供訪問應用程式的行為,通常通過介面定義或注解定義兩種方法實作,
- 控制器負責決議用戶的請求并將其轉換為一個模型,
- 在Spring MVC中一個控制器類可以包含多個方法
- 在Spring MVC中,對于Controller的配置方式有很多種
實作介面Controller定義控制器是較老的辦法:
public class HelloController implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和視圖
ModelAndView mv = new ModelAndView();
//封裝物件,放在ModelAndView中,Model
String aa = "HelloSpringMVC!";
mv.addObject("abc",aa);
//mv.addObject("abv","aaaa!");
//封裝要跳轉的視圖,放在ModelAndView中
mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
return mv;
}
}
缺點:一個控制器中只有一個方法,如果要多個方法則需要定義多個Controller;定義的方式比較麻煩;
@Controller注解
@Controller注解型別用于宣告Spring類的實體是一個控制器(@Controller:web層 @Service:service層 @Repository:dao層);
Spring可以使用掃描機制來找到應用程式中所有基于注解的控制器類,為了保證Spring能找到你的控制器,需要在組態檔中宣告組件掃描,
<!-- 自動掃描包,讓指定包下的注解生效,由IOC容器統一管理 -->
<context:component-scan base-package="com.zhang.controller"/>
@Controller注解的類會自動添加到Spring背景關系中
@RequestMapping 設定映射訪問路徑
@Controller
public class HelloController {
@RequestMapping("/t2")
public String test2(User user, Model model) {
model.addAttribute("msg", user.toString());
return "hello";
}
}

@RequestMapping 也可以放在類上,這樣在每個方法的請求路徑前面都要加上類上的路徑
@Controller
@RequestMapping("/controller")
public class HelloController {
@RequestMapping("/t2")
public String test2(User user, Model model) {
model.addAttribute("msg", user.toString());
return "hello";
}
}

請求型別
用于約束請求的型別,可以收窄請求范圍,指定請求謂詞的型別如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等,
POST請求:
@RequestMapping(value = "/hello", method = {RequestMethod.POST})
public String test3(Model model) {
model.addAttribute("msg","helloSpringMVC");
return "hello";
}
使用瀏覽器地址欄進行訪問默認是Get請求,會報錯405:

改為Get請求
@RequestMapping(value = "/hello", method = {RequestMethod.GET})
public String test3(Model model) {
model.addAttribute("msg","helloSpringMVC");
return "hello";
}
可以正常訪問:

組合注解:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping("/hello")相當于
@RequestMapping(value = "/hello", method = {RequestMethod.GET})
// @RequestMapping(value = "/hello", method = {RequestMethod.GET})
@GetMapping("/hello")
public String test3(Model model) {
model.addAttribute("msg","helloSpringMVC");
return "hello";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335539.html
標籤:java
