15.获取路径中的参数值——@PathVariable中的value

本节课是@PathVariable注解的具体使用。。。
与@RequestParam的区别

@PathVariable获取URI地址中的参数值,需要结合URI模板映射
@PathVariable会将数据放到模型中,界面可以通过el表达式获取(即浏览器上面可以显示出来),但是@RequestParam不能通过界面获得

1.@PathVariable String name

加上@PathVariable就能够获取到浏览器中rul的参数值

@RequestMapping("/get_param")
@Controller
public class GetParamController {
	@RequestMapping("/test6/{name}")  
	public String test6(@PathVariable String name) {
		System.out.println("GetParamController test6()...");
		System.out.println("name="+name);
		return "test";//跳转到test.jsp
		/* 
		 * ../test6/tom   结果:name=null 就要在参数里面加上@PathVariable  结果就变为:name=tom
		 * ../test6/tom?name=kk  结果:name=tom  拿到的是URI路径里面的值跟后面的没有任何关系
		 * */
	}
}

2.@PathVariable(“username”) String name

当浏览器中的是username,而后台要接收的是name

在这里插入图片描述
就会报错,由于username和name不匹配

在这里插入图片描述

此时要加上value值,@PathVariable(“username”)

@RequestMapping("/get_param")
@Controller
public class GetParamController {
	@RequestMapping("/test7/{username}")  //username与下面的name不一致,报错,就需要加上@PathVariable("username")
	public String test7(@PathVariable("username") String name) {//name和username不一致时,用@PathVariable("username")
		System.out.println("GetParamController test7()...");
		System.out.println("name="+name);
		return "test";//跳转到test.jsp
	}
}

在这里插入图片描述
此时就不会报错了

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java,反射是一种强大的机制,可以在运行时动态地获取和操作类的信息。通过反射,我们可以获取注解信息,包括获取@PathVariable注解的值。 要获取@PathVariable注解的值,可以按照以下步骤进行操作: 1. 首先,使用反射获取目标方法的Method对象。可以通过Class类的getMethod()或getDeclaredMethod()方法来获取目标方法的Method对象。 2. 然后,通过Method对象的getParameterAnnotations()方法获取方法参数上的所有注解。这个方法返回一个二维数组,每个元素表示一个参数上的所有注解。 3. 遍历参数上的注解数组,找到带有@PathVariable注解的参数。 4. 最后,通过注解对象的value()方法获取@PathVariable注解的值。 下面是一个示例代码: ```java import org.springframework.web.bind.annotation.PathVariable; public class ReflectionExample { public static void main(String[] args) throws NoSuchMethodException { // 获取目标方法的Method对象 Method method = MyClass.class.getMethod("myMethod", String.class); // 获取方法参数上的所有注解 Annotation[][] parameterAnnotations = method.getParameterAnnotations(); // 遍历参数上的注解数组 for (Annotation[] annotations : parameterAnnotations) { for (Annotation annotation : annotations) { // 判断是否为@PathVariable注解 if (annotation instanceof PathVariable) { // 获取@PathVariable注解的值 String value = ((PathVariable) annotation).value(); System.out.println("PathVariable value: " + value); } } } } } class MyClass { public void myMethod(@PathVariable("id") String id) { // 方法体 } } ``` 相关问题: 1. 什么是Java反射? 2. 如何使用反射获取方法的参数注解? 3. 除了@PathVariable,还有哪些常用的Spring注解?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值