struts2 参数注入 方法拦截器

Posted 奋斗的孩子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2 参数注入 方法拦截器相关的知识,希望对你有一定的参考价值。

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee" id="WebApp_9" version="2.4">
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <package name="crm" namespace="/" extends="struts-default" >
    <interceptors>
      <interceptor name="myInter" class="com.huawei.interceptor.MyInterceptor" />
      <interceptor name="myMethodInter" class="com.huawei.interceptor.MyMethodInterceptor" >
        <param name="includeMethods">test1,test3</param>
        <!-- <param name="excludeMethods">test2,test4</param> -->
      </interceptor>
      <interceptor-stack name="myStack">
        <!-- 拦截器的执行顺序是根据 interceptor-ref的前后顺序-->
        <!-- <interceptor-ref name="defaultStack" /> -->
        <!-- <interceptor-ref name="myInter" /> -->
        <interceptor-ref name="myMethodInter" />
        <!-- <interceptor-ref name="token" /> -->
      </interceptor-stack>
    </interceptors>
    <default-interceptor-ref name="myStack" />
    <!-- 全局result -->
    <global-results>
      <result name="success">/ok.jsp</result>
    </global-results>
  </package>
  <package name="default" namespace="/" extends="crm">
    <action name="firstAction" class="com.huawei.s2.action.FirstAction" >
      <!-- <result name="invalid.token" >/error.jsp</result> -->
    </action>
  </package>
</struts>

1.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>This is my JSP page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  <body>
    <form action="firstAction">
      <input name="uname" value="zhangsan"><br>
      <input name="sal" value="10000.0"><br>
      <%-- <s:token></s:token> --%>
      <input type="submit" value="提交">
    </form>
  </body>
</html>

MyInterceptor:

package com.huawei.interceptor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
* 要么实现 Interceptor 接口 要么 继承类
* @author Administrator
*
*/
public class MyInterceptor extends AbstractInterceptor{
  //以下要实现参数注入的功能
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Object actionObj =invocation.getAction();//获取action
    Class clazz = actionObj.getClass();//action对象对应的反射对象
    Map<String, Object> paramsMap = ActionContext.getContext().getParameters();
    if(paramsMap!=null&&paramsMap.size()>0){
      for(String key:paramsMap.keySet()){
        Field field = clazz.getDeclaredField(key);
        String setterName = "set"+key.substring(0,1).toUpperCase()+key.substring(1);
        Method setterMethod = clazz.getDeclaredMethod(setterName, field.getType());
        String[] mapValue = (String[]) paramsMap.get(key);
        if(field.getType()==Double.class){
          setterMethod.invoke(actionObj, Double.parseDouble(mapValue[0]));
        }else {
          setterMethod.invoke(actionObj, mapValue[0]);
        }
      }
    }
    invocation.invoke();
    return null;
  }
}

MyMethodInterceptor:

package com.huawei.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/**
* function:方法拦截器
* @author Administrator
*
*/
public class MyMethodInterceptor extends MethodFilterInterceptor {

  @Override
  protected String doIntercept(ActionInvocation invocation) throws Exception {
    System.out.println("方法执行前");
    invocation.invoke();
    System.out.println("方法执行后");
    return null;
  }
}

action:

package com.huawei.s2.action;
public class FirstAction {
  private String uname;
  private Double sal;
  public String execute(){
    System.out.println(uname+"========FirstAction======="+sal);
    return "success";
  }
  /**
  * test1()~test4():是用于验证方法拦截器的
  */
  public void test1(){
    System.out.println("=======FirstAction =========test1=====");
  }
  public void test2(){
    System.out.println("=======FirstAction =========test2=====");
  }
  public void test3(){
    System.out.println("=======FirstAction =========test3=====");
  }
  public void test4(){
    System.out.println("=======FirstAction =========test4=====");
  }
  public String getUname() {
    return uname;
  }
  public void setUname(String uname) {
    this.uname = uname;
  }
  public Double getSal() {
    return sal;
  }
  public void setSal(Double sal) {
    this.sal = sal;
  }
}

以上是关于struts2 参数注入 方法拦截器的主要内容,如果未能解决你的问题,请参考以下文章

struts2 拦截器,使用spring注入

Java实战之01Struts2-03属性封装类型转换数据验证

框架总结

Struts2 源码分析-----拦截器源码解析 --- ParametersInterceptor

为啥struts2的拦截器会导致session为空呢?

struts2拦截器过滤放行后ajax请求后参数丢了