欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

http之HttpServletRequest和HttpServletResponse

程序员文章站 2022-03-30 19:49:03
...

对于客户端的一个请求,服务端建立request和response对象,分别代表请求和返回。

 

一、HttpServletRequest对象

   客户端通过http协议访问时,请求中所有的信息都存放在该对象中,包括parameter name和value,attribute,

input stream,cookie,http协议相关的信息等。

 

1、parameter和attribute的区别

parameter是客户端提交的参数;

attribute是与客户端无关,在不同servlet之间传递参数,当做容器使用

 

设置:

 String white = (String) request.setAttribute(“name”,"china");

 

读取:

 

String white = (String) request.getAttribute(“name”);

2、Cookie

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

cookie是当做http头部信息存储k-v形式存储,key固定为Cookie,v为name=value形式,多个键值以分号分割。

服务端读取cookie

//简便的获取cookie信息的方式
Cookie[] cookies = request.getCookies();
for(Cookie cookie : cookies){
    log.info("name={},value={}",cookie.getName(),cookie.getValue());
}
//原始的从头部获取cookie的方式
String rawCookie = request.getHeader("Cookie");
String[] rawCookieParams = rawCookie.split(";");
for(String cookie : rawCookieParams){
    log.info("cookie={}",cookie);
}

 

 

参考:

https://*.com/questions/33690741/httpservletrequest-getcookies-or-getheader

 

3、inputStream

ServletInputStream servletInputStream = request.getInputStream();

参考JAVA API解释

可以看出为客户端请求的字节流,一般框架已经封装好,使用较少。 

public abstract class ServletInputStream
extends InputStream
Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. With some protocols, such as HTTP POST and PUT, a ServletInputStream object can be used to read data sent from the client.

ServletInputStream object is normally retrieved via the ServletRequest.getInputStream() method.

This is an abstract class that a servlet container implements. Subclasses of this class must implement the java.io.InputStream.read() method.

 

 二、HttpServletReponse对象

 //设置http返回码:404、200等
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
resp.setContentType("application/json;charset=UTF-8");
String data = "这是字节流输出的内容";
 byte[] dataByteArr = data.getBytes(StandardCharsets.UTF_8);
//获取http输出字节流
 //resp.getOutputStream().write(dataByteArr);
 //resp.flushBuffer();
//获取http输出字符流
resp.getWriter().println("这是字符流输出的内容");

 获取字节流还是字符流只能选择一种。