SpringMVC中的请求地址映射:@RequestMapping、@RequestParam、@PathVariable

0、目录

1)    相关注解

@RequestMapping(最重要)@RequestParam@PathVariable

注意:@RequestParam与@PathVariable的区别。

2)    用到的类

枚举类:RequestMethod

3)    请求地址映射

A.       精准化映射

利用RequestMapping的value、method、params、header实现;同时利用@RequestParam对请求参数添加限制条件。

B.       @PathVariable

REST风格;从请求地址URL模板中提取变量值。

C.        Ant风格匹配:模糊匹配。

D.       正则表达式匹配

E.        “或”匹配:从多个条件中满足一个即可。

1.      @RequestMapping:映射请求地址。

1)    @RequestMapping功能:映射请求地址

Spring MVC使用@RequestMapping注解为控制器类或内部方法指定可以处理哪些URL请求。@RequestMapping是一个用来处理请求地址映射的注解(将请求地址映射到对应的控制器方法中)可用于类或方法

@RequestMapping请求路径映射,如果标注在某个@Controller的级别上,则表明访问此类路径下的方法都要加上其配置的路径;最常用是标注在方法上,表明哪个具体的方法来接受处理某次请求。

2)    @RequestMapping修饰类和方法

注解@RequestMapping类级别和方法级别层面都可标注,用来确定将被调用方法的URL。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径;用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法。在类上可以使用也可以不使用@RequestMapping,但是在handle方法上必须使用@RequestMapping

按照一般的开发习惯:类上的@RequestMapping一般就是利用类名作为父路径,可以指定多层,如@RequestMapping(value='/xxx/xxx/类名');然后内部方法上利用方法名指定,一般就是一层路径,如@RequestMapping(value='/方法名')。

提供初步的请求映射信息,相当于WEB应用的根目录。

在标有@Controller的类中,利用@RequestMapping可以将该类中的方法变成handler方法,用来处理请求。

3)    @RequestMapping的属性(6个):实现精准化映射

@RequestMapping具有四个属性:value、method、params、headers、consumes、produces。(consumes、produces使用较少)

分别为映射请求路径(value属性)、请求方法(method属性)、请求参数(parmas属性)或请求头(headers属性)。多个属性同时指定的时候,利用逗号隔开,属性之间的关系是“与”的关系。

@RequestMapping一般情况必须指定属性value,用来指定对应的URL,这就是粗略映射。当@RequestMapping只指定一个属性value,此时value可省略不写,即@RequestMapping(value="/hello")等价于@RequestMapping("/hello")。

注意:"@RequestMapping"的value值前后是否有“/”对请求的路径没有影响,即value="book" "/book""/book/"其效果是一样的

A.       method:指定请求的method类型, GET、POST、PUT、DELETE等;

@RequestMapping(value="/get/{bookid}",method={RequestMethod.GET,RequestMethod.POST})

RequestMethod是一个枚举类。

B.       params:指定request中必须包含某些参数值是,才让该方法处理。

@RequestMapping(params="action=del"),请求参数包含“action=del”,如:http://localhost:8080/book?action=del

params通过一个数组定义,如params={"xxx1=yyy1","xxx2=yyy2","xxx3","xxx4"}

意思是,必须有参数值为yyy1的xxx1参数,值为yyy2的xxx2参数,必须具有参数xxx3和xxx4参数,值可以为任意。

如:@RequestMapping(value="/hello",method=RequestMethod.POST,params={"user=zhaohong","passwd=zhao12","code"})

C.        headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。

headers的使用方法与params相同,如headers={"Accept=text/html"}

@RequestMapping(value="/header/id",headers = "Accept=application/json"):表示请求的URL必须为“/header/id且请求头中必须有“Accept =application/json”参数即可匹配。

D.       consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html。

@Controller

@RequestMapping(value= "/pets", method = RequestMethod.POST,consumes="application/json")

public voidaddPet(@RequestBody Pet pet, Model model) {   

    // implementation omitted

}

 方法仅处理request Content-Type为“application/json”类型的请求。

E.        produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。

@Controller

@RequestMapping(value= "/pets/{petId}", method = RequestMethod.GET, produces="application/json")

@ResponseBody

public PetgetPet(@PathVariable String petId, Model model) {   

    // implementation omitted

}

 方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

4)    或的关系:用花括号括起来,逗号隔开即可。

@RequestMapping(value={"/getBody","/fetchBody"} )即 /get或/fetch都会映射到该方法上。

@RequestMapping(value="getBody",method={RequestMethod.GET,RequestMethod.POST})

2.      Ant风格:URL支持的3种风格

1)     Ant风格资源地址支持3种匹配符介绍

A.       ? : 匹配文件名中的一个字符;

B.       *:匹配文件名中的任意多个字符(包括0),但是只能匹配1层目录;

C.        **:匹配任意多层目录(包括0),可以为0层、1层或多层目录;

2)    示例

@RequestMapping(value="/get/id?"):可匹配“/get/id1”或“/get/ida”,但不匹配“/get/id”或“/get/idaa”;

@RequestMapping(value="/get/id*"):可匹配“/get/idabc”或“/get/id”,但不匹配“/get/idabc/abc”;

@RequestMapping(value="/get/id/*"):可匹配“/get/id/abc”,但不匹配“/get/idabc”;

@RequestMapping(value="/get/id/**/{id}"):可匹配“/get/id/abc/abc/123”或“/get/id/123”,也就是Ant风格和URI模板变量风格可混用

3.      @PathVariable:用来获取请求路径URL中的动态参数

1)    REST风格的URL

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

REST风格简单描述:

         传统URL:http://www.baidu.com?user=zhaohong&password=zhao12

REST风格:http://www.baidu.com/zhaohong/zhao12

就是改变key=value的形式,直接使用value。

2)    REST:表现层状态转化

POST:新建资源;(

DELETE:删除资源;(

PUT:更新资源;(

GET:获取资源。(

3)    映射信息:占位符

SpringMVC配置映射信息,需要在映射信息后面对应的位置加入占位符{xxx}

如:@RequestMapping(value="www/baidu/com/{user}/{passwd}"}

4)    @PathVariable的功能

@PathVariable用于将请求URL中的模板变量值映射到功能处理方法的参数上,即提取URL模板中的变量作为参数。。

5)    @PathVariable的value属性

通过 @PathVariable 可以将URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(value="xxx")绑定到操作方法的入参(形参)中。如果URL模板中定义的{XXX}变量名与方法参数名一致,value属性可以省略,若不一致,必须制定value属性,但是如果只定义value一个属性,value往往也可以省略。

6)    正则匹配URL与@PathVariable的结合

@RequestMapping(value="/get/{idPre:\\d+}-{idNum:\\d+}"):可以匹配“/get/123-1”,但不能匹配“/get/abc-1”,这样可以设计更加严格的规则。

可以通过@PathVariable 注解提取路径中的变量(idPre,idNum)

@ResponseBody
@RequestMapping(value = "getRegexParam/{idPre:\\d+}-{idNum:\\d+}",method = {RequestMethod.GET,RequestMethod.POST})
public String getRegexParams(@PathVariable("idPre") int idPre,@PathVariable String idNum){
    return idPre+"-"+idNum;
}

http://localhost:8080/SpringMVCDemo0711/test/getRegexParam/666-888

结果:666-888

7)    示例:

@ResponseBody
@RequestMapping
(value = "/getPathVairable/{id}/{name}/{address}",method = {RequestMethod.GET,RequestMethod.POST})
public String getPathVariableValue(@PathVariable(value = "id") String NO,@PathVariable("name")StringmyName,@PathVariable String address){
   
return "StudentNo:"+NO+"<br>StudentName:"+myName+"<br>StudentAddress:"+address;
}

这个例子中:{id}与方法参数NO对应;{name}与方法参数myName对应;{address}与方法参数address对应。

4.      @RequestParam绑定单个请求参数值

1)    @RequestParam的作用

@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。

public Stringrequestparam1(@RequestParam String username)

 请求中包含username参数(如/requestparam1?username=zhang),则自动传入。

注意:在Controller的handler方法中获取参数的方式两种:一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。

显然直接使用@RequestParam比较方便。

当然,现在不添加@RequestParam,也已经默认支持

@ResponseBody
@RequestMapping(value = "/getParams",method = {RequestMethod.GET,RequestMethod.POST})
public String getParams(String id,String name){
    return "StudentID:"+id+"<br>StudentName:"+name;
}
http://localhost:8080/SpringMVCDemo0711/test/getParams?id=100&name=zhaohong

StudentID:100

StudentName:zhaohong

2)    @RequestParam的3个属性:

value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将抛出异常;

defaultValue:默认值,表示如果请求中没有同名参数时的默认值,设置该参数时,自动将required设为false。

3)    示例

public Stringrequestparam4(@RequestParam(value="username",required=false) Stringusername)

表示请求中可以没有名字为username的参数,如果没有默认为null。

4)    需要注意如下几点:

原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。

Boolean包装类型:默认Boolean.FALSE,其他引用类型默认为null。

5)    POJO对象接收:根据对象属性自动创建对象

当然需要Pojo中有各个变量的set方法。

@ResponseBody
@RequestMapping(value = "/getStudent",method = {RequestMethod.GET,RequestMethod.POST})
public String getStudent(Student student){
    return student.toString();
}
http://localhost:8080/SpringMVCDemo0711/test/getStudent?id=100&name=zhaohong&address=Beijing
结果:Student{id=100, name='zhaohong', address='Beijing'}

6)    多个同名参数接收问题:集合接收或数组接收

如果请求中有多个同名的应该如何接收呢?

方法:利用数组或者集合接收。

举例:给用户角色分配时,可能授予多个角色权限:

A.       利用List集合接收

@ResponseBody
@RequestMapping
(value = "getList",method = {RequestMethod.GET,RequestMethod.POST})
public String getList(@RequestParam(value = "role")List<String> roleList){
   
return roleList.toString();
}

http://localhost:8080/SpringMVCDemo0711/test/getList?role=student&role=teacher&role=worker

结果:[student, teacher,worker]

B.       利用数组接收

@ResponseBody
@RequestMapping(value = "getArray",method = {RequestMethod.GET,RequestMethod.POST})
public String getArray(@RequestParam(value = "role")String[] roleArray){
    return Arrays.toString(roleArray);
}

http://localhost:8080/SpringMVCDemo0711/test/getArray?role=student&role=teacher&role=worker

结果:[student, teacher, worker]

5.      @PathVariable与@RequestParam的区别

1)    相同点

A.       作用位置相同:都是直接修饰方法参数变量;

B.       功能相似:都是将URL中的变量值映射到方法参数上;

C.        都具有value属性:将URL变量名与方法参数名映射起来;

2)    不同点

A.       对应的URL不同

@PathVariable对应的URL是REST风格,具有占位符{XXX},即URL模板;如/{id}/{name}

@RequestParam对应的URL是传统URL,key=value形式,如?id=1&name=zhaohong

B.       设置默认值

@RequestParam可以通过defaultValue属性设置默认值,而@PathVariable不可以。

C.        是否必需

@RequestParam可以通过required属性设置是否必需,默认为true;而@PathVariable一定是必需的。

6.      RequestMethod枚举类的介绍

1)    RequestMethod类:定义HTTP的请求方法。

public enum RequestMethod  extendsjava.lang.Enum<RequestMethod>

Java 5 enumeration of HTTP request methods. Intended for use with the RequestMapping.method()attribute of the RequestMapping annotation.

         DispatcherServlet默认不支持traceoptions请求

Note that, bydefaultDispatcherServlet supports GET, HEAD, POST, PUT, PATCHand DELETE only. DispatcherServlet will process TRACEand OPTIONS with the default HttpServlet behavior unless explicitly told to dispatch those request types as well:Check out the "dispatchOptionsRequest" and "dispatchTraceRequest"properties, switching them to "true" if necessary.

2)    枚举元素(8个)Enum Constants

DELETE、GET 、HEAD、PATCH 、POST 、PUT 、TRACE、OPTIONS

3)    2个静态方法




猜你喜欢

转载自blog.csdn.net/qq_29545781/article/details/81000361
今日推荐