Java custom interceptor method instance

  • 2020-04-01 03:57:02
  • OfStack

This article illustrates a Java custom interceptor and its use. Share with you for your reference. The details are as follows:

The logininterceptor.java file is as follows:


package com.tq365.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.tq365.vo.User;

public class LoginInterceptor extends AbstractInterceptor{
  private static final long serialVersionUID = 1406123004582563032L;
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = ServletActionContext.getRequest().getSession();
    User user = (User)session.getAttribute("USER");
    //The requested url
    String path = request.getServletPath();
    boolean flag = false;
    if("/loginuser.jspx".equals(path)){
      flag = true;
    }else{
      if(user!=null){
        flag = true;
      }
    }
    System.out.println(path);
    return flag ? invocation.invoke() : "error";
  }
}

Struts.xml file is as follows:


<interceptors>
  <!-- login The interceptor  -->
  <interceptor name="login" class="com.tq365.util.LongInterceptor"/>
  <interceptor-stack name="myInterceptor">
 <interceptor-ref name="login"/>
 <interceptor-ref name="paramsPrepareParamsStack"/>
  </interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInterceptor"/>

I hope this article has been helpful to your Java programming.


Related articles: