Spring Mvc中传递参数方法之url/requestMapping详解

2025-05-29 0 63

前言

相信大家在使用spring的项目中,前台传递参数到后台是经常遇到的事, 我们必须熟练掌握一些常用的参数传递方式和注解的使用,本文将给大家介绍关于Spring Mvc中传递参数方法之url/requestMapping的相关内容,分享出来供大家参考学习,话不多说,直接上正文。

方法如下

1. @requestMapping: 类级别和方法级别的注解, 指明前后台解析的路径。 有value属性(一个参数时默认)指定url路径解析,method属性指定提交方式(默认为get提交)

?

1

2

3

4

5

6

7

8

9

10

11

12
@RequestMapping(value = "/testing")

public class QuestionSetDisplayController extends BaseController {}

@RequestMapping(value = "/applicant/recover")

public BaseModel recover(String cellphone) throws OTPException {

return userService.recover(cellphone);

}

2. @RequestParam: 请求参数规则注解。 value属性匹配前台传递的参数(一个参数时默认),required属性此字段是否必须传值(boolean,默认为true),defaultValue此参数的默认值(存在此参数时,说明前台不必需传递参数,required为false)

?

1

2

3

4

5

6

7
@RequestMapping("/login") //url: /login?name=tom

public String login(@RequestParam(value="age",required=false,defaultValue="24") String agenum,@RequestParam("name") String name){

return "hello";

}

3. @PathVariable: url参数注解, 一般用于从url中获取参数

?

1
@RequestMapping(value = "/system/getAllCodeTableData/{category}", method = RequestMethod.GET) //前台url: '/system/getAllCodeTableData/APPLICANT_ENGLISH'

?

1
public List<CodeTableModel> getCodeTableModelByCategory(@PathVariable String category) throws OTPException {<br>     return codeTableService.getCodeTableModelByCategory(category); <br>}

4. 特殊的 属性编辑器 在前台到后台data日期类型等的转化会出错,此时我们需要属性编辑器进行属性的转化 //日期传递参数会产生异常,因此在传递时间参数时,需要进行类型转换,在初始化时进行数据的绑定与转化

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
@RequestMapping(value="/todate/{data}",method=RequestMethod.GET)

public String todate(@PathVariable("data") Date date){

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));

return "start";

}

@InitBinder //初始化参数绑定, 日期类型的转化,

public void initBinder(ServletRequestDataBinder binder){

binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对快网idc的支持

原文链接:http://www.cnblogs.com/nelson-hu/p/6595522.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring Mvc中传递参数方法之url/requestMapping详解 https://www.kuaiidc.com/115549.html

相关文章

发表评论
暂无评论