Request获取请求体数据和Request获取请求参数通用方式介绍
Request获取请求体数据
获取请求体数据:
请求体:只要POST请求方式,才有请求体,在请求体中封装了POST请求的请求参数
步骤:
1.获取流对象
BufferedReader getReader():获取字符输入流,只能操作字符数据
ServletInputStream getInputStream():获取字节输入流,可以操作所有类型数据
2.再从流对象中拿数据
regist.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册页面</title> </head> <body> <form action="/servlet/requestD5" method="post"> <input type="text" placeholder="请输入用户名" name="username"><br> <input type="text" placeholder="请输入密码" name="password"> <input type="submit" value="注册"> </form> </body> </html>
@WebServlet("/requestD5") public class RequestD5 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求消息体 //获取字符流 BufferedReader br = request.getReader(); //读取数据 String len = null; while ((len=br.readLine())!=null){ System.out.println(len); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
Request获取请求参数通用方式介绍
1.获取请求参数通用方式:
1.String getParameter(String name):根据参数名称获取参数值
2.String[] getParameterValues(String name):根据参数名称获取参数值的数组 hobby=xx&hobby=game
3.Enumeration<String> getParameterNames():获取所有请求的参数名称
4.Map<String,String[]> getParameterMap():获取所有参数的map集合
Request获取请求参数通用方式演示
@WebServlet("/requestD6") public class RequestD6 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //post获取请求参数 //根据参数名称获取参数值 String username = request.getParameter("username"); /*System.out.println("post"); System.out.println(username);*/ //根据参数名称获取参数值的数组 String[] hobbies = request.getParameterValues("hobby"); /*for (String hobby : hobbies) { System.out.println(hobby); }*/ //获取所有请求的参数名称 Enumeration<String> parameterNames = request.getParameterNames(); /*while (parameterNames.hasMoreElements()){ String name = parameterNames.nextElement(); System.out.println(name); String value = request.getParameter(name); System.out.println(value); System.out.println("--------------"); }*/ //获取所有参数的map集合 Map<String, String[]> parameterMap = request.getParameterMap(); //遍历 Set<String> keyset = parameterMap.keySet(); for (String name : keyset) { //获取键获取值 String[] values = parameterMap.get(name); System.out.println(name); for (String value : values) { System.out.println(value); } System.out.println("-------------"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*String username = request.getParameter("username"); System.out.println("post"); System.out.println(username);*/ this.doPost(request, response); } }
根据参数名称获取参数值的数组
获取所有请求的参数名称
hobby只获取了一个要获取多个需要返回数组
获取所有参数的map集合
可以完全获取全部数据
Request获取请求参数中文乱码问题处理
会出现乱码
get方式:tomcat 8 已经将get方式乱码问题解决了
post方式:会乱码
解决:在获取参数前,设置request的编码:request.setCharacterEncoding("utf-8");
就可以解决掉了