Servlet进阶API

每个Servlet都必须由web容器读取Servlet设置信息(标注或者web.xml)、初始化。
对于每个Servlet的设置信息,web容器会为其生成一个ServletConfig作为代表对象,从中可以取得Servlet初始化参数,以及代表整个web应用
程序的ServletContext对象。
Web容器启动后,会读取Servlet设置信息,将Servlet类加载并实例化,并为每个Servlet设置信息产生一个ServletConfig对象,而后调用Servlet接口的
init()方法,并将产生的ServletConfig对象当做参数传入。
这个过程只会在创建Servlet实例后发生一次。
GenericServlet:
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
// NOOP by default
}

ServletConfig相当于Servlet的设置信息代表对象。

可以使用标注设置Servlet初始参数
 */
@WebServlet(name = "FiveServlet",
urlPatterns = {"/five.do"},
initParams = {
@WebInitParam(name = "name", value = "xiya"),
@WebInitParam(name = "age", value = "24")
})
private String name;
private String age;
@Override
public void init() throws ServletException {
name = getInitParameter("name");
age = getInitParameter("age");
}

或者web.xml

<servlet>
<servlet-name>FiveServlet</servlet-name>
<servlet-class>FiveServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>xiya</param-value>
</init-param>
<init-param>
<param-name>age</param-name>
<param-value>25</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FiveServlet</servlet-name>
<url-pattern>/five.do</url-pattern>
</servlet-mapping>

web.xml中的设置会覆盖标注的设置。(标注的name属性需要和web.xml的<servlet-name>匹配)。


ServletContext:作为整个Web应用程序的代表。

应用程序事件、监听器

Web容器管理Servlet/JSP相关的对象生命周期,我们可以使用监听器处理对HttpServletRequest对象、HttpSession对象,ServletContext对象的生成、销毁事件,实际上就是我们编写回调函数,然后由Web容器来调用。

HttpServletRequest事件、监听器

ServletRequestListener:是生命周期监听器。
ServletRequestAttributeListener是属性改变监听器。
public interface ServletRequestListener extends EventListener {

    /**
* The request is about to go out of scope of the web application.
* The default implementation is a NO-OP.
* @param sre Information about the request
*/
public default void requestDestroyed (ServletRequestEvent sre) {
} /**
* The request is about to come into scope of the web application.
* The default implementation is a NO-OP.
* @param sre Information about the request
*/
public default void requestInitialized (ServletRequestEvent sre) {
}
}

测试代码:

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* Created by N3verL4nd on 2017/3/1.
*/
@WebListener
@WebServlet(name = "ListenerServlet", urlPatterns = {"/listener.do"})
public class ListenerServlet extends HttpServlet implements ServletRequestListener, ServletRequestAttributeListener{ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
request.setAttribute("name", "xiya");
request.setAttribute("name", "xiya1");
} @Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("requestDestroyed");
} @Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("requestInitialized");
} @Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
System.out.println("attributeAdded");
System.out.println("attributeAdded: " + srae.getName() + " " + srae.getValue());
} @Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
System.out.println("attributeRemoved");
System.out.println("attributeRemoved: " + srae.getName() + " " + srae.getValue());
} @Override
public void attributeReplaced(ServletRequestAttributeEvent srae) {
System.out.println("attributeReplaced");
System.out.println("attributeReplaced:" + srae.getName() + " " + srae.getValue());
}
}

访问:http://localhost:8080/jspRun/listener.do

输出:
requestInitialized

attributeReplaced

attributeReplaced:org.apache.catalina.ASYNC_SUPPORTED true

doGet

attributeAdded

attributeAdded: name xiya

attributeReplaced

attributeReplaced:name xiya

requestDestroyed

HttpSession事件、监听器

public interface HttpSessionListener extends EventListener {

    /**
* Notification that a session was created.
* The default implementation is a NO-OP.
*
* @param se
* the notification event
*/
public default void sessionCreated(HttpSessionEvent se) {
} /**
* Notification that a session is about to be invalidated.
* The default implementation is a NO-OP.
*
* @param se
* the notification event
*/
public default void sessionDestroyed(HttpSessionEvent se) {
}
}

在HttpSession对象初始化或结束前,分别调用sessionCreated()与sessionDestroyd()方法。

ServletContext事件、监听器

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* Created by N3verL4nd on 2017/3/1.
*/
@WebListener
@WebServlet(name = "ContextListenerServlet", urlPatterns = {"/contextListener.do"})
public class ContextListenerServlet extends HttpServlet implements ServletContextListener{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
} @Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("contextInitialized");
} @Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("contextDestroyed");
}
}

[2017-03-01 04:02:31,096] Artifact jspRun:war exploded: Artifact is being deployed, please wait...

[2017-03-01 04:02:31,097] Artifact WeiBo:war exploded: Artifact is being deployed, please wait...

contextInitialized

[2017-03-01 04:02:31,448] Artifact jspRun:war exploded: Artifact is deployed successfully

[2017-03-01 04:02:31,450] Artifact jspRun:war exploded: Deploy took 354 milliseconds

由此可见,当整个Web应用程序加载Web容器之后,容器会生成一个ServletContext对象。

重新部署后的日子信息:
[2017-03-01 04:03:53,921] Artifact jspRun:war exploded: Artifact is being deployed, please wait...

[2017-03-01 04:03:53,922] Artifact WeiBo:war exploded: Artifact is being deployed, please wait...

contextDestroyed

contextInitialized

[2017-03-01 04:03:54,580] Artifact jspRun:war exploded: Artifact is deployed successfully

[2017-03-01 04:03:54,580] Artifact jspRun:war exploded: Deploy took 659 milliseconds

[2017-03-01 04:03:55,270] Artifact WeiBo:war exploded: Artifact is deployed successfully

[2017-03-01 04:03:55,270] Artifact WeiBo:war exploded: Deploy took 1,348 milliseconds

注:
生命周期监听器与属性改变监听器都必须使用@WebListener或在web.xml中设置,容器才会知道要加载、读取监听器的相关设置。

过滤器

它是介于Servlet与浏览器之间,可以拦截过滤浏览器对Servlet的请求,也可以改变Servlet对浏览器的响应。
在Servlet/JSP中要实现过滤器,必须实现Filter接口。并且需要使用@WebFilter标注或在web.xml中定义过滤器。
public interface Filter {
public default void init(FilterConfig filterConfig) throws ServletException {}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException;
public default void destroy() {}
}

Filter接口的doFilter()方法类似于Servlet接口的service()方法。当请求来到容器,而容器发现调用Servlet的service()方法前,可以应用某过滤器,就会

调用该过滤器的doFilter()方法。
如果调用FilterChain的doFilter()方法,就会运行下一个过滤器,如果没有下一个过滤器,就会调用Servlet的service()方法。
如果没有调用FilterChain的doFilter(),则请求就不会继续交给接下来的过滤器或目标Servlet,这就是所谓的拦截请求。


JSP&Servlet学习笔记----第5章的更多相关文章

  1. JSP&Servlet学习笔记----第3章

    Web容器是JSP/Servlet唯一认识的HTTP服务器. HTTP是基于请求/响应的无状态通信协议. 流程: 1.请求来到HTTP服务器 2.HTTP服务器将请求转交给Web容器 3.Web容器创 ...

  2. JSP&Servlet学习笔记----第6章

    JSP与Servlet是一体两面的关系. JSP最终还是被编译为Servlet. <%@page contentType="text/html;charset=UTF-8" ...

  3. JSP&Servlet学习笔记----第4章

    HTTP是基于请求/响应的无状态的通信协议. 使服务器记得此次请求与之后请求关系的方式,叫做会话管理. 隐藏域:由浏览器在每次请求时主动告知服务器多次请求间必要的信息.仅适用于一些简单的状态 管理,如 ...

  4. JSP&Servlet学习笔记----第1/2章

    HTML(HyperText Markup Language):超文本标记语言 HTTP(HyperText Transfer Protocol):超文本传输协议 URL(Uniform Resour ...

  5. jsp&servlet学习笔记

    1.路径引用问题 一个css.jsp.html.或者javascript文件从从一个工程复制到另一工程,如果引用的时候使用的时相对路径,看似没有错误,但是却一直引用不进来,这时候要使用绝对路径,这样才 ...

  6. 【JSP&Servlet学习笔记】5.Servlet进阶AIP、过滤器与监听器

    Servlet接口上,与生命周期及请求服务相关的三个方法是init().service()与destory()方法.当Web容器加载Servlet类并实例化之后,会生成ServletConfig对象并 ...

  7. JSP Servlet学习笔记——使用fileupload上传文件

    关键代码如下: index.jsp <body> <center> <h3>文件上传</h3> <font color="red&quo ...

  8. 【JSP&Servlet学习笔记】4.会话管理

    Http本身是无状态通信协议,要进行会话管理的基本原理,就是将需要维护的状态回应给浏览器,由浏览器在下次请求时主动发送状态信息,让Web应用程序“得知”请求之间的关联. 隐藏字段是将状态信息以窗体中看 ...

  9. # jsp及servlet学习笔记

    目录 jsp及servlet学习笔记 JSP(Java Server Page Java服务端网页) 指令和动作: servlet(小服务程序) jsp及servlet学习笔记 JSP(Java Se ...

随机推荐

  1. docker-none

    禁用容器的网络连接 如果要完全禁用容器上的网络堆栈,可以--network none在启动容器时使用该标志.在容器内,仅创建环回设备.以下示例说明了这一点. 创建容器. $ docker run -- ...

  2. 通过httpClient设置代理Ip

    背景: 我们有个车管系统,需要定期的去查询车辆的违章,之前一直是调第三方接口去查,后面发现数据不准确(和深圳交警查的对不上),问题比较多.于是想干脆直接从深圳交警上查,那不就不会出问题了吗,但是问题又 ...

  3. 【转】安卓开发经验分享:资源、UI、函数库、测试、构建一个都不能少

    本文由 ImportNew - 唐尤华 翻译自 gigavoice.如需转载本文,请先参见文章末尾处的转载要求. 除了高超的武艺,每位黑忍者还需要装备最好的武器.在软件开发的世界里,好的工具能让我们的 ...

  4. MySQL插入操作

    说明:value的值可以为数据,DEFAULT,NULL,expr 含有ATUO_INCREMENT的列可以插入DEFAULT.NULL,或者不插入记录来实现自动增长. 插入记录的三种方法:①可以同时 ...

  5. mac-air上安装 rabbitmq 并简单使用

    简介: brew 安装 rabbitmq,docker安装rabbitmq 安装官方php-amqp 扩展 简单使用样例(发送10次helloworld

  6. wannafly camp day1

    题目描述: 恬恬的生日临近了.宇扬给她准备了一个大 蛋糕. 正如往常一样,宇扬在蛋糕上插了nnn支蜡烛,并把蛋糕分为mmm个区域.因为某种原因,他必须把第iii根蜡烛插在第aia\_iai​个区域或第 ...

  7. html+css 知识点总结 day1(01-08)

    01  初步认识浏览器 02 浏览器内核 IE   内核:Trident,                 win10 Edge  内核:EdgeHTML Firefox(火狐浏览器)   内核:Ge ...

  8. scrapy持久化到Excel表格

    前提条件: 防止乱码产生 ITEM_PIPELINES = { 'xpc.pipelines.ExcelPipeline': 300, } 方法一 1.安装openpyxl conda install ...

  9. git branch stash

    一.branch(分支) 1.创建分支 git branch dev 2.切换分支 git branch dev 3.合并分支 git merge bug 4.查看分支 git branch 5.删除 ...

  10. .net mvc Bundle 自己配置

    遇到了个坑 来和大家分享一下 1.一个空的mvc项目需要引用 System.Web.Optimization 2.然后nuget添加 microsoft ASP.NET WEB OPTIMIZATIO ...