Servlet分为三种:
n 普通的servlet
n 过滤器servlet
n 监听器servlet
过滤器:
实现的接口: javax.servlet.Filter
该接口的三个方法为:
public void init(FilterConfig config)throws ServletException{}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException,ServletException{}
public void destory(){}
在上表中有FilterChain接口,该接口最主要的方法是:
doFilter( ServletRequest request, ServletResponse response ){}
该方法实现了向下一个过滤器的跳转或者servlet的跳转;
例子:编码过滤
下面是一个jsp表单页面输入文本信息后跳转到另一个页面打印出来,如果不加入Filter的话会出现打印页面乱码,当然可以再页面设置:request.setcharacerEncoding(“utf-8”);来解决页面乱码;
表单页:index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="form1" action="result.jsp" method="post">
输入内容:<input name="input" type="text">
<input type="submit" value="提交">
</form>
</body>
</html>
打印结果页:result.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String str = request.getParameter("input");
%>
<%=str%>
</body>
</html>
过滤器:Filter.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package filter.demo;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* @author Administrator
*/
public class FilterTest implements Filter{
private String setCharacter = null;
public void init(FilterConfig config)throws ServletException{
setCharacter = config.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)
throws IOException,ServletException{
request.setCharacterEncoding(this.setCharacter);
chain.doFilter(request, response);
}
public void destroy() {
}
}
配置文件:web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>fitlerservlet</filter-name>
<filter-class>filter.demo.FilterTest</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>fitlerservlet</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>