`
lgh1992314
  • 浏览: 293887 次
文章分类
社区版块
存档分类
最新评论

JSP&Servlet学习笔记----第5章

阅读更多

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学习笔记(第二版)课后答案

    吉林大学珠海学院JSP&Servlet学习笔记(第二版)课后答案

    JSP &amp; Servlet学习笔记(第2版)

    书 名:JSP & Servlet学习笔记(第2版) 作 者:(台湾)林信良 著 出 版 社:清华大学出版社 出版时间:2012-5-1 ISBN:9787302283669 纸书页数:456页 定 价:¥ 58.00 内容简介: 本书是作者多年来...

    JSP网络编程学习笔记源代码 part2

    第五篇为“标签语言和表达式语言”,主要讲述JSP的标签技术,JSP提供的标准标签库JSTL的用法及用户如何自定义自己的标签库;第六篇为“Web应用高级专题”,主要讲述Servlet过滤器、JSP异常处理、JSP日志、认证和安全...

    Java学习笔记-个人整理的

    {5.2.1}将浮点数四舍五入到指定精度}{98}{subsection.5.2.1} {6}Exception}{99}{chapter.6} {6.1}\ttfamily try-catch}{99}{section.6.1} {6.2}\ttfamily finally}{100}{section.6.2} {6.3}\ttfamily throws}{...

    Java/JavaEE 学习笔记

    Servlet学习笔记..............212 Servlet前言.............212 第一章 Servlet Basic ........................214 第二章 Form表单.219 第三章 Servlets生命周期................222 第四章 资源访问 ..............

    J2EE学习笔记(J2ee初学者必备手册)

    Servlet学习笔记..............212 Servlet前言.............212 第一章 Servlet Basic ........................214 第二章 Form表单.219 第三章 Servlets生命周期................222 第四章 资源访问 ..............

    java jdk7 学习笔记

    再看第二本《java核心技术卷1-基础知识》,bruce eckel推荐的入门书籍。 第三本是《java核心技术卷2-高级特性》。 第四本是bruce eckel本人编写...第五本是《head first servlet &jsp》。 第六本是《head first ejb》。

    J2EE学习笔记

    第五章:软件系统架构设计 167 第六章:J2EE专题学习 167 6.1:EJB 167 6.2:JMS 172 6.3:Socket 182 6.4:WebService 189 6.5:集群分布式应用(以JBOSS为例) 190 6.6:JNLP原理及应用: 190 6.7:Log4原理及应用: 191 ...

    java jdk8 学习笔记

    第一章 1.Java 编程语言刚开始 Oak 橡树 办公室外 已被注册 边喝咖啡边讨论名称 2.动态加载类别文档、字符串池(String Pool)等特性为节省内存而设计 3.jdk java development kit java 开发工具集 java se 平台...

    整理后java开发全套达内学习笔记(含练习)

    以“%”开头,[第几个数值$][flags][宽度][.精确度][格式] printf()的引入是为了照顾c语言程序员的感情需要 格式化输出 Formatter;格式化输入 Scanner;正则表达式 输出格式控制: 转义符: \ddd 1到3位8...

Global site tag (gtag.js) - Google Analytics