第二个Listerner
<listener-class>com.sun.j2ee.blueprints.petstore.controller.web.SignOnNotifier</listener-class>
</listener>
Filter与Listener是Servlet2.3增加的功能,Filter可以在接受使用者的Request之后,做一些检查处理,若没问题则把使用者要求的Response丢回给使用者,反之则丢回系统预设的处理画面,最常使用的情况就是登入,在网页应用系统中有些功能是必须登入才能使用,过去的做法我们会将登入检查写在这些个别功能上,如此会造成登入检查若要修正,则必须逐支修改,造成时间浪费,运用Filter,我们可将登入检查程序与其它程序独立,日后容易维护。Listener则是增加对Context,Session生命周期的控制,例如我们能够在Session初始化时,将所需使用的资料一起产生,并将Reference存入Session,Seesion关闭时可顺便将相关资源移除,如此资源集中控管,容易维护。
Encoding Filter
它的程序代码位置在
Petstore_home\src\components\encodingfilter\src\com\sun\j2ee\blueprints\encodingfilter\web\EncodingFilter.java
,它会再读取web.xml(位置在Petstore_home\src\apps\petstore\src\docroot\WEB-INF\web.xml)中的参数,决定编码方式再将其设入Request中:
web.xml
<!-- Encoding Filter Declaration Start -->
<filter>
<filter-name>EncodingFilter</filter-name>
<display-name>EncodingFilter</display-name>
<description>no description</description>
<filter-class>com.sun.j2ee.blueprints.encodingfilter.web.EncodingFilter
</filter-class>
<init-param> //设定编码方式参数
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
EncodingFilter.java
public class EncodingFilter implements Filter {
private FilterConfig config = null;
// default to ASCII
private String targetEncoding = "ASCII";
//初始化时读取参数
public void init(FilterConfig config) throws ServletException {
this.config = config;
this.targetEncoding = config.getInitParameter("encoding");
}
public void destroy() {
config = null;
targetEncoding = null;
}
//将编码方式参数存入reqeust,结束此Filter
public void doFilter(ServletRequest srequest, ServletResponse sresponse,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)srequest;
request.setCharacterEncoding(targetEncoding);
// move on to the next
chain.doFilter(srequest,sresponse);
}






