What is a filter

  • Struts2 interceptors intercept before or after accessing an Action method. Struts2 interceptors are pluggable, and interceptors are an implementation of AOP
  • Interceptor Stack: Connects interceptors in a chain in a certain order. When accessing an intercepted method, interceptors in the Struts2 interceptor chain are called in the order they were previously defined

Custom interceptors

steps

  1. Define a custom class that implements an Interceptor interface (deriving AbstractInterceptor or MethodFilterIntercepter).
  2. Register the interceptor defined in the previous step in struts.xml
  3. Reference the interceptor defined above in the Action you want to use

Examples to explain —- text filter design and application

Example: To develop an online forum filtering system, if there is uncivilized language published by users, it will automatically replace the uncivilized words through interceptors. It just gives a simple filter, filter whether there is “hate” text, if there is “hate”, then use “like” to replace the content to filter “hate”, form a new text content and display on the forum.

Custom interceptors

package interceptor;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class MyInterceptor extends AbstractInterceptor {
	public String intercept(ActionInvocation ai) throws Exception {
	   // Get all the attributes submitted for the page and their values
	   Map<String, Object> parameters = ai.getInvocationContext().getParameters();
	   // Filter each pair of attributes and attribute values, and save the filtered content to the attribute
	   for (String key : parameters.keySet()) {
	      Object value = parameters.get(key);
	      if( value ! =null && value instanceof String[]) {
	         String[] valueArray = (String[]) value;
	         for (int i = 0; i < valueArray.length; i++) {
	            if( valueArray[i] ! =null) {// Determine whether the comments submitted by users have content to be filtered
	                if(valueArray[i].contains("Hate")) { 
	                   // Replace "hate" with "like"
	                   valueArray[i] =valueArray[i].replaceAll("Hate"."Like");
	                   // Set the replacement comment content to the Action comment content
	                   parameters.put(key, valueArray);
	                 }
	              }
	           }
	        }
	     }
	   return ai.invoke();// Execute the next interceptor or Action}}Copy the code

Register your custom interceptor in struts.xml


      
<! DOCTYPEstruts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.custom.i18n.resources" value="globalMessages"/>
    <constant name="struts.i18n.encoding" value="UTF-8" /> 
    <package name="I18N" extends="struts-default">
        <interceptors>
             <! Replace is the name of the interceptor --> 
            <interceptor name="replace" class="interceptor.MyInterceptor" /> 
        </interceptors>
	 <action name="public" class="action.PublicAction"><! -- Text filter Action configuration -->
            <result name="success">/success.jsp</result> 
              <interceptor-ref name="replace"/>  <! -- Use custom interceptor -->
              
             <interceptor-ref name="defaultStack" />  <! Struts2 system default interceptor -->
        </action>
     </package>
</struts> 

Copy the code

Write actions that reference custom interceptors

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */
package action;

import com.opensymphony.xwork2.ActionSupport;

/ * * * *@author lenovo
 */
public class PublicAction extends ActionSupport {

    private String title;
    private String content;
    // Getters and setters for properties

    public String getTitle(a) {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent(a) {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
    

    public String execute(a) {
        returnSUCCESS; }}Copy the code

Interface design

  1. Comments on the interfaceindex.jsp
<%@ page language="java" pageEncoding="UTF-8"% > < %@taglib prefix="s" uri="/struts-tags"%> < HTML > <head> <title> comment </title> </head> <body> <hr> <s:form action="public" method="post">
              <s:textfield name="title" label="Comment title" maxLength="36"/>
              <s:textarea name="content" cols="36" rows="6" label="Comment content"/>
              <s:submit value="Submit"/>
	</s:form>
    </body>
</html>

Copy the code
  1. Comments are filtered and returned to the interfacesuccess.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%> < HTML > <head> <title> </title> </head> <body> <hr> <s:property value="title"<s:property value="content"/>
  </body>
</html>

Copy the code

The results of