- 登陆页面login.jsp
<body>
<form action="${pageContext.request.contextPath }/encodeServlet" method="post">
username:<input type="text" name="username"/>
<input type="submit" value="POST方式提交"/>
</form>
<hr/>
<form action="${pageContext.request.contextPath }/encodeServlet" method="get">
username:<input type="text" name="username"/>
<input type="submit" value="GET方式提交"/>
</form>
</body>
- EncodeServlet中的内容
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type=request.getParameter("type");
if("mgString".equals(type))
{
String content=request.getParameter("content");
System.out.println(content);
}else
{
System.out.println(request.getClass());
String name = request.getParameter("username");
System.out.println(name);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("username");
System.out.println(name);
}
-
创建com.Demo.Filter下的EncodingFilter.Java文件,导入javax.servlet接口
-
在web.xml中在配置一个过滤器
<filter>
<filter-name>UserFilter</filter-name>
<filter-class>com.etc.filter.UserFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 往EncodingFilter中继续写内容
生成代理对象
Proxy代理——reflect反射包
HttpServletRequest 是接口
Proxy.newProxyInstance(目标对象的类加载器,目标对象的接口,对代理对象进行什么操作)
//请求乱码过滤器
public class UserFilter implements Filter {
List<String>list;
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// 转型
final HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 处理POST方式提交的数据的乱码问题
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 处理GET方式提交的数据乱码问题
// 要创建一个request对象的代理对象
HttpServletRequest proxy = (HttpServletRequest) Proxy.newProxyInstance(request.getClass().getClassLoader(),
new Class[] { HttpServletRequest.class }, new InvocationHandler() { // 处理器
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = null;
// 判断当前request对象的方法名称
String methodName = method.getName();
if ("getParameter".equals(methodName)) {
// 接受此方法的参数
String value = request.getParameter(args[0].toString());
// 判断请求方式-获取当前请求方法 GET POST
String methodSubmit = request.getMethod();
if ("GET".equals(methodSubmit)) {
// 对接收到的参数进行非空判断
if (!("".equals(value)) && value != null) {
// 对接收到的参数进行编码
value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
}
//进行敏感字符过滤
for(String str:list)
{
if(value.contains(str))
{
value=value.replace(str,"*");
}
}
}
return value;
} else {
returnValue = method.invoke(request, args);
}
return returnValue;
}
});
chain.doFilter(proxy, response);
}
public void init(FilterConfig fConfig) throws ServletException {
//创建敏感字符库
list=new ArrayList<String>();
list.add("诈");
list.add("骗");
list.add("恐");
}
public void destroy() {
}
}