javaweb—HttpServletRequest和HttpServletResponse对象

**GETPOST提交

主要区别:

# 1Get是用来从服务器上获得数据,而Post是用来向服务器上传递数据。例如我们访问网站都是Get方式,而我们的图像上传则是Post
# 2Get将表单中数据的按照variable=value的形式,添加到action所指向的URL后面,并且两者使用“?”连接,各个变量之间使用“&”连接;Post是将表单中的数据放在form的实体内容中,按照变量和值相对应的方式,传递到action所指向URL
# 3
Get是不安全的,因为数据被放在请求的URL中。Post的所有操作对用户来说都是不可见的。
# 4
Get传输的数据量小,一般小于1K;而Post可以传输大量的数据。
# 5
Get限制Form表单的数据集的值必须为ASCII字符;而Post支持整个ISO10646字符集。默认是用ISO-8859-1编码。

 

** HttpServletRequest对象

HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息。

protectedvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       /**

        * request对象中取出请求数据

        * */

       // 获取请求方方式

       System.out.println("请求方式:"+request.getMethod());

       // 获取资源的URI

       System.out.println("URI"+request.getRequestURI());

       // 获取资源的URL

       System.out.println("URL:"+request.getRequestURL());

       // 获取http版本

       System.out.println("http版本号:"+request.getProtocol());

        //-------------------------------------------------------

       // 获取host请求头名称

       System.out.println("头名称:"+request.getHeader("Host"));

       // 获取所有的请求头

       System.out.println("所有的请求头名称列表");

       Enumeration<String> elem = request.getHeaderNames();

       while (elem.hasMoreElements()) {

           String headerName = (String) elem.nextElement();

           String headerValue=(String) request.getHeader(headerName);

           System.out.println(headerName+": "+headerValue);

       }

       //-------------------------------------------------------  

    }

 

    // 采用的是post方法

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       InputStream is=request.getInputStream();// 得到实体输入流

       byte[] buf=new byte[1024];

       int len=0;

       while ((len=is.read(buf))!=-1) {

           System.out.println(new String(buf,0,len));

       }

    }

结果:

请求servletGet方法

请求方式:GET

URI/ibatis01/FuncDemo

URL:http://localhost:8080/ibatis01/FuncDemo

http版本号:HTTP/1.1

头名称:localhost:8080

所有的请求头名称列表

accept: text/html, application/xhtml+xml, image/jxr, */*

accept-language: zh-Hans-CN,zh-Hans;q=0.5

user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586

accept-encoding: gzip, deflate

host: localhost:8080

connection: Keep-Alive

cookie: bdshare_firstime=1464055541439

请求servletPost方法,获取Post对象的实体内容

name=wxh&pwd=123

** 获取参数对象方式

#1. 通过getParameter(“XXX”)方法获取

#2. 通过Enumeration<T>遍历requestname集合,用name取出对应的value

#3. 还有一个getParameterValues(“XXX”)获取一个那么有多个value对象,它返回的是一个String[]类型的数据,在遍历这个数据集合就可以取出所有的数据

 

** 参数内容编码问题

不论是post还是get都会出现乱码问题,因为jsp端设置的是utf-8的编码格式,而servlet解析用的默认的是iso-8853-1的编码格式。[中文乱码]

一般有两种解决方案

#1. 手动解码方式[iso-8853-1 à utf-8]

         name=new String(name.getBytes("iso-8859-1"),"utf-8");

#2. setCharacterEncoding(“utf-8”)

         request.setCharacterEncoding("UTF-8");

注意:setCharacterEncoding(“utf-8”)只有在doPost中才有效,因为post请求中参数的传递在实体内容中,而不是url地址后面。

package com.ibatis01.servlet;

 

import java.io.IOException;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class Request extends HttpServlet {

 

         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   /**

                    * 设置编码格式

                    * 但是对get方式没用

                    * 这个方法只对post提交的实体内容有效

                    * get只能用手动解码[iso-8853-1 --> utf-8]

                   */

                   request.setCharacterEncoding("UTF-8");// 没用

                   Enumeration<String> en=request.getParameterNames();// 获取name集合

                   while (en.hasMoreElements()) {

                            String name = (String) en.nextElement();// 获取name

                            name=new String(name.getBytes("iso-8859-1"),"utf-8");// 防止乱码

                            if(name.equals("hobby")){

                                     // 通过getParameterValues(String)获取多值

                                     String[] values=request.getParameterValues(name);// 获取value

                                     for (int i = 0; i < values.length; i++) {

                                               values[i]=new String(values[i].getBytes("iso-8859-1"),"utf-8");// 防止乱码

                                               System.out.println(name+": "+values[i]);

                                     }

                            }else{

                                     String value=request.getParameter(name);

                                      value=new String(value.getBytes("iso-8859-1"),"utf-8");// 防止乱码

                                     System.out.println(name+": "+value);

                            }

                   }

         }

 

         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   request.setCharacterEncoding("UTF-8");

                   System.out.println("---- POST方式 ----");

                   /**

                    * 获取请求的参数

                    * 利用getParameter获取参数

                    * */

                   String name=request.getParameter("name");

                   String pwd=request.getParameter("pwd");

                   System.out.println("名字:"+name+" | 密码:"+pwd);

                  

                   /**

                    * 利用Enumeration<T>遍历获取全部参数

                    * */

                   Enumeration<String> en=request.getParameterNames();// 获取Key

                   while (en.hasMoreElements()) {

                            String _name = (String) en.nextElement();

                            String _pwd=(String)request.getParameter(_name);

                            System.out.println(_name+": "+_pwd);

                   }

         }

}

 

** HttpServletResponse对象

HttpServletResponse对象代表服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。

返回的内容分成三大部分:1.状态码、2.响应头、3.实体内容[数据]

常用的几个方法:

voidaddCookie(Cookie cookie)    将一个Set-Cookie头标加入到响应。      

voidaddDateHeader(String name,long date)    使用指定日期值加入带有指定名字(或代换所有此名字头标)的响应头标的方法。      

voidsetHeader(String name,String value)    设置具有指定名字和取值的一个响应头标。      

voidaddIntHeader(String name,int value)    使用指定整型值加入带有指定名字的响应头标(或代换此名字的所有头标)。      

boolean containsHeader(Stringname)    如果响应已包含此名字的头标,则返回true      

StringencodeRedirectURL(String url)    如果客户端不知道接受cookid,则向URL加入会话ID。第一种形式只对在sendRedirect()中使用的URL进行调用。其他被编码的URLs应被传递到encodeURL()      

StringencodeURL(String url)          

voidsendError(int status)    设置响应状态码为指定值(可选的状态信息)。HttpServleetResponse定义了一个完整的整数常量集合表示有效状态值。      

voidsendError(int status,String msg)          

voidsetStatus(int status)    设置响应状态码为指定指。只应用于不产生错误的响应,而错误响应使用sendError()  

常见http错误:http://blog.sina.com.cn/s/blog_68158ebf0100wr7z.html

package com.ibatis01.servlet;

 

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class ResponseDemo extends HttpServlet {

 

         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   /**

                    * HttpServletResponse对象返回信息

                   */

                  

                   /**

                    * 1.状态码

                   */

                   // 返回状态

                   //response.setStatus(404);

                  

                   // 返回状态加错误页面

                   //response.sendError(404);

                  

                   /**

                    * 2.响应头

                   */

                   response.setHeader("server", "JBoss");

                  

                   /**

                    * 3.实体内容

                   */

                   response.getWriter().write("hello world");// 字符发送

                   // response.getOutputStream().write("hello world".getBytes());// 字节发送

                  

                   // 页面重定向

                   response.sendRedirect("/ibatis01/login.jsp");

                  

                   // 服务器发送给浏览器的数据类型和内容编码

                   response.setContentType("text/html;charset=utf-8");

         }

 

         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                  

         }

}

 

猜你喜欢

转载自blog.csdn.net/u013468915/article/details/52013126
今日推荐