spring 學習二 @RequestMapping

來源:互聯網
上載者:User

標籤:lan   foo   瀏覽器   get、post、   正則表達   index   cep   ram   htm   

RequestMapping是一個用來處理請求地址映射的註解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。

RequestMapping註解有六個屬性,下面我們把她分成三類進行說明。

1、 value, method;

value:     指定請求的實際地址,指定的地址可以是URI Template 模式(後面將會說明);

         @RequestMapping(value={"/foo","/bar"})。  // 可以指定多個值

     @RequestMapping("/appointments")   // 如果只要一個值,可以省略value
    @RequestMapping("/action3/{p1}/{p2}")  // 路徑預留位置,支援Regex
        public String action3(@PathVariable int p1,@PathVariable int p2,Model model){             model.addAttribute("message", p1+p2);              return "foo/index";    }

method:  指定請求的method類型, GET、POST、PUT、DELETE等;

2、 consumes,produces;

consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;

@Controller@RequestMapping("/home")public class HomeController {    // 請求內容類型必須為text/html,注意瀏覽器預設沒有指定Content-type    @RequestMapping(value = "/action8",consumes="text/html")    public String action8(Model model) {        model.addAttribute("message", "請求的提交內容類型(Content-Type)是text/html");        return "foo/index";    }}

produces:    指定返回的內容類型,僅當request要求標頭中的(Accept)類型中包含該指定類型才返回;

//用戶端接收json且編碼為utf-8,多數瀏覽器Accept設定的為*/*,接收任意類型    @RequestMapping(value = "/action9",produces="application/json; charset=UTF-8")    public String action9(Model model) {        model.addAttribute("message", "用戶端可以接收的類型是application/json; charset=UTF-8");        return "foo/index";    }
3、 params,headers;

params: 指定request中必須包含某些參數值是,才讓該方法處理。

  @RequestMapping(value = "/action10",params={"id=215","name!=abc"})    public String action10(Model model) {        model.addAttribute("message", "請求的參數必須包含id=215與name不等於abc");        return "foo/index";    }

headers: 指定request中必須包含某些指定的header值,才能讓該方法處理請求。

  @RequestMapping(value = "/action11",headers="Host=localhost:8088")    public String action11(Model model) {        model.addAttribute("message", "要求標頭部資訊中必須包含Host=localhost:8088");        return "foo/index";    }

 

spring 學習二 @RequestMapping

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.