当前位置:首页>开发>正文

HttpServletRequest和ServletRequest的区别 HttpServletRequest的方法

2023-05-22 15:34:19 互联网 未知 开发

 HttpServletRequest和ServletRequest的区别 HttpServletRequest的方法

HttpServletRequest和ServletRequest的区别

HttpServletRequest继承自ServletRequest
HttpServletRequest比ServletRequest多了一些针对于Http协议的方法。
例如:getHeader(), getMethod() , getSession()
HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息。

HttpServletRequest的方法

HttpServletRequest方法总结

getScheme()方法返回请求的计划,比如http,https或者ftp.
getServerName()方法返回被发送请求的服务器的主机名
getServerPort()方法返回被发送请求的端口号。
getContextPath()返回请求地址的根目录,以"/"开关,但不是以"/"结尾。
一个常用的获得服务器地址的连接字符串是:
String path = request.getContextPath()
String basePath = request.getScheme() "://" request.getServerName() ":" request.getServerPort() path "/"

getCookies() 取得cookie
getMethod() 取得请求方法,如get,post或put
getRequestURL() 取得请求URL(统一资源定位符)
getRequestURI() 取得请求URI(统一资源标识符)
getSession() 取得对应session

getHeaderNames()返回请求包含的所有头名称的一个enumeration(遍历器)
使用方法如下:
Enumeration en = request.getHeaderNames()
while(en.hasMoreElements()){
out.print(en.nextElement())

}
输出如下结果:
accept accept-language accept-encoding user-agent host connection cookie
具体含义是:
Accept:浏览器可接受的MIME类型。
Accept-Language:浏览器所希望的语言种类,当服务器能够提供一种以上的语言版本时要用到。
Accept-Encoding:浏览器能够进行解码的数据编码方式,比如gzip。Servlet能够向支持gzip的浏览器返回经gzip编码的HTML页面。许多情形下这可以减少5到10倍的下载时间。
User-Agent:浏览器类型,如果Servlet返回的内容与浏览器类型有关则该值非常有用。
Host:初始URL中的主机和端口。
Connection:表示是否需要持久连接。如果Servlet看到这里的值为“Keep-Alive”,或者看到请求使用的是HTTP 1.1(HTTP 1.1默认进行持久连接),它就可以利用持久连接的优点,当页面包含多个元素时(例如Applet,图片),显著地减少下载所需要的时间。要实现这一点,Servlet需要在应答中发送一个Content-Length头,最简单的实现方法是:先把内容写入ByteArrayOutputStream,然后在正式写出内容之前计算它的大小。
Cookie:这是最重要的请求头信息之一

getHeader(name)返回指定名称的特定请求的值。
使用方法如下:
out.print("cookie:===" request.getHeader("cookie") "<br>")

完整举例:
accept:===*/*
accept-language:===zh-cn
accept-encoding:===gzip, deflate
user-agent:===Mozilla/4.0 (compatible MSIE 6.0 Windows NT 5.1 SV1 TheWorld)
host:===localhost:8080
connection:===Keep-Alive
cookie:===JSESSIONID=BF00F7FD72F5DF83DF8F62E3D5EFF960

如何在一个类中获取HttpServletRequest 对象

普通类中获取request对象方法:
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()
HttpServletRequest request = sra.getRequest()

SpringMVC控制层框架中获取request对象只要在方法名后面的括号中写上参数类型和对象名称就可以自动获取了

Spring MVC 中获取 HttpServletRequest request, HttpServletResponse response 对象的方法

//这样能获取Request和Response对象,你说的那种没用过
@RequestMapping("view")
publicString view(HttpServletRequest request, HttpServletResponse) {
    return"view"
}

随便看看