欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-02-24 09:38:31|栏目:JAVA代码|点击:

前言

相信大家在使用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));

 } 

总结

上一篇:详解使用Maven构建多模块项目(图文)

栏    目:JAVA代码

下一篇:从千千静听歌词服务器获取lrc歌词示例分享

本文标题:Spring Mvc中传递参数方法之url/requestMapping详解

本文地址:http://www.codeinn.net/misctech/69039.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有