JAVA Controller 获取请求数据的方式汇总

2021/6/6 12:22:50

本文主要是介绍JAVA Controller 获取请求数据的方式汇总,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

本文不做底层理论知识的汇总,仅将多数获取数据的方式做应用层面的汇总与验证。
其中,文件数据的获取,另文再写~

其中请求方式,仅测试了 GET 和 POST 方法;

请求头信息,仅测试了 multipart/form-data 与 application/x-www-form-urlencoded

通过路由获取

@RequestMapping(value="/test/{id}/{name}", method= {RequestMethod.GET, RequestMethod.POST})
public String test(@PathVariable int id, @PathVariable(name="name") String userName){
    
}

说明:如果 @PathVariable 不使用 name 参数指定名称,则必须和路由中的一致,否则会抛出异常;所指定的参数值,也不可为空。

传统方式获取

@RequestMapping(value="/test1", method= {RequestMethod.GET, RequestMethod.POST})
public String test1(HttpServletRequest request){
    String param1 = request.getParameter("param1"), // url 参数
        form1 = request.getParameter("form1"), //form-data
        //x-www-form-urlencoded
        encoded1 = request.getParameter("encoded1");
        
    String[] params = request.getParameterValues("params"), 
        forms = request.getParameterValues("forms"), 
        encodeds = request.getParameterValues("encodeds");
}

说明:

  • 通过在不同位置添加测试键,来读取数据。结果表明:当请求头为 form-data 时,GET 和 POST 都能获取到 url 和 data 中的数据;当请求头为 x-www-form-urlencoded 时,GET 请求获取不到 data 中的数据。
  • 数组值获取,只是使用的方法不同。请求时,参数名为一致。如果用 getParameter 获取同名参数,则只会返回第一个值。
  • 数组值另外一种形式的获取,可以在前端中将数组 JSON.stringify()包装后作为单值发送,后端用 JSON 方式解码为数组,这通常可用于一些前端多选的操作。

请求参数注解方式获取

@RequestMapping(value="/test2", method= {RequestMethod.GET, RequestMethod.POST})
public String test2(@RequestParam(name = "name", defaultValue="noname", required=true) String userName){
    // 仅获取单个值
}

@RequestMapping(value="/test2_1", method= {RequestMethod.GET, RequestMethod.POST})
public String test2_1(@RequestParam Map<String, Object> params) {
    // 获取集合
}

说明:@RequestParam 注解可以简单的获取参数值。但是当请求方法为 GET,请求头又为 x-www-form-urlencoded 时,获取不到值。

请求体注解方式获取

@RequestMapping(value="/test3", method= {RequestMethod.GET, RequestMethod.POST})
public String test3(@RequestBody String body) {
    
}

说明:@RequestBody 注解仅适用于 x-www-form-urlencoded 的请求方式,会将请求参数组合为 & 连接的字符串;如果请求方式为 POST 时,会将 URL 中的参数一起打包进字符串。

特殊注解类

@RequestMapping(value="/test4", method= {RequestMethod.GET, RequestMethod.POST})
	public String test4(@RequestHeader(name = "headername", required=false) String headervalue, @CookieValue(name = "cookiename", required=false) String cookievalue){
}

说明:可直接获取头信息和 cookie 信息。

对象参数方式获取

@RequestMapping(value="/test5", method= {RequestMethod.GET, RequestMethod.POST})
public String test5(Person person){
    // person.getId()
    // person.getName()
}

说明:对象参数的形式,可以获取包含所有与参数类属性同名的值;例如:{'name': 'Gary'}。但是当请求方法为 GET,请求头又为 x-www-form-urlencoded 时,获取不到值。



这篇关于JAVA Controller 获取请求数据的方式汇总的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程