【Java】@PathVariable与@RequestParam 影响后台参数类型与前台传参的形式

本文通过实例解析了SSM框架中RequestParam与PathVariable两种注解的不同用法及对前端URL的影响,并分享了作者的实际经验。

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

前言

  小编最近在维护项目的过程中,遇到了swagger中不同环境下的同一方法运行效果不同。

一、问题背景

   自己在写SSM框架中的controller层写方法时,将两个注入@PathVariable与@RequestParam的概念没有理解清楚,导致Tomcat拦截了错误的语法。本地运行成功而在Nginx服务器部署后的环境被拦截。(自己听了公司技术老总的分析后,大体的理解是这样的,可能会有一些偏差。)

二、两种注解在后端如何正确使用

   1.第一种情况参数都使用@RequestParam注入,那么地址的拼写是不需要加参数的。
@RequestMapping(value = {"/findDictionarybyTypeId"}, 
method = RequestMethod.GET)
@ResponseBody
    public ItooResult findDictionarybyTypeId(HttpServletRequest request, 
    HttpServletResponse response, @RequestParam(required = false, defaultValue = "") 
    String typeId, @RequestParam(required = false, defaultValue = "") String dictionaryInfo) 

  在swagger中的展现形式:
这里写图片描述
   2.另一种情况参数使用@PathVariable注入,那么地址的拼写是需要加参数值的。

 @RequestMapping(value = {"/exportToExcel/{typeId}"},
  method = RequestMethod.GET)

    @ResponseBody
    public ItooResult exportToExcel(HttpServletRequest request,
     HttpServletResponse response, @PathVariable String typeId, 
     @RequestParam(required = false, defaultValue = "") String dictionaryInfo) 

  在swagger中的展现形式:
这里写图片描述

三、两种注解影响前端URL拼写

   1.使用@RequestParam注入的地址拼写:参数需要写参数名:'?typeId=' + this.dictionnaryId
url = 'http://192.168.22.52:8080/single-web/dictionary/findDictionarybyTypeId'  
+ '?typeId=' + this.dictionnaryId + '&dictionaryInfo=' + this.info;

   2.使用@PathVariable注入的地址拼写:参数直接传值:this.dictionnaryId

const url = 'http://192.168.22.52:8080/single-web/dictionary/exportToExcel/' 
+ this.dictionnaryId + '?dictionaryInfo=' + this.info;

小结

  出现了问题是一件好的事情,可以帮助我们接触之前没有学过的知识,同时要及时请教身边的巨人,站在巨人的肩膀上成长得会很快,不过自己还需要多掌握一些知识,夯实基础。
感谢您的访问!
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值