URL匹配

书写方式

是对DispatcherServlet所匹配的URL进行二次匹配。本例DispatcherServelt的servlet-mapping中<url-pattern>/</url-pattern>。

//将匹配 /viewProduct
@RequestMapping("viewProduct")
public String viewProduct(...) { ... }

//将匹配 /viewProduct 
@RequestMapping(value="viewProduct")
public String viewProduct(...) { ... }

//将匹配 /viewProduct和/showProduct
@RequestMapping(value={"viewProduct","showProduct"})
public String viewProduct(...) { ... }

如果DispatcherServelt的servlet-mapping中<url-pattern>/store/*</url-pattern>。

//将匹配 /store/viewProduct
@RequestMapping("viewProduct")
public String viewProduct(...) { ... }

@RequestMapping可以加在Controller class,下例url-pattern为/

@RequestMapping("product")
public class ProductController{
    //将匹配 /product/viewProduct
    @RequestMapping("viewProduct")
    public String viewProduct(...) { ... } 
    ......
}

最优匹配

如果一个url匹配多个多个,采用最佳匹配的方式。

@RequestMapping("view/*")
public String viewAll(...) { ... }
@RequestMapping("view/*.json")
public String viewJson(...) { ... }
@RequestMapping("view/id/*")
public String view(...) { ... }
@RequestMapping("view/other*")
public String viewOther(...) { ... }

对于/view/other.json,将匹配viewOther()。前缀优先。有例如/view/id/anything.json,将匹配view()。

方法匹配

@RequestMapping("account")
public class AccountManagementController{
    //匹配 GET /account/add 
    @RequestMapping(value="add", method=RequestMethod.GET)
    public String addForm(...) { ... }

    //匹配 POST /account/add  
    @RequestMapping(value="add", method=RequestMethod.POST)
    public View addSubmit(...) { ... }
}

如果在类中指定方法,例如:

@RequestMapping(value="account", method={RequestMethod.GET, RequestMethod.POST})
public class AccountManagementController

先检查是否符合类的@RequestMapping限制,然后再检查是否符合方法@RequestMapping的限制。

请求参数限制

//要求具备参数employee,具备参数confirm且值为true
@RequestMapping(value="can", params={"employee", "confirm=true"})
public String can(...) { ... }

//要求不能具备employee,具备参数confirm且值不能为true
@RequestMapping(value="other", params={"!employee", "confirm!=true"})
public String other(...) { ... }

同样的,对于参数限制先检查是否符合类的@RequestMapping限制,然后再检查是否符合方法@RequestMapping的限制。

HTTP Header限制

和请求参数一样,具备否定的条件。此外:

  • header的值支持通配符。
  • header的名字大小写不敏感
@RequestMapping(value="user", headers={"X-Client", "content-type=text/*"})
public User user(...) { ... }

Content Type限制

可以使用headers对Content Type进行限制,但是更方便的通过consumes和produces:

  • consumes:对应请求中的Content-Type
  • produces:对应请求中的Accept
@RequestMapping(value="song", consumes={"text/json", "application/json"},
                              produces={"text/json", "application/json"})
public Song song(...) { ... }

本限制可以加载method也可以加在class,如果均有,则method的限定会override在类的限定,这和之前的有点不同,需要注意。因为这已经很明确具体到某个header的值的设定。



相关链接:

我的Professional Java for Web Applications相关文章