1. 程式人生 > >Spring MVC相關的註解

Spring MVC相關的註解

@Conttoller

是用來表示註解的類做為MVC 框架的一個controller 的主要註解 ,dispatcher servlet 掃描被@controller 註解的類,從而將web請求對映到被@requestmapping 註解的方法上。

@Controller
public class AdviceController {

}

與Conttoller 類似的還有一個@RestController 該註解主要是返回資料,提供一個Rest 介面

@RestController
public class AdviceController {

}

@RequestMapping

@requestmappering註解用來將使用者請求對映到處理器類或者方法,可以在類級別或者方法級別應用該註解。使用@requestmapping註解的方法可以允許有非常靈活的簽名,他可以接受HTTP servlet 請求/響應物件,HTTP session物件,inputstream output stream 物件,path variable /modeattribute 註解引數,bingdingresult 物件以及其他物件

    @RequestMapping(value = "urlName")
    public String name(String name) {
        return name;
    }

@ModeAttribute

該註解使用一個向檢視公開的建將一個返回值與一個引數在一起 ,可以在方法級別或方法的引數上應用該註解

@PathVariable

將一個方法引數繫結到一個URL 模板 ,如果可以通過URL 從使用者獲取資料 ,將有利於處理器方法的執行,所以通過 @PathVariable 從URL 中獲取資料傳給後臺 @PathVariable 引數可以是任何型別 ,如 int date string

    @RequestMapping(value = "/user/{userId}")
    public String test(@PathVariable Long userId){
        
    }

@ConttollerAdvice

將程式碼集中到一個地方,以便跨控制器共享程式碼 ConttollerAdvice 註解的類可以包含有 ExceptionHandler InitBinder 和 ModeAttribute ,這些方法可以被應用到應用程式中所有帶有@RequestMapping 註解的方法中
其中@InitBinder用來初始化webDataBinder方法,比如之策自定義編輯器,以便解析日期欄位
@ExceptionHandler 用來定義方法來處理控制器類發生的異常

@ControllerAdvice
public class GlobalControllerExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class);
    private JSONObject jsonObject = new JSONObject();

    @ExceptionHandler(value = Exception.class)
    public Object defaultErrorHandler(Exception e) {
        LOGGER.error(e.getMessage());
        jsonObject.put("code", -1);
        jsonObject.put("message", e.getMessage());
        ResponseEntity responseEntity = new ResponseEntity(jsonObject, HttpStatus.INTERNAL_SERVER_ERROR);
        return  responseEntity;
    }
    @ModelAttribute
    public void addModelAttribute(Model model){
        model.addAttribute("msg","hello world");
    }
}

github url: springbootcontrolleradvice