Servlet是运行在web服务器上的应用程序,也是web服务器的组成部分,浏览器请求发送给服务器,服务器接收请求调用Servlet进行处理,
Server的概念:Servlet是用Java编写的Server端程序,它与协议和平台无关。Servlet运行于Java-enabled Web Server中。Java Servlet可以动态地扩展Server的能力,并采用请求-响应模式提供Web服务
Servlet的定义:
- 狭义上:有java/c语言实现的用于供服务器和浏览器消息处理和转发的一个接口
- 广义上:实现了Servlet接口的所有实现类
Servlet的过程:
- 浏览器发送请求给服务器
- 服务器接收请求调用Servlet程序处理
- Servlet将处理数据和返回值提交给服务器
- 服务器再转发给浏览器
Servlet和WEB服务器的关系:这就相当于公司和员工的关系,WEB服务器中包括很多个Servlet子处理程序,每个Servlet处理容器处理服务器接收浏览器的请求
一,Servlet的三种实现方式
servlet的三种实现接口:
- Servlet:Servlet的根接口
- GenericServlet:GenericServeric的实现类,对Servlet的方法进行了初始化,同时也实现ServletConfig接口,但它不依赖于具体Http协议,是基于Servlet的实现抽象类
- HttpServlet:HttpServlet类继承了GenericServlet类,但它提供了协议的支持,如doPost,doGet…… ,通过解析协议对服务请求进行分发处理
一,Servlet接口
所有Servlet实现的根接口,所有实现类都直接或间接的实现了Servlet
Servlet的五个方法:
- init:初始化方法,在Servlet实例化时,会最先调用该方法,在处理客户端请求之前做一些初始化操作,如:建立数据库连接,获取配置信息
- service:service主要用来写业务逻辑,处理请求
- destroy:销毁Servlet,在服务器中对Servlet对象进行移除,释放Servlet资源,对连接进行关闭,内存数据进行持久化
- getServletConfig:返回一个ServletConfig对象,ServletConfig主要是对Servlet参数进行获取和获取ServletContext对象
- getServletInfo:获取Servlet的版本,作者,版权信息
Servlet的生命周期:
例:
ublic class test implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { System.out.println("Serlvet启动init!!!!"); } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("WQL love FQ"); } @Override public String getServletInfo() { return null; } @Override public void destroy() { System.out.println("Servlet关闭!!"); } }
结果: Serlvet启动init!!!! WQL love FQ 24-Dec-2020 03:08:19.785 信息 [main] org.apache.catalina.core.StandardServer.await 通过关闭端口接收到有效的关闭命令。正在停止服务器实例。 24-Dec-2020 03:08:19.786 信息 [main] org.apache.coyote.AbstractProtocol.pause 暂停ProtocolHandler["http-nio-8080"] Servlet关闭!!
二,GenericServlet抽象类
GenericServlet分别实现了Servlet和ServletConfig两个接口,在此基础上还添加了一个log日志方法和对Init添加了重载方法
log方法:将指定的消息写入servlet日志文件,并以servlet的名称为前缀。
一,ServletConfig接口
ServletConfig作用:servlet容器在初始化期间用来将信息传递给servlet的servlet配置对象
getInitParameter:返回一个包含已命名初始化参数值的字符串,如果参数不存在,则返回null
getInitParameterNames:返回servlet的初始化参数的名称作为字符串对象的枚举,或者如果servlet没有初始化参数,则返回空枚举。
getServletContext:返回一个ServletContext全局对象
getServletName:返回Servlet实例名称
三,HttpServlet抽象类
HttpServlet继承了GenericServlet抽象类,但它支持HTTP请求,对Http协议请求进行解析,它提供了针对协议的doGet,doPost,doDelete,doPut……方法,它们都针对不同请求的类
doDelete:由服务器调用(通过服务方法),以允许servlet处理删除请求。
doGet:由服务器调用(通过服务方法),以允许servlet处理GET请求,获取数据。
doPost:由服务器调用(通过服务方法),以允许servlet处理POST请求,数据的提交。
doPut:由服务器调用(通过服务方法),以允许servlet处理PUT请求,数据的修改。
Service:Servlet的处理逻辑方法,不提供协议支持。
doHead:从受保护的服务方法接收HTTP头请求并处理该请求。
doTrace:由服务器调用(通过服务方法),以允许servlet处理跟踪请求。
二,Servlet的两种配置方式
Servlet的配置主要有xml配置和注解配置两种
一,web.xml配置Servelt
不写了,在Tomcat那篇博客中有详细讲到
二,注解配置
注解配置是在tomcat8.0(Servlet3.0)之后出现的
一,@WebServlet注解
作用:主要处理映射关系(url和实体类)
属性:
属性名 | 类型 | 属性描述 |
---|---|---|
name | String | 指定servlet的name属性,等价于<Servlet-name>.如果没有显示指定,则该servlet的取值即为类的全限定名. |
value | String[] | 等价于urlPatterns,二者不能共存. |
urlPatterns | String[] | 指定一组servlet的url的匹配模式,等价于 <url-pattern> 标签. |
loadOnStartup | int | 指定servlet的加载顺序,等价于 <load-on-startup> 标签. |
initParams | WebInitParam[] | 指定一组初始化参数,等价于 <init-param> 标签. |
asyncSupported | boolean | 申明servlet是否支持异步操作模式,等价于 <async-supported> 标签. |
displayName | String | servlet的显示名,等价于 <display-name> 标签. |
description | String | servlet的描述信息,等价于 <description> 标签. |
二,@WebFilte注解
作用:Servlet的过滤器和拦截器
- 用户权限过滤
- 记录日志
- 字符编码处理
属性:
属性名 | 类型 | 属性描述 |
---|---|---|
asyncSupported | boolean | 指定Filter是否支持异步模式 |
dispatcherTypes | DispatcherType[] | 指定Filter对哪种方式的请求进行过滤. 支持的属性:ASYNC、ERROR、FORWARD、INCLUDE、REQUEST; 默认过滤所有方式的请求 |
filterName | String | Filter名称 |
initParams | WebInitParam[] | 配置参数 |
displayName | String | Filter显示名 |
servletNames | String[] | 指定对哪些Servlet进行过滤 |
urlPatterns/value | String[] | 两个属性作用相同,指定拦截的路径 |
三,Request
Request:接收解析客户端请求,有Request作用域数据共享区
在Servlet中Request分为两种:
- ServletRequest:不提供协议支持,获取客户端的请求信息(请求行,请求头信息)
- HttpServletRequest:提供协议解析,继承了ServletRequest接口,并默认初始化了一些方法,并在ServletRequst基础上添加了一些新方法
一,ServletRequest接口
无任何父实现类
java.lang.Object |
getAttribute(java.lang.String name) Returns the value of the named attribute as an Object , or null if no attribute of the given name exists. |
java.util.Enumeration |
getAttributeNames() Returns an Enumeration containing the names of the attributes available to this request. |
java.lang.String |
getCharacterEncoding() Returns the name of the character encoding used in the body of this request. |
int |
getContentLength() Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. |
java.lang.String |
getContentType() Returns the MIME type of the body of the request, or null if the type is not known. |
ServletInputStream |
getInputStream() Retrieves the body of the request as binary data using a ServletInputStream . |
java.lang.String |
getLocalAddr() Returns the Internet Protocol (IP) address of the interface on which the request was received. |
java.util.Locale |
getLocale() Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. |
java.util.Enumeration |
getLocales() Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header. |
java.lang.String |
getLocalName() Returns the host name of the Internet Protocol (IP) interface on which the request was received. |
int |
getLocalPort() Returns the Internet Protocol (IP) port number of the interface on which the request was received. |
java.lang.String |
getParameter(java.lang.String name) Returns the value of a request parameter as a String , or null if the parameter does not exist. |
java.util.Map |
getParameterMap() Returns a java.util.Map of the parameters of this request. |
java.util.Enumeration |
getParameterNames() Returns an Enumeration of String objects containing the names of the parameters contained in this request. |
java.lang.String[] |
getParameterValues(java.lang.String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist. |
java.lang.String |
getProtocol() Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1. |
java.io.BufferedReader |
getReader() Retrieves the body of the request as character data using a BufferedReader . |
java.lang.String |
getRealPath(java.lang.String path) Deprecated. As of Version 2.1 of the Java Servlet API, use ServletContext.getRealPath(java.lang.String) instead. |
java.lang.String |
getRemoteAddr() Returns the Internet Protocol (IP) address of the client or last proxy that sent the request. |
java.lang.String |
getRemoteHost() Returns the fully qualified name of the client or the last proxy that sent the request. |
int |
getRemotePort() Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request. |
RequestDispatcher |
getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. |
java.lang.String |
getScheme() Returns the name of the scheme used to make this request, for example, http , https , or ftp . |
java.lang.String |
getServerName() Returns the host name of the server to which the request was sent. |
int |
getServerPort() Returns the port number to which the request was sent. |
boolean |
isSecure() Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS. |
void |
removeAttribute(java.lang.String name) Removes an attribute from this request. |
void |
setAttribute(java.lang.String name, java.lang.Object o) Stores an attribute in this request. |
void |
setCharacterEncoding(java.lang.String env) Overrides the name of the character encoding used in the body of this request. |
setCharacterEncoding:设置字符集
getCharacterEncoding:获取字符集
getAttribute:通过键获取Request作用域中的值
setAttribute:设置作用域中的键和值
getLocalName:获取当前主机名
getServerPort:获取Tomcat的端口号
getServletName:获取Servlet名称
getParameter:通过键获取请求中的参数值
getRequestDispatcher:进行请求的转发
……
二,HttpServletRequest
java.lang.String |
getAuthType() Returns the name of the authentication scheme used to protect the servlet. |
java.lang.String |
getContextPath() Returns the portion of the request URI that indicates the context of the request. |
Cookie[] |
getCookies() Returns an array containing all of the Cookie objects the client sent with this request. |
long |
getDateHeader(java.lang.String name) Returns the value of the specified request header as a long value that represents a Date object. |
java.lang.String |
getHeader(java.lang.String name) Returns the value of the specified request header as a String . |
java.util.Enumeration |
getHeaderNames() Returns an enumeration of all the header names this request contains. |
java.util.Enumeration |
getHeaders(java.lang.String name) Returns all the values of the specified request header as an Enumeration of String objects. |
int |
getIntHeader(java.lang.String name) Returns the value of the specified request header as an int . |
java.lang.String |
getMethod() Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. |
java.lang.String |
getPathInfo() Returns any extra path information associated with the URL the client sent when it made this request. |
java.lang.String |
getPathTranslated() Returns any extra path information after the servlet name but before the query string, and translates it to a real path. |
java.lang.String |
getQueryString() Returns the query string that is contained in the request URL after the path. |
java.lang.String |
getRemoteUser() Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. |
java.lang.String |
getRequestedSessionId() Returns the session ID specified by the client. |
java.lang.String |
getRequestURI() Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. |
java.lang.StringBuffer |
getRequestURL() Reconstructs the URL the client used to make the request. |
java.lang.String |
getServletPath() Returns the part of this request's URL that calls the servlet. |
HttpSession |
getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. |
HttpSession |
getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. |
java.security.Principal |
getUserPrincipal() Returns a java.security.Principal object containing the name of the current authenticated user. |
boolean |
isRequestedSessionIdFromCookie() Checks whether the requested session ID came in as a cookie. |
boolean |
isRequestedSessionIdFromUrl() Deprecated. As of Version 2.1 of the Java Servlet API, use isRequestedSessionIdFromURL() instead. |
boolean |
isRequestedSessionIdFromURL() Checks whether the requested session ID came in as part of the request URL. |
boolean |
isRequestedSessionIdValid() Checks whether the requested session ID is still valid. |
boolean |
isUserInRole(java.lang.String role) Returns a boolean indicating whether the authenticated user is included in the specified logical "role". |
与ServletRequest相比添加的方法:
getSession:获取Session会话对象
getCookie:获取Cookie对象信息
getHeaders:获取客户端的请求头信息,通过键可以获取值
例:
@WebServlet(value = "/luoqin") public class gg extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); System.out.println(req.getServletPath());//获取Servlet路径 System.out.println(req.getContextPath());//获取Servlet项目路径 System.out.println(req.getServerName());//获取Servlet名称 System.out.println(req.getServerPort());//获取Servlet端口号 System.out.println(req.getCharacterEncoding());//获取编码字符集 System.out.println(req.getParameter("name"));//按照参数名获取参数值 Enumeration<String> a = req.getParameterNames(); } }
访问:
http://localhost:8080/serlvet_war_exploded/luoqin?name=王清霖 结果:
/luoqin /serlvet_war_exploded localhost 8080 UTF-8 王清霖
三,Request的请求转发,重定向和作用域
请求的转发依赖于作用域提供信息的共享区域,作用域方便了在服务器端数据的共享
一,请求的转发
在ServletRequest中的getRequestDispatcher方法实现请求的转发
getRequestDispatcher返回值:RequestDispatcher对象
Request转发的特点:
- Request是针对于服务器端而不是客户端,所有它转发在客户端的url不会改变
- 转发有作用域的支持,可以获取作用域中的数据
- 转发的对象只能是项目下的servlet资源
RequestDispatcher类:
void |
forward(ServletRequest request, ServletResponse response) Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. |
void |
include(ServletRequest request, ServletResponse response) Includes the content of a resource (servlet, JSP page, HTML file) in the response. |
forward:将请求转发到另一个Servlet,jps文件,Html文件中
include:在响应资源中包含Servlet,JSP,HTML
二,Request作用域
作用域其实就是一个信息共享域,不同的Servlet可以通过这个作用域拿到处理信息,并进行下一步处理或者进行返回
Request作用域的特点:
- Request作用域只能在一次请求中有效,一次请求后将被销毁
- 作用域的形式是map型的,一键一值,值可以是基本数据类型也可以是引用数据类型
ServletRequest类中提供了作用域的方法:
Object getAttribute(String a):通过键获取Request作用域中的值
void setAttribute(String a,Object b):设置作用域中的键和值
例:
@WebServlet(value = "/Q2") public class Q2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取作用域中的值 String a = (String) req.getAttribute("name"); String a1 = (String) req.getAttribute("names"); System.out.println(a+"\t"+a1); } } @WebServlet(value = "/Q1") public class Q1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //在作用域中设置值 req.setAttribute("name","傅晴"); req.setAttribute("names","王清霖"); //转发给Q2 req.getRequestDispatcher("/Q2").forward(req,resp); } }
结果:
傅晴 王清霖
四,Responser
Responser类的作为响应数据的对象,负责数据的响应
在Servlet中对象的响应有两种:
- ServletResponser:不支持协议解析,负责Servlet数据的响应
- HttpServletResponse:扩展ServletResponse接口,以在发送响应时提供特定于http的功能。例如,它有访问HTTP报头和cookie的方法。
一,ServletResponse
SetcontentTpye:设置发送到客户端的响应的内容类型,如果响应还没有提交。
getwriter:获取javaIO流中的打印流
setCharacterEncodeing:设置响应的字符集
getCharacterEncodeing:获取响应的字符集
resetBuffer:清除响应中基础缓冲区的内容,而不清除标头或状态代码。
reset:清除缓冲区中存在的任何数据以及状态代码和头文件。
getBuffer:返回响应使用的实际缓冲区大小。
getlocal:如果还没有提交响应,则设置响应的区域设置。
二,HttpServletReponse
继承了ServletRespose类,并在此基础上,支持Http协议的操作
addHeader:添加Header头部信息
addcookie:添加cookic信息
setHeader:设置Header头部信息
sendReddirect:响应重定向
例:
@WebServlet(value = "/w1") public class w1 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter a = resp.getWriter(); a.println("<html>"); a.println("<head>"); a.println("</head>"); a.println("<body>"); a.println("<h1>Servlet解析</h1>"); a.println("</body>"); a.println("</html>"); } }
结果:
三,请求的重定向
请求的重定向特点:
- 与转发不同重定向,可以定位到任何资源,并不局限于项目的servlet中
- 重定向不支持域的资源的获取,但可以获取请求中的参数
- 转发是服务器内部的转发不会影响到客户端,而重定向是服务器外部资源的请求
重定向的所有:提供HttpServletResponse类中的sendReddirect方法实现重定向
sendReddirect("外部资源url地址")
五,Servlet中Cookie的使用
一,Cookie的产生原因(状态管理问题)
HTTP协议存在的问题:
- Http协议是无状态的,不能保存每次提交的信息
- 如果每一次用户有新的请求,请求的服务器无法知道上次的问题内容,这在密码的登录存在麻烦
Cookic的出现就是针对Http的无状态,无法保存请求信息问题
概念:将浏览器和web服务器多次交互作为一个整体处理,并且将多请求的数据进行保存
HTTP协议的状态管理分类:
- 客户端状态管理技术:将状态信息保存在客户端,也就是Cookie
- 服务器状态管理技术:将状态信息保存在服务器,代表技术有Session(服务器转递Session时需要使用Cookie)
二,Cookic的原理
Cookie的保存过程:
- 在浏览器访问Web服务器的某个资源时,由WEB服务器在HTTP响应信息头中添加Cookie,附带转给服务器
- 服务器接收消息头中的Cookie将他保存,下次无法访问服务器时,在请求头中添加保存的Cookie信息回传给服务器
- 服务器解析Cookie做出响应
Cookie的组成部分:Cookie由键值对组成,一个key一个value
Cookie的弊端:
- 大小的限制:Cookie存储的数据只有4k~8k字节,无法存储较大型的数据
- 客户端的禁用:客户端框架禁用cookie,cookie就无法使用
- 安全问题:Cookie可能会被篡改
三,Cookie的使用
Cookie的构造方法:
public Cookie(String name, String value) { validation.validate(name); this.name = name; //name设置键 this.value = value; //value设置值 }
java.lang.Object |
clone() Overrides the standard java.lang.Object.clone method to return a copy of this cookie. |
java.lang.String |
getComment() Returns the comment describing the purpose of this cookie, or null if the cookie has no comment. |
java.lang.String |
getDomain() Returns the domain name set for this cookie. |
int |
getMaxAge() Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. |
java.lang.String |
getName() Returns the name of the cookie. |
java.lang.String |
getPath() Returns the path on the server to which the browser returns this cookie. |
boolean |
getSecure() Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol. |
java.lang.String |
getValue() Returns the value of the cookie. |
int |
getVersion() Returns the version of the protocol this cookie complies with. |
void |
setComment(java.lang.String purpose) Specifies a comment that describes a cookie's purpose. |
void |
setDomain(java.lang.String pattern) Specifies the domain within which this cookie should be presented. |
void |
setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. |
void |
setPath(java.lang.String uri) Specifies a path for the cookie to which the client should return the cookie. |
void |
setSecure(boolean flag) Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL. |
void |
setValue(java.lang.String newValue) Assigns a new value to a cookie after the cookie is created. |
void |
setVersion(int v) Sets the version of the cookie protocol this cookie complies with. |
setValue:设置当前Cookie的值
setName:设当前Cookie的键
setVersion:设置当前Cookie遵循的协议版本号
setPath:设置访问那个url路径携带该Cookie
getPath:获取访问路径
setMaxage:设置有效时间,大于0以秒时间为单位,等于0浏览器关闭cookie就销毁,小于0内存存储
如何将Cookie添加进响应头中和获取客户端的cookie:
- 添加设置:通过HtttpServletResponse对象中的addCookie(Cookie cookie)方法
- 获取:通过HttpServletRequest对象中的Cookie[] getCookies()方法
Cookie的编码和解码:cookie默认是不支持中文的只能包含ASCII码
- 编码:通过java.net.URLEncode类中的encode(String str,String encoding)方法
- 解码:通过java.net.URLDncoder类中的dncoder(String str,String dncoder)方法
例:
@WebServlet(value = "/FQ520") public class FQ extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie a = new Cookie("name","FQloveWQL"); Cookie a1 = new Cookie("names","FQloveWQLs"); a.setMaxAge(60*60);//设置数cookie时间 a.setPath("/serlvet_war_exploded/fq");//设置路径携带cookie resp.addCookie(a);//添加进响应头中 resp.addCookie(a1); req.setAttribute("name","hehe"); req.getRequestDispatcher("fq1").forward(req,resp); }}
结果:
六,HttpSession
一,HttpSession的作用和概述
session的保存依赖于cookie
1,Httpsession的作用:
- httpSession记录客户端的状态,指一段数据内,客户端和服务器一连串的交互过程
- 在一个Session客户端可能一次或者多次访问服务器上的同一个资源,也可能一次或者多次访问服务器上的不同资源
2,Session在服务器中的产生过程:
- 服务器为每一次会话分配了session对象,同一个浏览器的多次请求同属于一个session
- 首次使用session时服务器会自动创建,并通过cookie保存发送给客户端,所以在看响应头时可以看到有一个Webstorm
- 当客户端在一次请求服务器时,通过sessionID来判断是否已有seesion
3,Session作用域:Session作用域和Request作用域一样也可以存储数据,但它有自己独有的方法如移除,销毁
- 存储数据的类型:Session作用域可以存储对象,集合,数组……
- 存储形式:也是通过k-v形式存储,value可以包含上述类型
4,Session作用域和Request作用域的区别:
- 生命周期:Session作用域的是一次会话,而Request作用域是一次请求,session作用域当客户端关闭时Session才会被销毁,而request作用域在一次请求后就会被销毁
- 方法上的完善:Session作用域提供了销毁方法和销毁时间(当客户端不关闭时的销毁方式),还提供数据的移除和修改方法,而request作用域没有
二,HttpSession的使用
在servlet中如何获取Session对象:通过HttpServletRequest中的getSession方法
java.lang.Object |
getAttribute(java.lang.String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name. |
java.util.Enumeration |
getAttributeNames() Returns an Enumeration of String objects containing the names of all the objects bound to this session. |
long |
getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
java.lang.String |
getId() Returns a string containing the unique identifier assigned to this session. |
long |
getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request. |
int |
getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. |
ServletContext |
getServletContext() Returns the ServletContext to which this session belongs. |
HttpSessionContext |
getSessionContext() Deprecated. As of Version 2.1, this method is deprecated and has no replacement. It will be removed in a future version of the Java Servlet API. |
java.lang.Object |
getValue(java.lang.String name) Deprecated. As of Version 2.2, this method is replaced by getAttribute(java.lang.String) . |
java.lang.String[] |
getValueNames() Deprecated. As of Version 2.2, this method is replaced by getAttributeNames() |
void |
invalidate() Invalidates this session then unbinds any objects bound to it. |
boolean |
isNew() Returns true if the client does not yet know about the session or if the client chooses not to join the session. |
void |
putValue(java.lang.String name, java.lang.Object value) Deprecated. As of Version 2.2, this method is replaced by setAttribute(java.lang.String, java.lang.Object) |
void |
removeAttribute(java.lang.String name) Removes the object bound with the specified name from this session. |
void |
removeValue(java.lang.String name) Deprecated. As of Version 2.2, this method is replaced by removeAttribute(java.lang.String) |
void |
setAttribute(java.lang.String name, java.lang.Object value) Binds an object to this session, using the name specified. |
void |
setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. |
setAttribute(String name,String value):设置作用域中的键和值
getAttribute(String name):通过键获取值
getAttributeNames:获取所有作用域数据的Key
removeAttribute(String name):通过键移除值
setMaxInactiveInterval(int interal):设置session的有效时间
getID:获取Session的ID
例:
@WebServlet(value = "/w") public class test1 extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession a=req.getSession(); a.setAttribute("name","wql");}
七,ServletContext作用
一:ServletContext概述
服务器会为每个web项目创建一个ServletContext对象:
1. ServletContext对象的创建是在服务器启动时完成的;
2. ServletContext对象的销毁是在服务器关闭时完成的。 ServletContext对象的作用是在整个Web应用的动态资源之间共享数据!例如在AServlet中向ServletContext对象中保存一个值,然后在BServlet中就可以获取这个值,这就是共享数据了。
二:获取ServletContext
1. ServletConfig#getServletContext();
2. GenericServlet#getServletContext();
3. HttpSession#getServletContext()
4. ServletContextEvent#getServletContext()
5. HttpServlet#getServletContext();
在Servlet中获取ServletContext对象:
1. 在void init(ServletConfig config)中:ServletContext context = config.getServletContext();,
ServletConfig类的getServletContext()方法可以用来获取ServletContext对象;
在GenericeServlet或HttpServlet中获取ServletContext对象:
2. GenericServlet类有getServletContext()方法,所以可以直接使用this.getServletContext()来获取;
三:域对象的功能
ServletContext是JavaWeb四大域对象之一:
1. PageContext;
2. ServletRequest;
3. HttpSession;
4. ServletContext; 其中ServletContext是最大的域对象。
域对象的通俗解释: 域对象就是用来在多个Servlet中传递数据!!!
1. 域对象必须有要存数据功能
2. 域对象必须要有取数据功能 域对象内部其实有一个Map 所有域对象都有存取数据的功能,因为域对象内部有一个Map,用来存储数据,
下面是ServletContext对象用来操作数据的方法:
java.lang.Object |
getAttribute(java.lang.String name) Returns the servlet container attribute with the given name, or null if there is no attribute by that name. |
java.util.Enumeration |
getAttributeNames() Returns an Enumeration containing the attribute names available within this servlet context. |
ServletContext |
getContext(java.lang.String uripath) Returns a ServletContext object that corresponds to a specified URL on the server. |
java.lang.String |
getInitParameter(java.lang.String name) Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. |
java.util.Enumeration |
getInitParameterNames() Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. |
int |
getMajorVersion() Returns the major version of the Java Servlet API that this servlet container supports. |
java.lang.String |
getMimeType(java.lang.String file) Returns the MIME type of the specified file, or null if the MIME type is not known. |
int |
getMinorVersion() Returns the minor version of the Servlet API that this servlet container supports. |
RequestDispatcher |
getNamedDispatcher(java.lang.String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet. |
java.lang.String |
getRealPath(java.lang.String path) Returns a String containing the real path for a given virtual path. |
RequestDispatcher |
getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. |
java.net.URL |
getResource(java.lang.String path) Returns a URL to the resource that is mapped to a specified path. |
java.io.InputStream |
getResourceAsStream(java.lang.String path) Returns the resource located at the named path as an InputStream object. |
java.util.Set |
getResourcePaths(java.lang.String path) Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument. |
java.lang.String |
getServerInfo() Returns the name and version of the servlet container on which the servlet is running. |
八,Filter过滤器
一,过滤器的概念
过滤器是处于客户端和服务器目标资源之间的一个技术,在客户端访问服务器时,在之间进行拦截操作,在访问进行中间处理,类似于AOP中的中间代理
过滤器的作用:
- 客户端发来请求,在到底具体的Servlet处理之前,Filter会先做逻辑处理
- 相当于代理,可以解决共性代码冗余问题,例:乱码处理,登录验证
二,Filter过滤器的实现
Filter的实现过程:
- 在java类中实现Filetr接口
- 在dofilter方法实现拦截器的逻辑
- 设置拦截路径,有两种方式:1,通过@Webfiler注解 2,通过配置文件
一,Filter接口
是实现Filter过滤器的根接口
源码:
public interface Filter { default void init(FilterConfig filterConfig) throws ServletException { } void doFilter(ServletRequest var1, ServletResponse var2, FilterChain var3) throws IOException, ServletException; default void destroy() { } }
API:
destroy() |
|
void |
doFilter(ServletRequest request, ServletResponse response, FilterChain chain) The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. |
void |
init(FilterConfig filterConfig) Called by the web container to indicate to a filter that it is being placed into service. |
destroy:由web容器调用,以指示筛选器它将退出服务。
dofilter:由于客户端请求链末端的资源,每次请求/响应对通过链传递时,容器都会调用过滤器的doFilter方法,实现具体的拦截逻辑
init:由web容器调用,以指示筛选器它正在被放置到服务中。初始化操作
二,FilterConfig接口
作用:servlet容器使用的过滤器配置对象,配置和获取初始化信息,在初始化期间将信息传递给过滤器,init时候会使用到
API:
java.lang.String |
getFilterName() Returns the filter-name of this filter as defined in the deployment descriptor. |
java.lang.String |
getInitParameter(java.lang.String name) Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. |
java.util.Enumeration |
getInitParameterNames() Returns the names of the filter's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters. |
ServletContext |
getServletContext() Returns a reference to the ServletContext in which the caller is executing. |
getFilterName:获取Filter的名字
getInitParameter:获取初始化参数
getInitParameterNames:获取初始化参数的名字
getServletContext:获取Servlet的Context对象
三,filterchain
作用:在过滤器执行完之后要放行的资源,如果有多个过滤器就向下反向过滤器,如果没有就执行被拦截的Servlet
API:
void |
doFilter(ServletRequest request, ServletResponse response) Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked. |
例:
拦截器:
@WebFilter("/v2")//拦截的路径 public class v1 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("过滤器!!!"); filterChain.doFilter(servletRequest,servletResponse);//放行请求到Servlet } @Override public void destroy() { } }
Servlet:
@WebServlet(value = "/v2") public class v2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter a=resp.getWriter(); a.println("<html>"); a.println("<head>"); a.println("</head>"); a.println("<body>"); a.println("<h1>过滤器</h1>"); a.println("</body>"); a.println("</html>"); } }
结果:
控制台输出:
过滤器!!! 26-Dec-2020 00:16:01.031 信息 [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployDirectory 把web 应用程序部署到目录 [F:\apache-tomcat-9.0.37\webapps\manager] 26-Dec-2020 00:16:01.098 信息 [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployDirectory Web应用程序目录[F:\apache-tomcat-9.0.37\webapps\manager]的部署已在[67]毫秒内完成
Comments | NOTHING
Warning: Undefined variable $return_smiles in /www/wwwroot/wql_luoqin_ltd/wp-content/themes/Sakura/functions.php on line 1109