Head-First Servelts&JSP reading note 3

<servlet>
  <servlet-name>BeerParamTests</servlet-name>
  <servlet-class>TestInitParams</servlet-class>
  <init-param>
    <param-name>adminEmail</param-name>
    <param-value>[email protected]</param-value>
  </init-param>
</servlet>

web.xml中的片段。

这个片段针对的是TestInitParams这个servlet。

getServletConfig()能够获得这个servlet相关的信息。

getServletConfig().getInitParameter("adminEmail");

能够获得对应的paramValue——[email protected]

当容器初始化一个Servlet的时候,会创建一个唯一对应的ServletConfig。

Container会从DD中读取相应的信息,绑定到这个ServletConfig对象上。

然后,调用Servlet类的init方法,把servletConfig对象的引用给Servlet对象。

ServletConfig对象的方法:

1 String getInitParameter(String);

2 Enumeration getInitParameterNames();  // Enumeration的一个实现类是StringTokenizer。。。

3 ServletContext getServletContext();

4 String getServletName();  // nearly with no use

<servlet>
  <servlet-name>BeerParamTests</servlet-name>
  <servlet-class>TestInitParams</servlet-class>
</servlet>
<context-param>
  <param-name>adminEmail</param-name>
  <param-value>[email protected]</param-value>
</context-param>

web.xml中的片段。

ServletContext,属于整个web-app,而不是某一个servlet。

this.getServletContext().getInitParameter("adminEmail");

this.getServletConfig().getServletContext().getInitParameter("adminEmail");

BOTH RIGHT!!! If the servlet extends HttpServlet or GenericServlet.

ServletContext对象的方法:

1 String getInitParameter(String)

2 Enumeration getInitParameterNames();

3 Object getAttribute(String);

4 getAttributeNames();

5 setAttribute(String, Object);

6 removeAttribute(String);

7 getRequestDispatcher(String);

Listener

有的时候需要在某一个或某些事件执行之前去完成一些工作,或之后完成一些工作。

这个工作可以让每一个servlet去实现,但是显得累赘,这个时候可以把这些工作提取出来,交给一个Java类去完成,这个java类就是一个Listener。

ServletContextListener

监听ServletContext的动作的监听器

public class SomeServletContextListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event){
    ServletContext sc = event.getServletContext;    String some = sc.getInitParameter("some");    Dog dog = new Dog(some);    sc.setAttribute("dog", dog);
  }
  public void contextDestoryed(ServletContextEvent event){
    // NOTHING TO DO HERE~
  }
}

设置监听器,在web.xml中,追加

<listener>
    <listener-class>xx.xx.SomeServletContextListener</listener-class>
</listener>

这样,Container就会去指定的位置寻找监听器类了,然后

Servlet类中,通过

Dog dog = (Dog) getServletContext().getAttribute(“dog”);

就可以获得这个dog对象了,注意强制类型转换。

其他类型的监听器:

ServletContextAttributeListener:用于监听ServletContext中的Attribute变动的。

  1. attributeAdded
  2. attributeRemoved
  3. attributeReplaced

HttpSessionListener:用于监听Session创建和销毁的,也就是说多少个用户在使用该程序。

  1. sessionCreated
  2. sessionDestroyed

ServletRequestListener:用于监听对该程序进行请求,以便对请求进行封装或者log情报打印等。

  1. requestInitialized
  2. requestDestroyed

等等。。。

ServletRequestAttributeListener

HttpSessionBindingListener

HttpSessionAttributeListener

HttpSessionActivationListener

所谓监听器,就是对某些东西进行监听,如追加,删除,变化,初始化和销毁。

Attribute的种类:ServletContext,HttpSession,HttpServletRequest

Parameter的种类:ServletContext init Parameter,Request Parameter,ServletConfig init Parameter

可以对Attribute进行设定,如this.getServletContext().setAttribute("Some", new Some());

但是不能对parameter进行修改。

可以获取Attribute和Parameter,但是Attribute的返回类型是Object,而Parameter返回类型是String,如:

Object o = request.getAttribute("Some");

String str = request.getParameter("Some");

String str = this.getServletConfig().getInitParameter("Some");

Attribute的存在的三个区域:

Context:ServletContext,对所有的用户可见;

Session:HttpSession,只对当前Session可见;

Request:ServletRequest,只对当前请求可见。

Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
Enumeration getAttributeNames()

Context Scope is not thread-safe

因为application的任何一个用户都可以新建一个servletcontext的一个attribute,当然也有修正和删除它的权利。

所以放到servletContext中的attribute不能保证其安全性。

syncronized(this.getServletContext) 能够保障其线程安全性。

HttpSession Scope is not thread-safe

synchronized(request.getSession());

HttpServletRequest Scope is thread-safe.

RequestDispatcher有两种获得方式,一种是通过request,一种是通过ServletContext

RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);

RequestDispatcher view = getServletContext().getRequestDispatcher(“/result.jsp”);

注意:他俩是相当不同的!!!

request的方式的话,如果参数是以"/"开头的话,它回去该项目的root目录下去寻找该页面,否则他会去request的相对路径下去寻找页面。

servletContext,只能以用“/”开头的字符串作为参数!

之后就可以用这个view.forward(request, response);了。

You can’t forward the request if you’ve already committed a response!

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  response.setContentType(“application/jar”);
  ServletContext ctx = getServletContext();
  InputStream is = ctx.getResourceAsStream(“bookCode.jar”);
  int read = 0;
  byte[] bytes = new byte[1024];
  OutputStream os = response.getOutputStream();
  while ((read = is.read(bytes)) != -1) {
    os.write(bytes, 0, read);
  }
  os.flush();  // cause an illegalStateException
  RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
  view.forward(request, response);
  os.close();
}

Head-First Servelts&JSP reading note 3

时间: 2024-08-27 19:43:50

Head-First Servelts&JSP reading note 3的相关文章

Head-First Servelts&amp;JSP reading note 4

HttpSession Http协议 Http协议是无状态的stateless,所以一个用户对服务器访问的话,不管多少次,服务器都会像第一次被访问一样.也就是说服务器不会区别用户. 一个请求过来,服务器会给一个相应,然后之间的联系就断了. Session 如何让服务器能够识别出来两个请求是来自同一个客户的呢?设置一个唯一的ID,这个ID叫做SessionId. 当服务器响应一个请求的时候,会附带着把这个sessionId放到response中,在紧接着的request的时候,会把这个sessio

Head-First Servelts&amp;JSP reading note 5

Filter 过滤器就是一个对所有的请求进行intercept(拦截),然后对请求进行相应的处理,或者servlet处理完成之后,对response进行处理等. 而这一切,servlet永远不可能知道. Filter和Servlet的相同点 1 容器也知道Filter的API 一旦一个java类实现了Filter接口,他就正式的成为了一个过滤器,容器中它也就被注册了. 2 容器管理他们的生命周期 他们也有init和destory方法,不同的是servlet有service方法(doGet/doP

thinking in java ----reading note (1)

# thinking in java 4th# reading note# victor# 2016.02.10 chapter 1 对象入门 1.1 抽象的进步    (1) 所有东西都是对象.    (2) 程序是一大堆对象的组合,对象间通过消息联系.    (3) 通过封装现有对象,可制作出新型对象.    (4) 每个对象都有一种类型(某个类的实例).    (5) 同一类的所有对象都能接受相同的消息.    1.2 对象的接口 & 1.3 实现方法的隐藏     接口规定了可对一个特定

jQueryInAction Reading Note 7.

jQuery插件命名规则 jquery.pluginName.js pluginName指代的是插件的名称,如voctrals,tlaliu或者更有意义的名称. 简化jQuery函数的参数列表 如果有一个函数有多个参数,但是并不是每一个参数都是必须的,可以把必须的参数放到前面,不必须的参数包装成一个object. 如: function complex(param, options){ var settings = $.extend( { option1 : defaultValue1, opt

jQueryInAction Reading Note 6.

这一章的前面一部分实在是无法理解,略过吧... $.noConflict() 无参数,无返回值,是用来把$符号交给其它的javascript库的. 但是并没有放弃使用jQuery的意思,jQuery仍然可以使用,并且可以把jQuery指派给另外一个别的名称,如$j,但是仍然会让人不爽. 但是如果在调用了$.noConflict()方法之后,还是想要使用$的话,可以使用一种方法,这种方法说白了就是设定一个形式参数$,而形式参数对应着的实体参数是jQuery,也就是说使用函数的方式. functio

thinking in java -----reading note(2)

# thinking in java 4th# reading note# victor# 2016.02.16 chapter 2 一切都是对象 2.1 用句柄操纵对象    使用句柄作为标识符指向一个对象.但拥有句柄并不意味着有一个对象同它连接.    例如,创建一个String句柄: String s;    此时,这里创建的是句柄,并不是对象.如果向s发一条消息,就会获得一个错误.因此,较为安全的做法是:创建一个句柄时,无论如何都进行初始化. 2.2 创建对象    通常使用 new 关

thinking in java ----reading note (3)

# thinking in java 4th# reading note# victor# 2016.03.13 chapter 3 控制程序流程 3.1 java 运算符    几乎所有运算符都只能操作"基本值类型"."=","=="和"!=" 能操作所有对象,String类支持"+"和"+=". 3.1.1 优先级    运算符的优先级决定了存在多个运算符时一个表达式个部分的计算顺序

jQueryInAction Reading Note 3.

属性和特性 操作元素属性 jQuery没有用于获取或者修改元素属性的命令.需要利用javascript,首先需要做的就是获得元素的引用. each(function) 对包装集中的各个元素,进行function操作,function有默认的参数为当前元素的位置,function具有当前对象this的引用. $("img").each(function(n){ this.alt = "this is " + n+1 + "th img, id is &quo

jQueryInAction Reading Note 5.

$(function(){ $('li:has(ul)') .click(function(event){ if (this == event.target){ if($(this).children().is(':hidden')){ $(this) .css('list-style-image', 'url(minus.gif)') .children().show(); } else { $(this) .css('list-style-image', 'url(plus.gif)') .