SpringMVC 之 @RequestMapping

SpringMVC 之 @RequestMapping

本节我们将学一下 SpringMVC 的 @RequestMapping。

  • Spring MVC 使用 @RequestMapping 注解为控制器指定可以处理哪些 URL 请求。

  • 在控制器的类定义及方法定义处都可标注

    • 类定义处:提供初步的请求映射信息。相对于 WEB 应用的根目录

      package com.spring.sstps.controller;
      
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.ModelMap;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      @Controller("contract")
      public class ContractController {
      
          @RequestMapping("/getContract/{cid}")
          public String getContract(@PathVariable("cid") Integer cid,ModelMap modelMap) throws Exception{
      
              return "contract/getContractDetial";
          }
      }
      
    • 方法处:提供进一步的细分映射信息。相对于类定义处的 URL。若类定义处未标注 @RequestMapping,则方法处标记的 URL 相对于WEB 应用的根目录

      package com.spring.sstps.controller;
      
      import org.springframework.stereotype.Controller;
      import org.springframework.ui.ModelMap;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      
      @Controller
      public class ContractController {
      
          @RequestMapping("/contracrt/getContract/{cid}")
          public String getContract(@PathVariable("cid") Integer cid,ModelMap modelMap) throws Exception{
      
              return "contract/getContractDetial";
          }
      }
      
  • • DispatcherServlet 截获请求后,就通过控制器上@RequestMapping 提供的映射信息确定请求所对应的处理方法。


映射请求参数

• @RequestMapping 除了可以使用请求 URL 映射请求外,还可以使用请求方法、请求参数及请求头映射请求。

• @RequestMapping 的 value、method、params 及 heads 分别表示请求 URL、请求方法、请求参数及请求头的映射条件,他们之间是与的关系,联合使用多个条件可让请求映射更加精确化。

/**
     * param 限制:只有Area=UA 并且 Domain !=SA 并且 请求头参数 Accept-Language 一定要为 zh-CN,zh;q=0.8
     * 并且 Connection = keep-alive 此时该URL 才能被映射成功否则将报404 错误
     * @param cid
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUAContract/{cid}", method = RequestMethod.POST,params={"Area=UA","Domain!=SA"},headers={"Accept-Language:zh-CN,zh;q=0.8","Connection:keep-alive"})
    public String getUAContract(@PathVariable("cid") Integer cid, ModelMap modelMap) throws Exception {

        return "contract/getUAContractDetial";
    }
  • params 和 headers支持简单的表达式

    • param1: 表示请求必须包含名为 param1 的请求参数

    • !param1: 表示请求不能包含名为 param1 的请求参数

    • param1 != value1: 表示请求包含名为 param1 的请求参数,但其值不能为 value1

    • {“param1=value1”, “param2”}: 请求必须包含名为 param1 和param2 的两个请求参数,且 param1 参数的值必须为 value1


映射请求

  • Ant 风格资源地址支持 3 种匹配符

    • ?:匹配文件名中的一个字符

      //  /getClearHouset/?/{cid} 是一个占位符,只能匹配任意一个字符
          @RequestMapping("/getClearHouset/?/{cid}")
          public String getClearHousetByDomain(@PathVariable("cid") Integer cid, ModelMap modelMap) throws Exception {
      
              return "contract/getClearHousetByDomain";
          }
    • *:匹配文件名中的任意字符

      //  /*/getClearHouset/{cid} 中的*可以使任意字符或者字符串
          @RequestMapping("/*/getClearHouset/{cid}")
          public String getClearHouset(@PathVariable("cid") Integer cid, ModelMap modelMap) throws Exception {
      
              return "contract/getClearHouset";
          }
    • 1**:** 匹配多层路径:1请忽略,应为编辑器的原因 星星:星星 的形式打不出来 - -!

      // /**/getClearHousetByDomain/{cid} 中可以时任意路径可以时单层比如 /UA/getClearHousetByDomain/{cid}
          // 也可以是多层比如  /NA/UA/getClearHousetByDomain/{cid}
          @RequestMapping("/**/getClearHousetByDomain/{cid}")
          public String getClearHousetByDomainAndArea(@PathVariable("cid") Integer cid, ModelMap modelMap) throws Exception {
      
              return "contract/getClearHousetByDomainAndArea";
          }

@PathVariable

带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义。

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的{xxx} 占位符可以通过@PathVariable(“xxx”) 绑定到操作方法的入参中。

@RequestMapping("/getBroker/{broker}")
    public String getBrokerByDomain(@PathVariable("broker") String broker, ModelMap modelMap) throws Exception {

        return "contract/getClearHousetByDomainAndArea";
    }
@RequestMapping("/getBroker/{broker}/Domain/{domain}")
    public String getBrokerByDomain(@PathVariable("broker") String broker, @PathVariable("domain") String domain,
            ModelMap modelMap) throws Exception {

        return "contract/getClearHousetByDomainAndArea";
    }

    /**
     * @PathVariable是用来获得请求url中的动态参数的
     * 同时还支持正则表达,一下例子为只要动态参数是 a-z的小写字母我们就能支持映射,否则不予以映射
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBrokerByReg/regexpress:[a-z-]")
    public String getBrokerByReg(@PathVariable("regexpress") String regexpress) throws Exception {
        return "contract/getBrokerByReg";
    }

RESTful Request

  • REST:即 Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便, 所以正得到越来越多网站的采用。

  • 资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的 URI 。要获取这个资源,访问它的URI就可以,因此 URI 即为每一个资源的独一无二的识别符

  • 表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层
    (Representation)。比如,文本可以用 txt 格式表现,也可以用 HTML 格式、XML 格式、JSON 格式表现,甚至可以采用二进制格式

  • 状态转化(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,是一个无状态协议,即所有的状态都保存在服务器 端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生“ 状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是 “表现层状态转化”。具体说,就是 HTTP 协议里面,四个表示操作方式的动
    词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。

  • SpringMVC 对RESTful 风格URL 的支持例子 (V >4.3.0)

    package com.spring.sstps.controller;
    
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController("/order")
    public class OrderController {
    
        /**
         * 添加新的订单
         * @return
         * @throws Exception
         */
        @PostMapping("/addOrder")
        public String addOrder() throws Exception{
            return "order/addOrder";
        }
    
        /**
         * 根据ID 获取 订单
         * @param oid
         * @return
         * @throws Exception
         */
        @GetMapping("/getOrder/{oid}")
        public String getOrderById(@PathVariable("oid") Integer oid) throws Exception{
            return "order/getOrderById";
        }
    
        /**
         * 获取订单列表
         * @return
         * @throws Exception
         */
        @GetMapping("/getOrders")
        public String getOrders() throws Exception{
            return "order/getOrders";
        }
    
        /**
         * 根据ID 删除订单
         * @param oid
         * @return
         * @throws Exception
         */
        @DeleteMapping("/deleteOrder/{oid}")
        public String deleteOrderById(@PathVariable("oid") Integer oid) throws Exception{
            return "order/deleteOrderById";
        }
    }
    

    代码解读:

    • @PostMapping(“/addOrder”)

      • 添加订单(资源)时使用POST 请求
    • @GetMapping(“/getOrder/{oid}”)

      • 根据ID 获取订单(资源)使用Get请求
    • @GetMapping(“/getOrders”)
      • 获取所有订单(资源)使用Get请求
    • @DeleteMapping(“/deleteOrder/{oid}”)
      • 根据ID 删除某个订单(资源) 使用DELETE请求

当然RESTful的请求还有很多种,建议下载一个叫POSTMAN 的APP或者Chrome的集成插件便可将RESTful的请求梳理地一清二楚。


@RequestParam

• 在处理方法入参处使用 @RequestParam 可以把请求参数传递给请求方法

  • value:参数名

  • required:是否必须。默认为 true, 表示请求参数中必须包含对应的参数,若不存在,将抛出异常

    @GetMapping(value="/getOrderByDomain")
        public String getOrderByDomain(@RequestParam(value="domain",required=true) String domain) throws Exception{
            return "order/getOrderById";
        }

@RequestHeader

• 请求头包含了若干个属性,服务器可据此获知客户端的信息,通过 @RequestHeader 即可将请求头中的属性值绑定到处理方法的入参中

@GetMapping("/getOrderByArea")
    public String getOrderByArea(@RequestHeader("Accept-Encoding") String encoding,@RequestHeader("Keep-alive") String status) throws Exception{
        return "order/getOrderByArea";
    }

@CookieValue

• @CookieValue 可让处理方法入参绑定某个 Cookie 值

@GetMapping("/getOrderByClearHouse")
    public String getOrderByClearHouse(@SessionAttribute("sessionId") String sessionId,@RequestParam("clearHouse") String clearHouse) throws Exception{
        return "order/getOrderByClearHouse";
    }

POJO 对象绑定请求参数值

请参考本人另外一篇文章:SpringMVC 之 @ModelAttribute&OOP处理


小结

  • 关于SpringMVC 的@RequestMapping 中还有很多点本章没有列出来,有兴趣的可以参考官方文档。
  • @RequestParam 和@PathVariable的区别:

    • springmvc/testPathVariable/1 这样的请求,我们通过@PathVariable来绑定请求的参数;

    • springmvc/testRequestParam?username=jackie&age=12 这样的请求参数是以键值对出现的,我 们通过@RequestParam来获取到如username或age后的具体请求值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值