Example: Define a filter for the "Halo" word that appears in the user's statement, that is, if the word is not available, the statement is allowed, and if there is a word, the statement is not allowed and the error is indicated.
charform.jsp
1<%@ page language= "Java"Import= "java.util.*" pageencoding= "Utf-8"%>2 345 6<body>7<%--form, submitted as post, submitted to Dogetdemo--%>8<form action= "showcontent.jsp" method= "POST" >9User name: <input type= "text" name= "username" ><br/>TenSpeech: <br/> One<textarea name= "Charcontent" rows= "-" cols= "></textarea><br/> A<input type= "Submit" value= "Submission" > -<input type= "reset" value= "reset" > -</form> the</body> -Browser display:
Charfilter.java
1 PackageCOM.MHB;2 3 Importjava.io.IOException;4 5 ImportJavax.servlet.Filter;6 ImportJavax.servlet.FilterChain;7 ImportJavax.servlet.FilterConfig;8 Importjavax.servlet.ServletException;9 Importjavax.servlet.ServletRequest;Ten ImportJavax.servlet.ServletResponse; One Importjavax.servlet.http.HttpServletRequest; A - Public classCharfilterImplementsFilter { - the Public voidInit (Filterconfig arg0)throwsservletexception { -SYSTEM.OUT.PRINTLN ("Illegal text filter initialization! "); - } - Public voidDoFilter (ServletRequest arg0, Servletresponse arg1, +Filterchain arg2)throwsIOException, servletexception { - //to set the receive format for a parameter +HttpServletRequest request =(HttpServletRequest) arg0; A //to set the encoding format for a parameter atRequest.setcharacterencoding ("Utf-8"); - //Receive chat content -String charcontent = Request.getparameter ("Charcontent"); - - if(Charcontent! =NULL){ - //The 1 to the right of the equal sign indicates that the string was not found. in //0 indicates that the string is at the first character and 1 is in the second character. - if(Charcontent.indexof ("halo") = =-1){ to Arg2.dofilter (arg0, arg1); +}Else{ -Request.getrequestdispatcher ("/sendfailure.jsp"). Forward (arg0, arg1); the } *}Else{ $ Arg2.dofilter (arg0, arg1);Panax Notoginseng } - } the Public voiddestroy () { +SYSTEM.OUT.PRINTLN ("Illegal text filter destroyed! "); A } the}
showcontent.jsp
1 Import= "java.util.*" pageencoding= "Utf-8"%> 2 3 4 5 <body> 6 <center> 7 8 user name: ${param.username}<br/> 9 speeches: ${param.charcontent} </center> </body>
sendfailure.jsp
1 sendfailure. txt 2 Import= "java.util.*" pageencoding= "Utf-8"%> 3 4 5 6 7 <body> 8 < Center> 9 </center> </body>
Web. XML configuration
<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>
The above is the code involved, the following input does not include "Halo" of the speech content
The speech contains the word "halo" and jumps directly to the failed speech page.
Filter for illegal characters