您的位置:首页技术文章
文章详情页

SpringBoot多种场景传参模式

【字号: 日期:2023-02-21 14:34:58浏览:5作者:猪猪
目录web技术多种传参方式传统参数传递复杂对象映射数组和集合类型参数Restful风格传参web技术

我们知道常见的web技术也就是网站开发,分为静态网站,和动态网站,动态网站技术常见的有三种,分别是 jsp java web,asp c# web,php web但是它们对应请求request,响应response 都是一样的我们用java web开发动态网站用的mvc框架就是,springmvc,当然我们现在用的是springboot 它只是对spirng全家桶的一个整合框架,他本质不是一个新的框架,内部还是spirng+springmvc

多种传参方式传统参数传递

我们知道controller方法中会帮我注入HttpServletRequest对象,我们可以通过request.getParameter('参数名')来直接获取参数,

@RequestMapping('/test01')public ModelAndView test01(HttpServletRequest request){ String username = request.getParameter('username'); String password = request.getParameter('password'); System.out.println(username); System.out.println(password); return null;}

简单类型参数映射

如果请求参数和Controller方法的形参同名,可以直接接收 如果请求参数和Controller方法的形参不同名,可以使用@RequestParam注解贴在形参前,设置对应的参数名称

注意这里只能是基本数据类型比如string,int,long,boolean等类型

@RequestMapping('/test02_1')public ModelAndView test02_1(String username,String password){ System.out.println(username); System.out.println(password); return null;}@RequestMapping('/test02_2')public ModelAndView test02_2(@RequestParam('username') String name,@RequestParam(value = 'password',defaultValue = '1234987') String pwd){ //使用了@RequestParam的参数不能传空值 // required:表示是否必须要传值 // defaultValue:当没有该请求参数时,SpringMVC给请求参数的默认值 System.out.println(name); System.out.println(pwd); return null;}复杂对象映射

当然在实际项目中,我们会有很多个参数,一般超过两个参数我们就要封装成对象,通过对象传参数,不然这么一个一个写会麻烦,代码冗余,不美观,不能复用

此时能够自动把参数封装到形参的对象属性上:

请求参数必须和对象的属性同名 此时对象会直接放入request作用域中,名称为类型首字母小写 @ModelAttribute设置请求参数绑定到对象中并传到视图页面的key值

@RequestMapping('/test03')public ModelAndView test03(@ModelAttribute('stu') Student student){ /*可以使用对象作为方法的形参,同时接受接受前台的多个请求参数 SpringMVC会基于同名匹配,将请求参数的值注入对应的对象中的属性中 @ModelAttribute起名字key值*/ System.out.println(student); ModelAndView mv = new ModelAndView(); mv.setViewName('test2'); return mv;}

如果需要body里面json传参数需要在形参前面加上@RequestBody 会自动完成映射

@PostMapping('/register') public Result bodyParams(@RequestBody Users users) {return ResultResponse.success(users); }数组和集合类型参数

当前台页面传来的参数是参数名相同,参数值不同的多个参数时,可以直接封装到方法的数组类型的形参中比如批量删除时传来的参数

/*对于参数名相同的多个请求参数,可以直接使用数组作为方法的形参接收 可以使用对象中的集合属性接收*/ @DeleteMapping('/del') public Result listParams(String[] ids) {return ResultResponse.success(ids); }

SpringBoot多种场景传参模式

Restful风格传参

Restful是一种软件架构风格,严格上说是一种编码风格,其充分利用 HTTP 协议本身语义从而提供了一组设计原则和约束条件。

主要用于客户端和服务器交互类的软件,该风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。 在后台,RequestMapping标签后,可以用{参数名}方式传参,同时需要在形参前加注解@PathVarible

@RequestMapping('/delete/{id}')public ModelAndView test4(@PathVariable('id')Long id){ System.out.println('delete'); System.out.println(id); return null;}

到此这篇关于SpringBoot多种场景传参模式的文章就介绍到这了,更多相关SpringBoot 传参模式内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Spring
相关文章: