目录


原生servlet接收参数

Spring MVC最基础的参数获取

接收基本数据类型参数

方法参数列表和请求参数不一致的处理方式

接收对象引用数据类型

接收复选框这种多个同名的参数

接收obj.field格式的数据

接收RESTful方式的参数

占位符和方法参数同名时

占位符和方法参数不同名时

Spring MVC进行四大作用域传值

jsp九大内置对象

四大作用域对象

Spring MVC进行作用域对象的注入与传值

Spring MVC使用Map进行作用域传值

Spring MVC使用Model进行作用域传值

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 接受请求参数、作用域传值的更多相关文章

  1. SpringMvc接受请求参数的几种情况演示

    说明: 通常get请求获取的参数是在url后面,而post请求获取的是请求体当中的参数.因此两者在请求方式上会有所不同. 1.直接将接受的参数写在controller对应方法的形参当中(适用于get提 ...

  2. SpringMVC接受请求参数、

    1. 接收请求参数 1.1. [不推荐]通过HttpServletRequest 在处理请求的方法中,添加HttpServletRequest对象作为参数,在方法体中,直接调用参数对象的getPara ...

  3. Springmvc之接受请求参数二

    Springmvc之接受请求参数 准备工作 新建一个表单提交 请求地址: http://localhost:8080/ProjectName/user/login.do <form action ...

  4. SpringMVC接受JSON参数详解及常见错误总结我改

    SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session了,想感受一下Token这样比较安全,稳健的方式,顺便写一个统一的接口给浏览器还有APP.所以把一个练手项目的前 ...

  5. SpringMVC接受JSON参数详解及常见错误总结

    SpringMVC接受JSON参数详解及常见错误总结 SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session了,想感受一下Token这样比较安全,稳健的方式,顺便写一 ...

  6. SpringMVC接受JSON参数详解

    转:https://blog.csdn.net/LostSh/article/details/68923874 SpringMVC接受JSON参数详解及常见错误总结 最近一段时间不想使用Session ...

  7. 16 SpringMVC 的请求参数的绑定与常用注解

    1.SpringMVC 绑定请求参数 (1)支持的数据类型 基本类型参数: 包括基本类型和 String 类型POJO 类型参数: 包括实体类,以及关联的实体类数组和集合类型参数: 包括 List 结 ...

  8. struts2接受请求参数

    https://blog.csdn.net/y249839817/article/details/77702745 https://blog.csdn.net/nthack5730/article/d ...

  9. SpringMVC之请求参数的获取方式

    转载出处:https://www.toutiao.com/i6510822190219264516/ SpringMVC之请求参数的获取方式 常见的一个web服务,如何获取请求参数? 一般最常见的请求 ...

随机推荐

  1. Capacitor 新一代混合应用“神器” 会代替Cordova吗??

    1.介绍or畅想 Capacitor是由ionic团队最新开发维护的一个跨平台的应用程序容器,可以轻松构建在iOS,Android,Electron 和 Web 上本机运行的Web应用程序.我们称这些 ...

  2. 中缀表达式得到后缀表达式(c++、python实现)

    将中缀表达式转换为后缀表达式的算法思想如下: 从左往右开始扫描中缀表达式 遇到数字加入到后缀表达式 遇到运算符时: 1.若为‘(’,入栈 2.若为’)‘,把栈中的运算符依次加入后缀表达式,直到出现'( ...

  3. OO Unit2多线程电梯总结博客

    OO Unit2多线程电梯总结博客 传说中的电梯居然就这样写完了-撒花

  4. C++ 编译期封装-Pimpl技术

    Pimpl技术——编译期封装 Pimpl 意思为“具体实现的指针”(Pointer to Implementation), 它通过一个私有的成员指针,将指针所指向的类的内部实现数据进行隐藏, 是隐藏实 ...

  5. Scss预处理器的使用总结

    变量 .嵌套.Mixin混合.function函数.插值 变量及文件导入 通过$定义变量 $white:#fff; $black:#000; 变量引用 .containner{ color:$blac ...

  6. 浅谈Google Chrome浏览器(操作篇)(上)

    开篇概述 在上篇博客中详解Google Chrome浏览器(理论篇)一文中,主要讲解了Chrome 搜索引擎使用.Chrome安装和基本操作.Chrome 基本架构.多线程等原理性问题,这篇将重点讲解 ...

  7. [SpringBoot guides系列翻译]调用RESTfulWebService

    原文 参考链接 CommandLineRunner Bean 翻译如何调用RESTful WebService 这节将演示如何在SpringBoot里面调用RESTful的WebService. 构建 ...

  8. Java 插入附件到PDF文档

    在文档中插入附件,可以起到与源文档配套使用的目的,以一种更简便的方式对文档起到补充说明的作用.下面将介绍通过Java编程插入附件到PDF文档中的方法.这里插入的文档可以是常见的文档类型,如Word.E ...

  9. JS之BOMBOM!

    什么是BOM? bom即browser object model 也就是浏览器对象模型,BOM由多个对象组成,其中代表浏览器窗口的window对象是BOM的顶层对象,其他对象都是该对象的子对象. 顶层 ...

  10. (详细)华为荣耀4X CHE-TL00H的usb调试模式在哪里打开的步骤

    每当我们使用PC通过数据线链上安卓手机的时候,如果手机没有开启usb开发者调试模式,PC则没能成功读到我们的手机,有时,我们使用的一些功能较强的工具好比之前我们使用的一个工具引号精灵,老版本就需要打开 ...