示例:定义一个Filter,用于用户发言中出现的“晕”字,即如果没有这个字则允许发言,如果有这个字则不允许发言并提示错误。
CharForm.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 3 <html> 4 <head></head> 5 6 <body> 7 <%-- 表单,提交方式为post,提交到DoGetDemo --%> 8 <form action="ShowContent.jsp" method="post"> 9 用户名:<input type="text" name="username"><br /> 10 发言:<br /> 11 <textarea name="charContent" rows="20" cols="40"></textarea><br /> 12 <input type="submit" value="提交"> 13 <input type="reset" value="重置"> 14 </form> 15 </body> 16 </html>
浏览器显示:
CharFilter.java
1 package com.mhb; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 13 public class CharFilter implements Filter { 14 15 public void init(FilterConfig arg0) throws ServletException { 16 System.out.println("非法文字过滤器初始化!"); 17 } 18 public void doFilter(ServletRequest arg0, ServletResponse arg1, 19 FilterChain arg2) throws IOException, ServletException { 20 //设置参数的接收格式 21 HttpServletRequest request = (HttpServletRequest)arg0; 22 //设置参数的编码格式 23 request.setCharacterEncoding("utf-8"); 24 //接收聊天内容 25 String charContent = request.getParameter("charContent"); 26 27 if(charContent != null){ 28 // 等号右边的-1表示没有找到该字符串, 29 //0表示该字符串位于第一个字符,1表示位于第二个字符。 30 if(charContent.indexOf("晕")== -1){ 31 arg2.doFilter(arg0, arg1); 32 }else{ 33 request.getRequestDispatcher("/SendFailure.jsp").forward(arg0, arg1); 34 } 35 }else{ 36 arg2.doFilter(arg0, arg1); 37 } 38 } 39 public void destroy() { 40 System.out.println("非法文字过滤器销毁!"); 41 } 42 }
ShowContent.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 3 <html> 4 <head><title>发言成功!</title></head> 5 <body> 6 <center> 7 <h1>发言成功</h1> 8 用户名:${param.username}<br /> 9 发言内容:${param.charContent } 10 </center> 11 </body> 12 </html>
SendFailure.jsp
1 SendFailure .txt 2 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 3 4 <html> 5 <head><title>发言失败</title></head> 6 7 <body> 8 <center> 9 <h1>发言失败,含有非法字符!</h1> 10 </center> 11 </body> 12 </html>
web.xml配置
<filter> <filter-name>CharFilter</filter-name> <filter-class>com.mhb.CharFilter</filter-class> </filter> <filter-mapping> <filter-name>CharFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
以上为所涉及到的代码,下面输入不含“晕”的发言内容
发言内容中包含“晕”字,直接跳转到发言失败页面。
时间: 2024-10-18 02:04:38