servlet API中最重要的一个功能就是能够为servlet和JSP页面定义过滤器。过滤器提供了某些早期服务器所支持的非标准“servlet链接”的一种功能强大且标准的替代品。 过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上。过滤器可附加到一个或多个servlet或JSP页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作如下的选择: 1. 以常规的方式调用资源(即,调用servlet或JSP页面)。 2.利用修改过的请求信息调用资源。 3. 调用资源,但在发送响应到客户机前对其进行修改 4. 阻止该资源调用,代之以转到其他的资源,返回一个特定的状态代码或生成替换输出。 |
|
过滤器提供了几个重要好处。
xml version="1.0" encoding="ISO-8859-1"
?>
DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > < web-app > < filter > < filter-name > MyFilter filter-name > < filter-class > myPackage.FilterClass filter-class > filter > < filter-mapping > ... filter-mapping > web-app >
xml version
=
"
1.0
"
encoding
=
"
ISO-8859-1
"
?>
DOCTYPE web - app PUBLIC " -//Sun Microsystems, Inc.//DTD Web Application 2.3//EN " " http://java.sun.com/dtd/web-app_2_3.dtd " > < web - app > < filter > < filter - name > MyFilter filter - name > < filter - class > myPackage.FilterClass filter - class > filter > < filter - mapping > < filter - name > MyFilter filter - name > < url - pattern >/ someDirectory / SomePage.jsp url - pattern > filter - mapping > web - app >
<
filter
>
< filter-name > SomeFilter filter-name > < filter-class > somePackage.SomeFilterClass filter-class > filter > < filter-mapping > < filter-name > SomeFilter filter-name > < servlet-name > SomeServlet servlet-name > filter-mapping >
<
filter
>
< filter-name > SomeFilter filter-name > < filter-class > somePackage.SomeFilterClass filter-class > filter > < filter-mapping > < filter-name > SomeFilter filter-name > < servlet-name >/Blah servlet-name > filter-mapping >
xml version="1.0" encoding="ISO-8859-1"
?>
DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > < web-app > < servlet > < servlet-name > Error servlet-name > < servlet-class > somePackage.ErrorServlet servlet-class > servlet > < servlet-mapping > < servlet-name > Error servlet-name > < url-pattern > /servlet/* url-pattern > servlet-mapping > web-app >
package moreservlets.filters;
import java.io. * ; import javax.servlet. * ; import javax.servlet.http. * ; import java.util. * ; // For Date class /* * Simple filter that prints a report on the standard output * each time an associated servlet or JSP page is accessed. */ public class ReportFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; System.out.println(req.getRemoteHost() + " tried to access " + req.getRequestURL() + " on " + new Date() + " . " ); chain.doFilter(request,response); } public void init(FilterConfig config) throws ServletException { } public void destroy() {} }
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> moreservlets.filters.ReportFilter moreservlets.TodaysSpecialServlet
------------------------------------------------------------------------------------------------------------------
下面是一个完整的例子:
testFilter.java
//建立一个实现Filter接口的类。这个类需要三个方法,分别是:doFilter、init和destroy。
//doFilter方法包含主要的过滤代码,init方法建立设置操作,而destroy方法进行清 package filterpkg; import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
public class testFilter implements Filter{
public void init(FilterConfig filterConfig) throws ServletException
{ } //在doFilter方法中放入过滤行为。doFilter方法的第一个参数为ServletRequest对象。 //此对象给过滤器提供了对进入的信息(包括表单数据、cookie和HTTP请求头)的完全访问。 //第二个参数为ServletResponse,通常在简单的过滤器中忽略此参数。 //最后一个参数为FilterChain,如下一步所述,此参数用来调用servlet或JSP页。 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) { PrintWriter wout=null; try { wout=response.getWriter(); } catch(IOException e) { } HttpServletRequest req=(HttpServletRequest)request;//将request转化为它的子类HttpServletRequest String uri=req.getRequestURI();//获得传入的URI if (uri.indexOf("MyJsp.jsp")>0 ||uri.indexOf("MainForm.do")>0 )//如果是我们指定的登录页面或验证页面 { try { //调用FilterChain对象的doFilter方法。Filter接口的doFilter方法取一个FilterChain对象作为它的一个参数。 //在调用此对象的doFilter方法时,激活下一个相关的过滤器。如果没有另一个过滤器与servlet或JSP页面关联,则servlet或JSP页面被激活。 filterChain.doFilter(request, response); } catch(Exception e) { } return; } if (req.getSession()!=null) if (req.getSession().getAttribute("USERID")==null) { wout.write(" Check error! "); wout.flush(); return; } try { filterChain.doFilter(request, response); } catch(Exception e) { } } public void destroy() { } } MyJsp.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="java.util.*" %>
<%
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%//登录页面,过滤器的FilterChain对象将会激活这个页面,而提交form后的MainForm.do是用于检验用户登录的servlet //注意这里的MainForm.do是在web.xml中映射的虚拟目录。 %> <% Date dt=new Date(); String dstr="当前日期:" +dt.toString(); out.print(dstr); %> ControlServlet.java
package filterpkg;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.*;
//写一个类,继承HttpServlet,就是Servlet
public class ControlServlet extends HttpServlet {
public ControlServlet() {
super(); }
public void destroy() {
super.destroy(); // Just puts "destroy" string in log // Put your code here }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" out.println(" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" "); out.println(""); out.flush(); out.close(); }
/**
* The doPost method of the servlet. * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String Eno,pwd,empname; Eno=request.getParameter("ENO");//request是servlet的内置对象,我们可以直接调用 pwd=request.getParameter("PWD"); try { Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//注册数据库驱动 } catch(Exception e) { } try { //连接数据库 Connection cnn=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;DataBaseName=jyx","sa","" ); //产生Statement对象 Statement st=cnn.createStatement(); //返回结果集 ResultSet rs= st.executeQuery("select * from employee where code='"+Eno+"' and password='"+pwd+"'"); if (rs.next())//如果记录存在 { HttpSession se= request.getSession(true); empname=rs.getString("NAME"); se.setAttribute("USERID",Eno);//记录在session中 se.setAttribute("PASSWORD",pwd); request.setAttribute("NAME", empname); RequestDispatcher dispatcher=request.getRequestDispatcher("MainForm.jsp"); dispatcher.forward(request,response); } else { // MyJsp.jsp } rs.close(); st.close(); cnn.close(); } catch(SQLException e ) { } }
/**
* Initialization of the servlet. * * @throws ServletException if an error occure */ public void init() throws ServletException { // Put your code here }
}
MainForm.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%=request.getAttribute("NAME")%> This is my JSP page. web.xml xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> |