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 参数注入 方法拦截器的更多相关文章

  1. Struts2之类范围拦截器和方法拦截器

    1.Struts2拦截器的体系结构 Struts2拦截器最大的特点是其透明性,即用户感觉不到它的存在,但我们在使用Struts2框架时,拦截器时时刻刻都在帮助我们处理很多事情. 包括: 文件上传 表单 ...

  2. 【Java EE 学习 69 上】【struts2】【paramsPrepareParamsStack拦截器栈解决model对象和属性赋值冲突问题】

    昨天有同学问我问题,他告诉我他的Action中的一个属性明明提供了get/set方法,但是在方法中却获取不到表单中传递过来的值.代码如下(简化后的代码) public class UserAction ...

  3. [Abp vNext 源码分析] - 3. 依赖注入与拦截器

    一.简要说明 ABP vNext 框架在使用依赖注入服务的时候,是直接使用的微软提供的 Microsoft.Extensions.DependencyInjection 包.这里与原来的 ABP 框架 ...

  4. 【struts2】预定义拦截器

    1)预定义拦截器 Struts2有默认的拦截器配置,也就是说,虽然我们没有主动去配置任何关于拦截器的东西,但是Struts2会使用默认引用的拦截器.由于Struts2的默认拦截器声明和引用都在这个St ...

  5. 使用struts2中默认的拦截器以及自定义拦截器

    转自:http://blog.sina.com.cn/s/blog_82f01d350101echs.html 如何使用struts2拦截器,或者自定义拦截器.特别注意,在使用拦截器的时候,在Acti ...

  6. Struts2基础学习(五)—拦截器

    一.概述 1.初识拦截器      Interceptor 拦截器类似前面学过的过滤器,是可以在action执行前后执行的代码,是我们做Web开发经常用到的技术.比如:权限控制.日志等.我们也可以将多 ...

  7. Node.js与Sails~方法拦截器policies

    回到目录 policies sails的方法拦截器类似于.net mvc里的Filter,即它可以作用在controller的action上,在服务器响应指定action之前,对这个action进行拦 ...

  8. Struts2基础-4-2 -struts拦截器实现权限控制案例+ 模型驱动处理请求参数 + Action方法动态调用

    1.新建项目,添加jar包到WEB-INF目录下的lib文件夹,并添加到builde path里面 整体目录结构如下 2.新建web.xml,添加struts2核心过滤器,和默认首页 <?xml ...

  9. 在struts2中配置自定义拦截器放行多个方法

    源码: 自定义的拦截器类: //自定义拦截器类:LoginInterceptor ; package com.java.action.interceptor; import javax.servlet ...

随机推荐

  1. ALGO-4_蓝桥杯_算法训练_结点选择

    问题描述 有一棵 n 个节点的树,树上每个节点都有一个正整数权值.如果一个点被选择了,那么在树上和它相邻的点都不能被选择.求选出的点的权值和最大是多少? 输入格式 第一行包含一个整数 n . 接下来的 ...

  2. C++ 获取类成员函数地址方法 浅析

    C语言中可以用函数地址直接调用函数:   void print ()   {   printf ("function print");   }   typdef void (*fu ...

  3. R语言学习——欧拉计划(1)Multiples of 3 and 5

    [题目一]If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. ...

  4. PHP中的urlencode,rawurlencode和JS中的encodeURI,encodeURIComponent

    PHP中的urlencode,rawurlencode和JS中的encodeURI,encodeURIComponent [PHP中的urlencode和rawurlencode] urlencode ...

  5. springMVC 是单例还是的多例的?

    曾经面试的时候有面试官问我spring的controller是单例还是多例,结果我傻逼的回答当然是多例,要不然controller类中的非静态变量如何保证是线程安全的,这样想起似乎是对的,但是不知道( ...

  6. flume系统使用以及与storm的初步整合

      Flume NG的简单使用可以参考介绍文档:http://blog.csdn.net/pelick/article/details/18193527,图片也来源此blog:       下载完fl ...

  7. 运用map并于执行期指定排序准则

    该例展示以下技巧: 如何使用map 如何撰写和使用仿函数 如何在执行期定义排序规则 如何在"不在乎大小写"的情况下比较字符串 #include<iostream> #i ...

  8. 「CQOI2016」K 远点对

    /* 考虑暴力 可以n ^ 2枚举点对 然后用一个容量为2k的小根堆来维护第k大 kd-tree呢就是来将这个暴力优化, 每次先找远的并且最远距离不如堆顶的话就不继续找下去 貌似挺难构造数据卡的 */ ...

  9. VS2015+Opencv半永久配置

    电脑W7 64位+VS2015+opencv3.0 刚开始学习opeencv很麻烦,配置的问题都弄了好久,一旦重装又出现很多问题,在网上看了一个论坛说的永久配置,特意记录一下! 第一步:下载openc ...

  10. UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 120: illegal multibyte sequence

    UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 120: illegal multibyte sequence f ...