Struct2_ defines the interceptor and uses annotations to act on the action's method

Source: Internet
Author: User

Objective: To control which methods need to be logged in order to access them by adding annotations to the method.

second, the way: the use of interceptors to determine whether the user login   Third, the realization step
  1. Defining a configuration file
    Struts.xml adding nodes
    1234567891011121314151617181920 <package name="custom-default" extends="struts-default">        <interceptors>            <!-- 声明自定义的权限控制拦截器 -->            <interceptor name="loginInterceptor" class="interceptors.LoginInterceptor" />            <!-- 把自定义的权限控制拦截器和默认的拦截器栈加到新的自定义的拦截器栈 -->            <interceptor-stack name="myInterceptors">                <interceptor-ref name="loginInterceptor" />                <interceptor-ref name="defaultStack" />            </interceptor-stack>        </interceptors>        <!-- 指定新的自定义的拦截器栈为默认的拦截器栈,这样自定义的权限控制拦截器就可以发挥作用了 -->        <!-- 这里name属性值对应的是上述interceptor-stack name属性值 -->        <default-interceptor-ref name="myInterceptors"></default-interceptor-ref>                <!-- 这里对应拦截器中return Action.LOGIN对应的页面-->        <global-results>            <result name="login">/WEB-INF/content/LoginInfo/login.jsp</result>        </global-results>    </package>
  2. Defining annotations

    Annotations are primarily on methods, and interceptors handle landing judgments based on whether the method defines annotations.

    123456789101112131415 package annotations; import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD})@Retention(value = RetentionPolicy.RUNTIME)public @interface Authority {     /**     * @return  The namespace value.     */    String value();}
  3. Defining interceptors

    123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 package interceptors;import java.lang.reflect.Method;import java.util.Map;import org.apache.struts2.convention.annotation.InterceptorRef;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import annotations.Authority;import common.Constants;@SuppressWarnings("serial")public class LoginInterceptor extends AbstractInterceptor {    @Override    public String intercept(ActionInvocation invocation) throws Exception {        String methodName = invocation.getProxy().getMethod();        Class clazz = invocation.getAction().getClass(); // 获取类对象        Method currentMethod = clazz.getMethod(methodName); //获取拦截的方法                //方法上添加了注解        if (currentMethod.isAnnotationPresent(Authority.class)) {            // 取得当前请求的注解的action            ActionContext context = invocation.getInvocationContext();            Map session = context.getSession();            //Constants.UserName=="UserName"            String user = (String) session.get(Constants.UserName);            System.err.println("拦截器起作用");            if (user == null) // 未登陆,跳转到登录页            {                System.err.println("进入拦截器:未登陆");                context.put("tip", "你还没有登录");                return Action.LOGIN;            } else {   //已登录,继续后续流程                System.err.println("进入拦截器:已登录");                return invocation.invoke();            }        } else {            System.err.println("进入拦截器:没有使用注解");            return invocation.invoke();        }    }}

  4. Defining action classes and methods
123456789101112131415161718192021222324252627 package action;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.InterceptorRef;import org.apache.struts2.convention.annotation.Namespace;import org.apache.struts2.convention.annotation.ParentPackage;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;import org.apache.struts2.interceptor.validation.SkipValidation;import annotations.Authority;import common.Constants;import org.apache.struts2.convention.annotation.InterceptorRefs;@SuppressWarnings("serial")@ParentPackage("custom-default")   //这里对应的配置文件中包的名称public class LoginAction extends SuperActionSupport {    @Action(value = "loginValidate", results = {            @Result(name = "success", location = "/WEB-INF/content/LoginInfo/success.jsp"),            @Result(name = "input", location = "/WEB-INF/content/LoginInfo/login.jsp") })    @Authority(""//定义注解后未登录回到登陆页,否则执行后续步骤    public String loginValidate() throws Exception {        return SUCCESS;    }}
  Iv. The pits encountered in the realization process
    1. Built-in annotations @interceptorrefs/@InterceptorRef can only be used on class files and not on methods (as can be seen from their @target properties)

    2. The annotation @parentpackage ("Custom-default") on the class must correspond to the Name property of the package in the Structs.xml, otherwise the annotation will not be effective

    3. The name value of the Default-interceptor-ref in Structs.xml corresponds to the name value of the Interceptor-stack, otherwise the annotation is not effective

v. References
    1. http://coolfire9201207034819.iteye.com/blog/1583802
    2. Http://www.codes51.com/article/detail_120593.html
    3. Http://www.cnblogs.com/linjiqin/archive/2013/06/21/3148129.html
    4. http://blog.csdn.net/z69183787/article/details/38440421
    5. http://blog.csdn.net/linchunhua/article/details/8494822

      ?





Struct2_ defines the interceptor and uses annotations to act on the action's method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.