SpringMVC常用註解

@RequestParam

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;

    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}

使用場景
傳遞的參數必須和RequestParam的value一致,但不存在這個參數的時候,默認會報錯,如果這個參數並非必須,那麼可以將@RequestParam的required設置false,age的類型最好爲Integer,這樣當age參數不存在的時候,會保存,因爲不能將null賦給int,如果非要用int,那麼可以加defaultValue屬性給個默認值

public String testRequestParam(@RequestParam(value = "username") String un,
                               @RequestParam(value = "age",required=false,defaultValue = "0") int age)

@RequestHeader

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestHeader {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;

    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}

使用

    @RequestMapping(value = "/testRequestHeader")
    public String requestHeader(@RequestHeader(value = "Accept-Language") String header ,String name){
        System.out.println("header: "+header);
        System.out.println("name "+name);
        return "info";

    }

@CookieValue

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CookieValue {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;

    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}

使用

   @RequestMapping(value = "/testCookieValue")
    public String testCookieValue(@CookieValue(value = "JSESSIONID") String sessionId){
        System.out.println("sessionId: "+sessionId);
        return "info";

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章