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. ELK日志分析系统搭建

    之前一段时间由于版本迭代任务紧,组内代码质量不尽如人意.接二连三的被测试提醒后台错误之后, 我们决定搭建一个后台日志分析系统, 经过几个方案比较后,选择的相对更简单的ELK方案. ELK 是Elast ...

  2. CentOS8安装fastdfs6.06

    目录 一.准备环境 二.解压并编译安装 1.解压下载好的包 2.编译安装 2.1.编译安装 libfastcommon 2.2.编译安装 fastdfs 2.3.安装 nginx 和 fastdfs- ...

  3. 洛谷P1427 小鱼的数字游戏 题解 递归入门题

    题目链接:https://www.luogu.com.cn/problem/P1427 题目大意: 给你一串数(输入到0为止),倒序输出这些数. 解题思路: 首先这道题目可以用数组存数据,然后输出. ...

  4. Ubuntu管理软件源

    在Ubuntu环境下,我们经常会使用apt-get(apt)命令下载各种软件,当所需软件在官方软件库中找不到时,我们需要添加第三方的软件源,或者由于位于海外的官方软件源下载速度过于感人时,需要添加国内 ...

  5. k8s-自动安装

    操作环境: centos7.3 node102-master-192.168.100.102 node103-node1-192.168.100.103 node104-node2-192.168.1 ...

  6. spring-boot第一章:快速开始

    快速开始 创建pom.xml文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns= ...

  7. Django 博客实现简单的全文搜索

    作者:HelloGitHub-追梦人物 文中所涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 搜索是一个复杂的功能,但对于一些简单的搜索任务,我们可以使用 Django Mode ...

  8. FUTABA舵机参数大全

    S9150 Digital servo 尺寸:47.5X27X25.3mm 重量:53g 速度:0.18sec/60"(4.8V) 扭力:5.8kg:cm(4.8V) ——————————— ...

  9. opensuse安装Tomcat碰到的问题

    已经安装好JDE,并配置好环境变量 从官网下载Tomcat tar包,解压到用户目录,进入运行bin下的start.sh,显示运行成功,但是浏览器中输入localhost:8080连接不上 检查一番发 ...

  10. 如何利用Map2Shp进行快速格式转换

    有时,用户仅需要进行GIS数据格式的简单转换,对文字注记.制图表达.投影信息无特别要求,可进行快速格式转换.做为MapGIS文件与Shape文件间的格式转换工具,Map2Shp软件操作过程十分简单,只 ...