论坛首页 Java企业应用论坛

Spring+Struts整合AOP

浏览 6241 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-08-16  
废话少说,直接上代码
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<!-- Struts -->
	<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>
	<!-- Spring -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:config/spring/applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- utf-8编码 -->
	<filter>
		<filter-name>Spring character encoding filter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>Spring character encoding filter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>


applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 使Spring关注Annotation -->
	<context:annotation-config />
	
	<!-- 使用annotation 自动注册bean(@Respository,@Component),并检查@Required,@Autowired的属性已被注入 -->
	<context:component-scan base-package="com.action" />

	<bean id="testLog" class="com.aop.MyLog"></bean> <!--将日志类注入到bean中。 -->

	<aop:config>
		<aop:aspect id="b" ref="testLog"><!--调用日志类 -->
			<aop:pointcut id="log"
				expression="execution(* com.action.*.*(..))" /><!--配置在log包下所有的类在调用之前都会被拦截 -->
			<aop:before pointcut-ref="log" method="before" /><!--在log包下面所有的类的所有方法被调用之前都调用MyLog中的before方法 -->
			<aop:after pointcut-ref="log" method="after" />
			<!--在log包下面所有的类的所有方法被调用之前都调用MyLog中的after方法 -->
		</aop:aspect>
	</aop:config>
</beans>


MyLog.java
package com.aop;

import org.aspectj.lang.JoinPoint;

public class MyLog {
	public void before(JoinPoint joinpoint) {
		String classname = joinpoint.getTarget().getClass().getName();
		String method = joinpoint.getSignature().getName();
		Object[] args = joinpoint.getArgs();
		System.out.println("classname====" + classname);
		System.out.println("method====" + method);
		for (int i = 0; i < args.length; i++) {
			System.out.println("args[" + i + "]====" + args[i]);
		}
		System.out.println("方法执行前打印");
	}
	public void after(JoinPoint joinpoint) {
		System.out.println("方法执行后打印");
	}
}


BaseAction
package com.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

/**
 * @className:BaseAction.java
 * @classDescription:父类Action,包括一些通用的方法
 * @author:xiayingjie
 * @createTime:2010-6-24
 */
@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public abstract class BaseAction extends ActionSupport implements
		ServletRequestAware, ServletResponseAware {

	/** 进行增删改操作后,以redirect方式重新打开action默认页的result名. */
	public static final String RELOAD = "reload";

	protected HttpServletRequest request;
	protected HttpServletResponse response;

	boolean flag;

	// -- 定义Service --//

	// -- 简化分页 --//

	/**
	 * Action函数, 默认的action函数, 默认调用list()函数.
	 */
	public String execute() throws Exception {
		return list();
	}

	// -- CRUD Action函数 --//
	/**
	 * Action函数,显示Entity列表界面. return SUCCESS.
	 */
	public abstract String list() throws Exception;

	/**
	 * Action函数,显示新增或修改Entity界面. return INPUT.
	 */
	public abstract String alter() throws Exception;

	/**
	 * Action函数,新增或修改Entity. return RELOAD.
	 */
	public abstract String save() throws Exception;

	/**
	 * Action函数,删除Entity. return RELOAD.
	 */
	public abstract String delete() throws Exception;

	// -- 简化取值----//
	/**
	 * 取得HttpRequest中Parameter的简化方法.
	 */
	public String getParameter(String name) {
		return (null == this.request.getParameter(name)) ? null : this.request
				.getParameter(name);
	}

	/**
	 * 取得HttpRequest中Attribute的简化函数.
	 */
	public Object getRequestAttribute(String name) {
		return request.getAttribute(name);
	}

	/**
	 * 取得HttpSession中Attribute的简化函数.
	 */
	public Object getSessionAttribute(String name) {
		return this.getSession().getAttribute(name);
	}

	/**
	 * 取得HttpSession的简化函数.
	 */
	public HttpSession getSession() {
		return request.getSession();
	}

	/**
	 * 设置HttpRequest中Attribute的简化函数.
	 */
	public boolean setRequestAttribute(String key, Object object) {
		try {
			flag = false;
			request.setAttribute(key, object);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;

	}

	/**
	 * 设置HttpSession中Attribute的简化函数.
	 */
	public void setSessionAttribute(String name, Object object) {
		getSession().setAttribute(name, object);
	}

	/**
	 * 获取根目录
	 */
	public String getRoot() {
		return request.getContextPath();
	}

	/**
	 * 获取根目录
	 */
	public String getRealRoot() {
		return this.getSession().getServletContext().getRealPath("/");
	}

	// -------自动生成----------//
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;

	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;

	}

	// ---------自动生成 service 的get set方法----------//
	/**
	 * @return the userManageService
	 */

}


UserManageAction.java
package com.action.manage;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.action.BaseAction;

@Namespace("/manage")
@Results({
		@Result(name = "success", location = "/index.jsp"),
		@Result(name = BaseAction.RELOAD, location = "/manage/user-manage.action", type = "redirect") })
public class UserManageAction extends BaseAction {
	// 此类中方法可以写任意多个。我只写一个

	/**
	 * 
	 */
	private static final long serialVersionUID = -2536997671753457354L;

	public String test() {
		System.out.println("测试类的test方法被调用");
		return "success";
	}

	@Override
	public String list() throws Exception {
		System.out.println("测试类的list方法被调用");
		return "success";
	}

	@Override
	public String alter() throws Exception {
		System.out.println("测试类的alter方法被调用");
		return RELOAD;
	}

	@Override
	public String save() throws Exception {
		System.out.println("测试类的save方法被调用");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		System.out.println("测试类的delete方法被调用");
		return RELOAD;
	}
}


index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
	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%>">

		<title>My JSP 'index.jsp' starting 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">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	</head>

	<body>
		<a href="<%=basePath%>manage/user-manage.action">list</a>
		<br />
		<a href="<%=basePath%>manage/user-manage!delete.action">delete</a>
		<br />
		<a href="<%=basePath%>manage/user-manage!test.action">test</a>
		<br />
		<a href="<%=basePath%>manage/user-manage!save.action">save</a>
		<br />
		<a href="<%=basePath%>manage/user-manage!alter.action">alter</a>

	</body>
</html>


代码能进入AOP,但是老是报错找不到这个方法异常,不知道是什么原因。
   发表时间:2011-08-16  
执行除开LIST方法以外的方法都会报这个异常java.lang.NoSuchMethodException:
不知道为什么 JAR在附件中~~~情高手看看
0 请登录后投票
   发表时间:2011-08-17  
前台请求
http://localhost:8080/test/manage/user-manage!delete.action
后台打印出
被拦截方法调用之后调用此方法,输出此语句
被拦截方法调用之后调用此方法,输出此语句
前台页面报
type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NoSuchMethodException: $Proxy11.delete()
	java.lang.Class.getMethod(Class.java:1605)
	org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.getActionMethod(AnnotationValidationInterceptor.java:75)
	org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:47)
	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
	com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
	com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
	org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
	org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
	org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
	org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)


不知道这是为什么~~~
0 请登录后投票
   发表时间:2011-08-18  
1、检查编译环境
2、是不是把最新编译出来的class文件都部署到服务器上了。
0 请登录后投票
   发表时间:2011-08-18  
显然没有定位到方法,你调用LIST成功 是因为你调用的是默认函数
0 请登录后投票
   发表时间:2011-08-18  
<a href="<%=basePath%>manage/user-manage!delete.action">delete</a>  
改成
<a href="<%=basePath%>manage/user-manage!delete">delete</a>  
试试
0 请登录后投票
   发表时间:2011-08-18  
jar包在哪。。。真麻烦
0 请登录后投票
   发表时间:2011-08-18  
@Namespace("/custom")
@Result(name="success",location="/index.jsp",type="dispatcher")
public class Test extends ActionSupport {
  @Action("/different/url")
  public String execute() {
	  System.out.println("execute");
    return SUCCESS;
  }

  @Action("url")
  public String doSomething() {
	  System.out.println("doSomething");
    return SUCCESS;
  }
}
0 请登录后投票
   发表时间:2011-08-18  
感觉还是你的baseAction写的有问题,我是指以注解的方式配置action的时候,可能少了某些注解。
如果你把BaseAction 换成 ActionSupport 然后再按照我上面的小例子写就可以正常找到方法了
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics