springmvc--REST 和@RequestParam

本文介绍Spring MVC中如何使用@RequestMapping进行请求映射,包括Ant风格的URL匹配及RESTful风格的设计,并展示了如何利用HiddenHttpMethodFilter支持HTTP的所有标准方法。此外,还讲解了@RequestParam注解用于绑定请求参数的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.@RequestMapping 支持 Ant 格的 URL

Ant 源地址支持 3 匹配符
– ?:匹配文件名中的一个字符
– *:匹配文件名中的任意字符
– **** 匹配多路径


– /user/*/createUser:         匹配/user/aaa/createUser/user/bbb/createUser URL

– /user/**/createUser:         匹配 /user/createUser/user/aaa/bbb/createUser URL
– /user/createUser??:          
匹配   /user/createUseraa/user/createUserbb URL

@RequestMapping("testAnt/*/abc")
	public String testAntPath(){
		System.out.println("test ant");
		return SUCCESS;
	}

hello.jsp

<a href="testAnt/1111/abc">testAnt</a><br>
2.  REST:即 Representational State Transfer。(源)表现层态转。是目前
    最流行的一
件架。它结构清晰、符合准、易于理解、展方便,
    所以正得到越来越多网站的采用
源(Resources:网上的一个体,或者是网上的一个具体信息。它
可以是一段文本、一
张图片、一首歌曲、一之就是一个具体的存在。
可以用一个
URI源定位符)指向它,种资对应一个特定的 URI 。要
源,访问它的URI就可以,因此 URI 一个源的独一无二的

现层Representation源具体呈出来的形式,叫做它的表现层
Representation)。比如,文本可以用 txt 格式表,也可以用 HTML
式、
XML 格式、JSON 格式表,甚至可以采用二制格式。
态转化(State Transfer出一个求,就代表了客端和服器的一
次交互
程。HTTP协议,是一个无状态协议,即所有的状都保存在服
端。因此,如果客
端想要操作服器,必手段,器端
态转State Transfer)。而这种转化是建立在表现层之上的,所以就是
现层态转。具体,就是 HTTP 协议里面,四个表示操作方式的
GETPOSTPUTDELETE。它别对应基本操作:GET 用来
源,POST 用来新建源,PUT 用来更新源,DELETE 用来源。
(2)HiddenHttpMethodFilter浏览form 只支持 GETPOST 求,而DELETEPUT method 并不支
持,
Spring3.0 添加了一个过滤器,可以将转换为标准的 http 方法,使得支持 GETPOSTPUT
DELETE

1.首先在web.xml配置过滤器 HiddenHttpMethodFilter

<filter>
 	<filter-name>HiddenHttpMethodFilter</filter-name>
 	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter </filter-class>
 </filter>
 
 <filter-mapping>
 	<filter-name>HiddenHttpMethodFilter</filter-name>
 	<url-pattern>/*</url-pattern>
 </filter-mapping>
2. 写一个Test方法
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
	public String testRestDelete(@PathVariable Integer id){
		System.out.println("testRest"+id);
		return SUCCESS;
	}
3. 将form表单的post请求 转为 delete请求
<form action="/springMVC-01/testRest/1" method="post">
		<input type="hidden" name="_method" value="put"/>
		<input type="submit" value="TestRest DELETE"/>
</form>

三.使用 @RequestParam 求参数

<1>在理方法入参使用 @RequestParam 可以把求参数传递给请求方法

@RequestParam 来映射请求参数. value 值即请求参数的参数名 required 该参数是否必须. 默认为 true,defaultValue 请求参数的默认值

	@RequestMapping(value="/testRequestParam")
	public String testRequestParam(
			@RequestParam(value="username")String un,
			@RequestParam(value="age",required=false,defaultValue="0")int age){
		System.out.println("username="+un+ ""+"age="+age);
		return SUCCESS;
	}
	

<a href="springMVC-01/testRequestParam?username=atguigu&age=11">Test RequestParam</a>















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值