javaweb接收数据及接受方式
1 获取请求头数据
1.0 Usage
package com.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;import org.springframework.ui.ModelMap;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import java.io.*;
import java.net.URLDecoder;import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Enumeration;@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/api")
public class HelloController{/*** Get request header informations, and return data in Map format.*/@RequestMapping(value="/return-header-map", method=RequestMethod.POST)@ResponseBody public Map retrunMap(HttpServletRequest req, HttpServletResponse res){Map<String, String> headerInfos = new HashMap<String, String>();Map<String, String> headerKV = new HashMap<String, String>();Enumeration<String> headerNames = req.getHeaderNames();System.out.format("header names: "+headerNames+"\n");headerInfos.put("method", req.getMethod());headerInfos.put("context", req.getContextPath());// headerInfos.put("headers", req.getHeaders("host"));headerInfos.put("Auth-type", req.getAuthType());return headerInfos;}/*** Get request header infomations, and return List format data.*/@RequestMapping(value="/return-header-list", method=RequestMethod.POST)@ResponseBody public List returnList(HttpServletRequest req, HttpServletResponse res){Map headerKV = new HashMap();Map outputInfos = new HashMap();List inputInfos = new ArrayList();List headerInfos = new ArrayList();outputInfos.put("name", "huahua");outputInfos.put("address", "shenzhen");inputInfos.add(outputInfos);headerKV.put("input", inputInfos);String defineHeader = req.getHeader("Authorization");headerKV.put("authorization", defineHeader);Enumeration<String> headerNames = req.getHeaderNames();while(headerNames.hasMoreElements()){String nextElement = headerNames.nextElement();headerKV.put(nextElement, req.getHeader(nextElement));}System.out.format("header key-value: "+headerKV+"\n");// inputInfos.add(headerKV);System.out.format("input infos: "+inputInfos+"\n");// headerKV.put("input", inputInfos);headerInfos.add(headerKV);return headerInfos;}
}
1.2 返回结果
- List
[{"authorization": "Authorization","input": [{"address": "shenzhen","name": "huahua"}],"content-length": "0","postman-token": "ec660634-fd23-4828-b6ac-8b4dfcbe2a1e","host": "localhost:8080","connection": "keep-alive","cache-control": "no-cache","accept-encoding": "gzip, deflate","user-agent": "PostmanRuntime/7.2.0","accept": "*/*"}
]
- Map
{"method": "POST","context": "/ssmPureBackend","headerNamesAndValue": {"content-length": "0","postman-token": "e53604b7-051e-4089-95e3-3efc04303726","host": "localhost:8080","connection": "keep-alive","cache-control": "no-cache","accept-encoding": "gzip, deflate","user-agent": "PostmanRuntime/7.2.0","accept": "*/*"},"Auth-type": null
}
2 javaweb接收请求提数据方式
2.1 GET
参数类型 | 获取参数方式 |
---|---|
URI请求参数 | HttpServletRequest.getParameter(“parameter_name”) |
2.2 POST
序号 | 参数类型 | 获取参数 | 描述 |
---|---|---|---|
1 | x-www-form-urlencode | @RequestBody variableName | 传递x-www-form-urlencode数据 |
1 | x-www-form-urlencode | @RequestParam(“variableName”) variableName | 传递x-www-form-urlencode数据 |
2 | json | HttpServletRequest.getInputStream | 传递json数据 |
3 | class-json | @RequestBody className objectName | 传递class参数,解析为json |
4 | class-map | @RequestBody className objectName | 传递class参数,赋值给Map变量 |
5 | map | @RequestBody Map variableName | 传递Map参数 |
6 | list | @RequestBody List variableName | 传递List参数 |
Java语言的Map,List集合,对应json形式的数据,若输入或输出json数据,将数据整合为Map结合即可.
json数据:JSON格式数据解析
2.3 获取请求体数据
2.3.1 entity/Info.java
package com.hello.entity;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;//使用lombok插件,可不用写setter和getter
@Data
@Accessors(chain = true)
@Builder
public class Info {private String name;private String sex;private String cellphone;public void setName(String name){this.name = name;}public String getName(){return name;}public void setSex(String sex){this.sex =sex;}public String getSex(){return sex;}public Info(){}public Info(String name, String sex, String cellphone){this.name = name;this.sex = sex;this.cellphone = cellphone;}
}
2.3.2 controller/HelloController.java
package com.hello;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;import org.springframework.ui.ModelMap;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;import java.io.*;
import java.net.URLDecoder;import com.hello.entity.Info;
import java.util.Map;
import java.util.HashMap;
import java.util.List;@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/api")
public class HelloController{@RequestMapping(value="/datas", method=RequestMethod.GET)// @ResponseBodypublic String printHello(HttpServletRequest request, Model model){model.addAttribute("message", "Hello Spring MVC Framework!");// return "hello";return "hello";}/*** URI paramter received.* @param request: parameter request object* @param model: database model object* @return name: user name*/@RequestMapping(value="/get-infos", method=RequestMethod.GET)@ResponseBodypublic String returnString(HttpServletRequest request, Model model){String name = request.getParameter("name");System.out.println("name:"+name);// String address = request.getParameter("address");return name;}/*** x-www-form-urlencode parameter received.* @param name: variable* @param address: variable* @return name*/@RequestMapping(value="/post-infos", method=RequestMethod.POST)@ResponseBodypublic String returnJson(@RequestBody String name, @RequestBody String address){System.out.println("data: "+name);// String address = request.getParameter("address");return name;}public static String getType(Object o){return o.getClass().toString();}/*** Transfer json data and parse it directly.* @param request: request object* @return request body*/@RequestMapping(value="/post-json", method=RequestMethod.POST)@ResponseBodypublic String loadJson(HttpServletRequest request){BufferedReader br;StringBuilder sb = null;String reqBody = null;try{br = new BufferedReader(new InputStreamReader(request.getInputStream()));String line = null;sb = new StringBuilder();while ((line = br.readLine()) != null ){sb.append(line);}reqBody = URLDecoder.decode(sb.toString(), "UTF-8");reqBody = reqBody.substring(reqBody.indexOf("{"));request.setAttribute("inputParam", reqBody);System.out.println("JsonRequest :"+reqBody);System.out.println("Type of request data:"+getType(reqBody));return reqBody;} catch (IOException e){e.printStackTrace();return "jsonerror";}}/*** Received parameter within Class entity.* @param info: object* @return object*/@RequestMapping(value="/post-class", method=RequestMethod.POST)@ResponseBodypublic Info loadClass(@RequestBody Info info){System.out.println("info:"+info);System.out.println("info type:"+getType(info));System.out.println("name:"+info.getName());String compare_name = "hello";// info.setName("xiaohong");System.out.println("source name: "+info.getName());System.out.println("source name type: "+getType(info.getName()));if(info.getName().equals(compare_name)){info.setName("xiaohong");System.out.println("judge name: "+info.getName());}else{System.out.println("Name changed error");}System.out.println("After name changed:"+info.getName());return info; }/*** Create class and set parameter.* @return*/@RequestMapping(value="/post-class-new", method=RequestMethod.POST)@ResponseBodypublic Info classNew(){Info info = new Info();info.setSex("male");return info;}/*** Parsing json data with class entity.* @param info* @param request* @return*/@RequestMapping(value="/post-class-json", method=RequestMethod.POST)@ResponseBodypublic String classJson(@RequestBody Info info, HttpServletRequest request){request.setAttribute("test_name", info.getName());String test_name = info.getName();return test_name;}/*** Parsing json data with class entity and received with map data. * @param info* @return*/@RequestMapping(value="/post-class-map", method=RequestMethod.POST)@ResponseBodypublic Map<String, String> classMap(@RequestBody Info info){Map<String, String> datas = new HashMap<String, String>();datas.put("username", info.getName());datas.put("sex", info.getSex());System.out.println("datas:"+datas);return datas;}/*** Tranfering map data.* @param map* @return*/@RequestMapping(value="/post-map", method=RequestMethod.POST)@ResponseBodypublic String postMap(@RequestBody Map<String, String> map){String name = "hello";String sex = "male";if(map.containsKey("name")){name = map.get("name").toString();}if(map.containsKey("sex")){sex = map.get("sex").toString();}return name;}/*** Transfering list data.* @param lists* @return*/@RequestMapping(value="/post-list", method=RequestMethod.POST)@ResponseBodypublic List<Info> postList(@RequestBody List<Info> lists){for(Info info : lists){System.out.println("data:"+info.toString());}return lists;}/*** Transfering x-www-from-urlencode data.* @param name* @return*/@RequestMapping(value="/post-param", method=RequestMethod.POST)@ResponseBodypublic String postParam(@RequestParam("name") String name){System.out.println("name:"+name);return name;}
}
【参考文献】
[1]https://www.cnblogs.com/zzsuje/articles/10329948.html
[2]https://www.cnblogs.com/dwp1216/p/10381858.html
[3]https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletRequest.html
javaweb接收数据及接受方式相关推荐
- STM32串口中断的4种接收数据的实现方式
本例程通过PC机的串口调试助手将数据发送至STM32,接收数据后将所接收的数据又发送至PC机. 实例一: void USART1_IRQHandler(u8 GetData) {u8 BackData ...
- linux内核网络协议栈--监控和调优:接收数据(十五)
译者序 本文翻译自 2016 年的一篇英文博客 Monitoring and Tuning the Linux Networking Stack: Receiving Data.如果能看懂英文,建议阅 ...
- C#中POST数据和接收的几种方式
POST方式提交数据,一种众所周知的方式: html页面中使用form表单提交,接收方式,使用Request.Form[""]或Request.QueryString[" ...
- Linux下TCP循环接收数据的方式
简介 服务器调用accept与客户端建立连接,连接建立成功后,会返回一个fd,表示这条了连接的文件描述符.之后调用recv函数接受连接的信息.根据recv函数的原型,需要服务器程序有一个接收缓冲区,实 ...
- php数据接受数据,php接收数据
PHP默认只识别application/x-www.form-urlencoded标准的数据类型. 因此,对型如text/xml 或者 soap 或者 application/octet-stream ...
- STM32串口发送数据和接收数据方式总结
文章目录 串口发送数据 串口接受数据 串口发送数据 1.串口发送数据最直接的方式就是标准调用库函数 . void USART_SendData(USART_TypeDef* USARTx, uint1 ...
- MVCAction接收数据方式
1.Model接收,Model接收的好处就是会自动帮我们填充数据 无论是GET方式还是post都能自动填充 2.FormCollection 只能接收From表单的值也就是只能接收POST 他的好处就 ...
- php后端接收数据,后端如何接收fetch方式发送的数据?
fetch方法借助FormData对象模拟表单的请求 这样能够实现完整的HTTP请求,而后端也能够像表单样接收数据 //前端 var formdata = new FormData(); formda ...
- 控制器中接收数据的四种方式
控制器中接收数据的四种方式: (仅限于个别的方式(get/post)有效) 通过形参的方式接收表单提交的数据(可以接收post与get提交的数据): 注释: GetData自己定义的方法名里面存入形参 ...
最新文章
- RHCE认证培训+考试七天实录(二)
- adb安装apk是出现INSTALL_FAILED_INSUFFICIENT_STORAGE
- 蓝桥杯 算法提高 递推求值(矩阵快速幂)详解
- 在语言中的运算符中,处于同一优先级别的运算符还分优先次序吗?
- 服务器站点解密出错,修改域超级管理员密码后站点复制出错。
- jar包直接拷贝到WEB-INF/lib下和以userLibrary引入的区别
- 实验人员考评指标_了解实验指标
- 6、控件样式模板和使用
- html如何查找文件,如何查找网站上HTML的CLASS文件并下?如何查找网站上HTM 爱问知识人...
- vijos1364:Likecloud-吃吃吃
- 深度学习笔记_ResNet
- Fatal error: Uncaught Error: Call to undefined function gzinflate()
- 笨办法学python3 视频打包_正版 笨办法学Python 3 进阶篇+笨办法 学Python 3 视频教学 笨方法学Python核...
- Windows应用替代方案接龙
- python之论文降重工具
- PMP第三节:项目管理过程
- 【蓝桥杯练习-PWM脉宽调制】
- 读《红楼梦》和《百年孤独》后关于爱、孤独和回忆的一点体会
- 【历史上的今天】1 月 23 日:现代集成电路雏形;JDK 1.0 发布;数学大师诞生
- 极客兔兔 TensorFlow入门教程