- 编写index2.jsp文件,在该页面实现数据的输入与现实最终处理结果。代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>违规字符隐藏</title>
</head>
<body>
<form action="index2.jsp" method="post">
<table>
<tr>
<td align="center"><h3>过滤敏感字符</h3></td>
</tr>
<tr>
<td align="center">
<textarea rows="8" cols="50" name="text"></textarea></td>
</tr>
<tr>
<td align="center">
<input type="submit" name="Submit" value="过滤"></td>
</tr>
<tr>
<td align="center">
${requestScope.newstr}
</td>
</tr>
</table>
</form>
</body>
</html>
- 写过滤文件Replace.java文件,在该页面完成数据的处理,代码如下:
package com.lyq.CharactorFilter;
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;
public class Replace implements Filter {
private String str,newStr=null;
public Replace() {
// TODO Auto-generated constructor stub
}
String encoding = null;// 字符编码
public void init(FilterConfig filterCongig) throws ServletException {
encoding = filterCongig.getInitParameter("encoding");// 获取初始化参数
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (encoding != null) {// 判断字符编码是否为空
request.setCharacterEncoding(encoding);// 设置request字符编码
response.setContentType("text/html;charset=" + encoding);// 设置response字符编码
str = request.getParameter("text");//获得输入的数据
if (str!=null&&str!=""&&str.indexOf("白日")!=-1) {//判断是否有敏感字符,若没有敏感字符则返回值为-1
newStr = str.replaceAll("白日","**");//完成敏感字符的替换,获得新字符串
request.setAttribute("newstr", newStr);//将新得到的字符串保存在request对象范围内
}else {
request.setAttribute("newstr", str);
}
chain.doFilter(request, response);
}
}
public void destroy() {
encoding = null;
}
}
- web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Eleven</display-name>
<filter>
<filter-name>Replace</filter-name>
<filter-class>com.lyq.CharactorFilter.Replace</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping><!-- 过滤器映射 -->
<filter-name>Replace</filter-name><!-- 过滤器名称 -->
<url-pattern>/*</url-pattern><!-- URL映射 -->
</filter-mapping>
</web-app>
执行结果如下: