Spring Mvc中传递参数方法之url/requestMapping详解
前言
相信大家在使用spring的项目中,前台传递参数到后台是经常遇到的事,我们必须熟练掌握一些常用的参数传递方式和注解的使用,本文将给大家介绍关于SpringMvc中传递参数方法之url/requestMapping的相关内容,分享出来供大家参考学习,话不多说,直接上正文。
方法如下
1.@requestMapping:类级别和方法级别的注解,指明前后台解析的路径。有value属性(一个参数时默认)指定url路径解析,method属性指定提交方式(默认为get提交)
@RequestMapping(value="/testing") publicclassQuestionSetDisplayControllerextendsBaseController{} @RequestMapping(value="/applicant/recover") publicBaseModelrecover(Stringcellphone)throwsOTPException{ returnuserService.recover(cellphone); }
2.@RequestParam:请求参数规则注解。value属性匹配前台传递的参数(一个参数时默认),required属性此字段是否必须传值(boolean,默认为true),defaultValue此参数的默认值(存在此参数时,说明前台不必需传递参数,required为false)
@RequestMapping("/login")//url:/login?name=tom publicStringlogin(@RequestParam(value="age",required=false,defaultValue="24")Stringagenum,@RequestParam("name")Stringname){ return"hello"; }
3.@PathVariable:url参数注解,一般用于从url中获取参数
@RequestMapping(value="/system/getAllCodeTableData/{category}",method=RequestMethod.GET)//前台url:'/system/getAllCodeTableData/APPLICANT_ENGLISH'
publicListgetCodeTableModelByCategory(@PathVariableStringcategory)throwsOTPException{
returncodeTableService.getCodeTableModelByCategory(category);
}
4.特殊的属性编辑器在前台到后台data日期类型等的转化会出错,此时我们需要属性编辑器进行属性的转化//日期传递参数会产生异常,因此在传递时间参数时,需要进行类型转换,在初始化时进行数据的绑定与转化
@RequestMapping(value="/todate/{data}",method=RequestMethod.GET) publicStringtodate(@PathVariable("data")Datedate){ System.out.println(newSimpleDateFormat("yyyy-MM-dd").format(date)); return"start"; } @InitBinder//初始化参数绑定,日期类型的转化, publicvoidinitBinder(ServletRequestDataBinderbinder){ binder.registerCustomEditor(java.util.Date.class,newCustomDateEditor(newSimpleDateFormat("yyyy-MM-dd"),true)); }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持