HttpServletRequest

 1 @Override
 2     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 3 
 4         /*解决请求乱码*/
 5         request.setCharacterEncoding("UTF-8");
 6 
 7         /*常用方法*/
 8         /*获取项目名*/
 9         System.out.println("项目名:"+request.getContentType());
10         /*获取客户机的地址*/
11         System.out.println("客户机的地址:" + request.getRemoteAddr()+":"+request.getRemotePort());
12 
13         /*获取请求头的信息*/
14 
15         /*获取请求方式是*/
16         System.out.println("请求方式:"+request.getMethod());
17 
18         /*获取请求的web项目名*/
19         System.out.println("web项目名:"+request.getContextPath());
20 
21         /*获取指定名称请求头*/
22         System.out.println("User-Agent头:"+request.getHeader("User-Agent"));
23 
24         /*获取所有的请求头的key*/
25         Enumeration<String> headerNames = request.getHeaderNames();
26         while (headerNames.hasMoreElements()) {
27             String s = headerNames.nextElement();
28             System.out.println(s + ":" + request.getHeader(s));
29         }
30 
31 
32         /*获取请求体的信息*/
33         /*获取参数的Map集合*/
34         Map<String, String[]> parameterMap = request.getParameterMap();
35         Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
36         for (Map.Entry<String, String[]> s : entries) {
37             String key = s.getKey();
38             String[] val = s.getValue();
39             System.out.println(key + ":" + Arrays.toString(val));
40         }
41 
42         /*获取数据*/
43         String name = request.getParameter("name");
44         String pwd = request.getParameter("pwd");
45         System.out.println(name + ":" + pwd);
46 
47 
48         /*request的域对象*/
49         /*声明周期:一次请求*/
50         request.setAttribute("name","杨淏宇");
51         System.out.println(request.getAttribute("name"));
52         /*请求转发*/
53         /*注意请求转发的路径不需要写项目名称*/
54         request.getRequestDispatcher("/demo.jsp").forward(request,response);
55         /*请求转发和重定向的区别:
56         * 请求转发:请求服务器一次,地址栏不发生变化,适用于有参数的时候,服务器行为
57         * 重定向:请求服务器两次,地址栏发生变化,使用于无参数的时候,浏览器行为
58         */
59 
60     }
61 
62     @Override
63     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
64         doPost(request, response);
65     }

  注意:tomcat 8 后不用解决请求乱码:

    之前post用:request.setCharacterEncoding("UTF-8");

      get用:parameter = new String(parameter.getBytes(“iso8859-1”),”UTF-8”); 注意只能解决一个乱码

posted @ 2019-11-09 22:08  养一只Tom猫  阅读(157)  评论(0编辑  收藏  举报