非法文字过滤器
非法文字过滤器:指对页面提交的内容中包含服务器不期望包含的信息(一般表现为字符)。服务器将不接受其提交的信息,并进行相应的非法输入信息提示。如论坛中的防灌水、垃圾回复或者不良信息等。
一、非法文字过滤器的实现:
下面以一个页面提交信息:发言页面的发言信息进行过滤。如非法信息定义为“晕”。相应的处理流程为:
该范例中包含了5个文件:发言页面charForm.jsp、非法文字过滤器charFilter.java、发言成功页面showContent.jsp、发言失败页面sendFailure.jsp和web.xml.
1、发言页面charForm.jsp
<%@ page language="java" contentType="text/html;charset=gb2312"%> <html> <head> <title>用户表单</title> </head> <body> <%--表单,提交方式为post-,提交到DoGetDemo--%> <form action="ShowContent.jsp" method="post"> 用户名:<input type="text" name="username"/><br> 发言:<br> <textarea name="charContent" rows="20" cols="40"></textarea><br> <input type="submit" value="发送"/> <input type="reset" value="重置"/> </form> </body> </html>
发言内容为文本域charContent的值。将发言提交到ShowContent.jsp。
2、非法文字过滤器charFilter.java
package Filter;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CharFilter implements Filter{
//初始化方法
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("非法文字过滤器初始化");
}
//过滤方法
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
//设置参数编码格式
request.setCharacterEncoding("gb2312");
//接受聊天内容
String charContent = request.getParameter("charContent");
if(charContent != null) {
if(charContent.indexOf("晕")== -1) {
chain.doFilter(req, res);
} else {
request.getRequestDispatcher("SendFailure.jsp").forward(req, res);
}
} else {
chain.doFilter(req, res);
}
}
//销毁方法
public void destroy() {
System.out.println("非法文字过滤器销毁");
}
}
若发言charContent中 含有‘晕’,则跳转到SendFailure.jsp。
3、发言成功页面showContent.jsp
<%@ page language="java" contentType="text/html;charset=gb2312"%> <html> <head> <title>发言成功</title> </head> <body> <center> <h1>发言成功</h1> 用户名:${param.username}<br> 发言内容:${param.charContent} </center> </body> </html>
用EL表达式提取并显示charForm.jsp中提交的username和charContent信息。
4、发言失败页面sendFailure.jsp
<%@ page language="java" contentType="text/html;charset=gb2312"%> <html> <head> <title>发言失败</title> </head> <body> <center> <h1>发言失败,含有非法文字</h1> </center> </body> </html>
过滤出来了发言中含有非法字符,提示用户发言失败。
5、在web.xml中进行过滤器的配置
<filter> <filter-name>charFilter</filter-name> <filter-class>Filter.charFilter</filter-class> </filter> <filter-mapping> <filter-name>charFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>