@requestMapping参数详解

对应项目jsp位置则是一级路径对应一级文件目录。

如url为/default/index对应项目中webapp/default/index.jsp


RequestMapping注解有六个属性,下面我们把她分成三类进行说明。

【1】value, method

value:指定请求的实际地址,指定的地址可以是URI Template 模式;

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


【2】consumes,produces

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

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


【3】params,headers

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

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


测试示例如下:


【1】value||path

  • JSP 页面

Test RequestMapping

  • controller

@RequestMapping(value=“/testRequestMapping” )

public String testRequestMapping() {

System.out.println(“testRequestMapping”);

return SUCCESS;

}

成功返回success.jsp 。

**Tips :**若 href 属性值,不等于value值,则将提示404错误。


value的uri值为以下三类:

A) 可以指定为普通的具体值;

如下:

@RequestMapping(“/testRequestMapping”)


B) 可以指定为含有某变量的一类值(URI Template Patterns with Path Variables)–restful风格;

@RequestMapping(“/testPathVariable/{id}”)

public String testPathVariable(@PathVariable Integer id2) {

System.out.println("testPathVariable: " + id2);

return SUCCESS;

}


除了value还有path,二者效果等同,可以参考源码如下图:

这里写图片描述


其中关于@PathVariable 有如下说明:

① 如果路径中的变量与方法中的变量名一致,可直接使用@PathVariable;

② 如果二者不一致,则使用@PathVariable(Variable)显示指定要绑定的路径中的变量 。

@PathVariable只能绑定路径中的占位符参数,且路径中必须有参数。

@PathVariable用法参考[路径参数绑定参考](()

@RequestMapping(“/testPathVariable/{id}”)

public String testPathVariable(@PathVariable(“id”) Integer id2) {

System.out.println("testPathVariable: " + id2);

return SUCCESS;

}

//路径中的 id 与 方法中的 id2 绑定

C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

@RequestMapping(“/spring-web/{symbolicName:[a-z-]+}-{version:\d.\d.\d}.{extension:.[a-z]}”)

public void handle(@PathVariable String version, @PathVariable String extension) {

// …

}

}


【2】method

  • JSP 页面

Test Method

//href 默认为get 请求。

  • controller–限制接收post 请求。

@RequestMapping(value = “/testMethod”, method = RequestMethod.POST)

public String testMethod() {

System.out.println(“testMethod”);

return SUCCESS;

}

  • result as follows :

HTTP Status 405 - Request method ‘GET’ not supported 。

这里写图片描述

【状态码405表示:请求 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 中指定的方法不被允许。】

将method 改为method = RequestMethod.GET正常跳转页面。


【3】consumes

  • JSP 页面

仍以testMethod为例,提交表单。

默认contentType为Content-Type:application/x-www-form-urlencoded。

这里写图片描述


  • controller–限制接收post 请求以及consumes="application/json"

@RequestMapping(value = “/testMethod”, method = RequestMethod.POST,consumes=“application/json”)

public String testMethod() {

System.out.println(“testMethod”);

return SUCCESS;

}

  • result as follows :

这里写图片描述

【状态码415表示:由于媒介类型不被支持,服务器不会接受请求。。】

去掉 consumes属性,页面正常跳转 !


【4】produces

你可能感兴趣的:(Java,经验分享,架构,java)