SpringMVC 接受请求参数、作用域传值
目录
Spring MVC使用ModelAndView进行作用域传值
原生servlet接收参数
原生servlet接收参数的方式无非就是利用请求对象中的getParameter()方法和getParameterValues()方法来获取请求中的参数值。
package cn.ganlixin.servlet; import java.io.IOException; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet("/test")
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8"); String name = request.getParameter("name");
String[] hobbies = request.getParameterValues("hobbies");
}
}
虽然原生的servlet通过getParameter()和getParameterValues()的方式也可以获取请求参数,却比较麻烦,不仅需要调用方法来获取,在获取之后,还需要进行数据类型转换,在使用参数的时候,还需要判断获取到的参数值是否为null,的确是比较麻烦。
而如果使用Spring MVC,就可以消除这些麻烦。
关于Spring MVC的配置,这里就不写了,可以参考:SpringMVC 框架介绍以及环境搭建
Spring MVC获取请求参数值
Spring MVC可以省去我们在原生servlet中通过getParameter()来获取参数,而是很智能的注入到我们写在方法的参数列表中。默认根据名称来注入(buName)。
基本类型数据参数
@Controller
public class FirstController {
// 请求localhost:8080/project/demo?name=abc&age=99
@RequestMapping("demo")
public String demo(String name, int age) {
// 请求中的 name 和 id的值会自动注入
System.out.println(name + " " + age);
return "/test.jsp";
}
}
接收参数名和方法中的参数不对应时,使用@RequestParam注解
@RequestParam写在方法的参数列表,如果不设置value时,默认是方法参数名对应请求参数key。@RequestParam可以设置value、defaultValue、required三个属性,分别代表:
// 请求localhost:8080/project/demo?name=abc&age=99
@RequestMapping("demo")
public String demo(@RequestParam String name,@RequestParam int age)
如果当请求参数和方法参数不对应时,设置注解的值
// 请求localhost:8080/project/demo?name11=abc&age11=99
@RequestMapping("demo")
public String demo(@RequestParam("name11") String name,@RequestParam("age11") int age)
设置默认值
// 请求localhost:8080/project/demo?name11=abc&age=99
@RequestMapping("demo")
public String demo(@RequestParam(value="name11", defaultValue="aaa") String name,int age)
设置请求中必须传递了某个参数,使用required=true,默认是false。注意,required和defaultValue不要同时出现,否则required就相当于设置为false。
// 请求localhost:8080/project/demo?name=abc&age=99
@RequestMapping("demo")
public String demo(@RequestParam(value="name", required=false) String name,int age)
接收对象引用类型,比如Person对象
Spring MVC根据请求中的参数,去Person对象中的属性值进行匹配,如果匹配的上,就将请求中传递的值,通过调用对象的setter,注入到对象中
package cn.ganlixin.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import cn.ganlixin.pojo.Person; @Controller
public class FirstController {
// 请求localhost:8080/project/demo?name=abc&age=99
@RequestMapping("demo")
public String demo(Person person) {
System.out.println(person); // Person [age=99, name=abc]
return "/test.jsp";
}
}
接收复选框这种多个同名参数
因为checkbox的name值都是相同的,所以后端程序在接收的时候需要使用List集合(不能用数组,因为长度未知),并且需要用@RequestParam注解写明方法参数接收哪一个key(这里不能让他自动注入,需要指定一下)。
package cn.ganlixin.controller; import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; @Controller
public class FirstController {
// 请求localhost:8080/project/demo?hobbies=swimming&hobbies=basketball
@RequestMapping("demo")
public String demo(@RequestParam("hobbies") List<String> hobbies) {
System.out.println(hobbies); // [swimming, basketball]
return "/test.jsp";
}
}
接收obj.field格式的数据
假设请求localhost:8080/project/demo?person.name=abc&person.age=99,参数是person.name和person.age这种格式,可以创建一个类,包含一个名称为person的属性。Spring MVC会自动进行注入:
比如创建了一个Demo类,包含一个private Person person属性,则下面的代码就可以正常运行:
package cn.ganlixin.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import cn.ganlixin.pojo.Demo; @Controller
public class FirstController {
// 请求localhost:8080/project/demo?person.name=abc&person.age=99
@RequestMapping("demo")
public String demo(Demo d) {
System.out.println(d);
// Demo [person=Person [age=99, name=abc]]
return "/test.jsp";
}
}
接收RESTful方式的参数
restful传值方式比如:/project/demo/abc/99,解析为name为abc,id为99。
@RequestMapping的占位符和方法参数相同
package cn.ganlixin.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class FirstController {
// 请求http://localhost:8080/project/demo/abc/99
@RequestMapping("demo/{name}/{id}")
public String demo(@PathVariable String name, @PathVariable Integer id) {
System.out.println(name + " " + id); // abc 99
return "/test.jsp";
}
}
@RequestMapping的占位符和方法参数不相同
package cn.ganlixin.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class FirstController {
// 请求http://localhost:8080/project/demo/abc/99
@RequestMapping("demo/{name11}/{id}")
public String demo(@PathVariable("name11") String name, @PathVariable Integer id) {
System.out.println(name + " " + id); // abc 99
return "/test.jsp";
}
}
Spring MVC四大作用域传值
jsp有9大内置对象
| 内置对象名 | page | request | response | session | application | out | config | pageConfig | exception |
| 数据类型 | Object | HttpServletRequest | HttpServletResponse | HttpSession | ServletContext | PrintWriter | ServletConfig | PageContext | Exception |
四大作用域对象
在jsp中,四大作用域对象分别是page、request、session、application。但是在servlet中,并没有专门的对象对page对应的对象进行操作。如果我们在servlet要对这几个对象进行操作,可以直接创建该类的对象即可,进行Xxx.setAttirbute(str, obj)进行设置值等操作。
Spring MVC进行注入request、response、session
下面是一个简单的controller:
@Controller
public class FirstController {
// 请求localhost:8080/project/demo?name=abc&age=99
@RequestMapping("demo")
public String demo(String name, int age) {
// 请求中的 name 和 id的值会自动注入
System.out.println(name + " " + age);
return "/test.jsp";
}
}
注意,上面的FirstController类并没有像以前写servlet一样继承HttpServlet,所以,我们写的controller并不是servlet,需要注意这一点。
Spring MVC进行作用域对象注入与传值
前面已经举了那么多Spring MVC在HandlerMethod中进行参数值的注入,其实对于四个内置作用域对象,通过Spring MVC也是可以进行注入的,不过需要注意的是,application对象(servlet中对应ServletContext不能进行注入):
package cn.ganlixin.controller; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class SecondController { @RequestMapping("test")
// 在HandlerMethod中直接写明参数的类型,参数名随意,Spring MVC会自动进行注入
public String test(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
request.setAttribute("key", "value of requestParameter");
response.setStatus(200);
session.setAttribute("key", "value of session"); // ServletContext不能进行注入,但是可以通过request对象进行获取
ServletContext servletContext = request.getServletContext();
servletContext.setAttribute("key", "value of servletContext"); return "/test.jsp";
}
}
上面的代码中,request、session和servletContext对象进行了数据操作(是在servlet中完成的操作),在jsp中,可以通过下面几个语句分别获得各自作用域的值:
${requestScope.key }
${sessionScope.key }
${applicationScope.key }
Spring MVC使用Map进行作用域传值
上面通过了四大作用域对象进行传值,除此之外,Spring MVC也可以通过Map进行传值,方式就是将HandlerMethod的参数设置为Map即可,通过该方式传值,默认是将参数放到request作用域中:
@RequestMapping("test2")
public String test2(Map<String, Object> mapData) {
// 直接往map中put值即可,默认是放到request作用域中
mapData.put("key", "value of Map");
return "/test.jsp";
}
因为通过map进行传值,是放到request作用域中,所以在jsp中,可以使用${key}或者${requestScope.key}来获取map中put的值。
Spring MVC使用Model进行作用域传值
使用Model和使用Map的方式其实是一样的,添加到model中的数据,都是放到request作用域中。访问方式和上面map的访问方式相同。
@RequestMapping("test3")
public String test3(Model model) {
model.addAttribute("key", "value of model");
return "/test.jsp";
}
Spring MVC使用ModelAndView进行作用域传值
使用ModelAndView进行传值,可能和前面的几种方式不同,因为ModelAndView从名称上就可以看出这个类包含Model和View,在使用时有两个注意点:
1、HandlerMethod参数列表不需要ModelAndView类型的参数(不进行注入),需要在HandlerMethod中创建一个ModelAndView对象。
2、HandlerMethod中,直接将数据添加到ModelAndView对象中即可。
3、HandlerMethod的返回值要设置为ModelAndView类型,就是将HandlerMethod内部创建的ModelAndView返回即可。
4、ModelAndView中的数据,也是在request作用域中。
示例如下:
@RequestMapping("test4")
public ModelAndView test4() {
// 创建ModelAndView对象时,需要传入一个字符串(视图名)
ModelAndView mav = new ModelAndView("/test.jsp");
mav.addObject("key", "value of ModelAndView");
return mav; // 直接返回ModelAndView对象即可
}
SpringMVC 接受请求参数、作用域传值的更多相关文章
- SpringMvc接受请求参数的几种情况演示
说明: 通常get请求获取的参数是在url后面,而post请求获取的是请求体当中的参数.因此两者在请求方式上会有所不同. 1.直接将接受的参数写在controller对应方法的形参当中(适用于get提 ...
- SpringMVC接受请求参数、
1. 接收请求参数 1.1. [不推荐]通过HttpServletRequest 在处理请求的方法中,添加HttpServletRequest对象作为参数,在方法体中,直接调用参数对象的getPara ...
- Springmvc之接受请求参数二
Springmvc之接受请求参数 准备工作 新建一个表单提交 请求地址: http://localhost:8080/ProjectName/user/login.do <form action ...
- SpringMVC接受JSON参数详解及常见错误总结我改
SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session了,想感受一下Token这样比较安全,稳健的方式,顺便写一个统一的接口给浏览器还有APP.所以把一个练手项目的前 ...
- SpringMVC接受JSON参数详解及常见错误总结
SpringMVC接受JSON参数详解及常见错误总结 SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session了,想感受一下Token这样比较安全,稳健的方式,顺便写一 ...
- SpringMVC接受JSON参数详解
转:https://blog.csdn.net/LostSh/article/details/68923874 SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session ...
- 16 SpringMVC 的请求参数的绑定与常用注解
1.SpringMVC 绑定请求参数 (1)支持的数据类型 基本类型参数: 包括基本类型和 String 类型POJO 类型参数: 包括实体类,以及关联的实体类数组和集合类型参数: 包括 List 结 ...
- struts2接受请求参数
https://blog.csdn.net/y249839817/article/details/77702745 https://blog.csdn.net/nthack5730/article/d ...
- SpringMVC之请求参数的获取方式
转载出处:https://www.toutiao.com/i6510822190219264516/ SpringMVC之请求参数的获取方式 常见的一个web服务,如何获取请求参数? 一般最常见的请求 ...
随机推荐
- css两列布局之基于BFC规则实现
css要实现常见的自适应两列布局的方式方法挺多. 这里讲的是利用设置overflow不为visible时会形成新的BFC来实现.至于什么是BFC,可以搜搜看先,基本都讲的差不多了.等有更多空余时间,专 ...
- python接口自动化(四)--接口测试工具介绍(详解)
简介 “工欲善其事必先利其器”,通过前边几篇文章的介绍,大家大致对接口有了进一步的认识.那么接下来让我们看看接口测试的工具有哪些. 目前,市场上有很多支持接口测试的工具.利用工具进行接口测试,能够提供 ...
- ToastCustomUtil【简单的Toast封装类】【自定义Toast的显示风格】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 ToastUtil + ToastCustom结合.主要解决低版本机型上系统toast显示不好看的问题. 效果图 代码分析 在Toa ...
- js实现二分查找算法
二分查找:是一种搜索某个值的索引的算法. 基本条件:有序的数组. 思路:1.将数组折半,分成左右两个数组. 2.判断要查找的数和中间位置数值的大小,来判断要查找的数实在哪一半. 3.之后继续折半查找, ...
- JavaScript夯实基础系列(一):词法作用域
作用域是一组规则,规定了引擎如何通过标识符名称来查询一个变量.作用域模型有两种:词法作用域和动态作用域.词法作用域是在编写时就已经确定的:通过阅读包含变量定义的数行源码就能知道变量的作用域.Jav ...
- [Flashback]开启数据库闪回数据库功能
Flashback是Oracle中一个重要的功能,想要使用闪回数据库功能,需要将数据库置于闪回数据库的状态. 1.检查数据库是否开启归档状态 SQL> archive log list; Dat ...
- EF 外键不显示、如何让外键显示!增、删、改 操作时,外键不显示,只显示导航属性!
一.问题描述:EF 外键不显示.如何让外键显示!增.删.改 操作时,外键不显示,只显示导航属性! EF 添加.增加.插入数据时,外键不显示! 二.解决方案:在根据数据库生成模型的时候,选中“在模型中” ...
- SpringBoot 2.0 mybatis mapper通用类
<!---mybatis通用类包含mybatis和连接池 mybatis和连接池就不需要引入--> <dependency> <groupId>tk.mybatis ...
- Oracle数据库的安装 【超详细的文图详解】
Oracle简介Oracle Database,又名Oracle RDBMS,或简称Oracle.是甲骨文公司的一款关系数据库管理系统.它是在数据库领域一直处于领先地位的产品.可以说Oracle数据库 ...
- h5与c3权威指南笔记--css3新属性选择器
[att*=val] 选择所有att属性值中包含val的.只要包含val值,不论val值在属性值的前面还是中间还是后面~ <style> div[class*=div]{ color: r ...