当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Mvc中传递参数方法之url/requestMapping详解

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

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

方法如下

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

@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)

@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中获取参数

@requestmapping(value = "/system/getallcodetabledata/{category}", method = requestmethod.get) //前台url: '/system/getallcodetabledata/applicant_english' 
public list<codetablemodel> getcodetablemodelbycategory(@pathvariable string category) throws otpexception {<br>     return codetableservice.getcodetablemodelbycategory(category); <br>} 

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

@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));

 } 

总结

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网