在struts2.1中使用注解和拦截器实现权限细粒度控制

正如上一篇文章说的,拦截器是struts2的核心,同时struts2引入了注解的方式。这里就来简单看看针对struts2.1中使用注解和拦截器的开发。
首先要引入struts2.1各包,特别要引入Convention Plugin插件。

本文只是一个简单模拟,因此我们新建两个jsp文件,分别为登录和退出。
login.jsp

< %@ page language="java"  pageEncoding="GB18030"%>

< %
pageContext.getSession().setAttribute("user","huashui");
pageContext.getSession().setAttribute("rights","TEST_AUTH");
%>
登录成功

logout.jsp

< %@ page language="java" pageEncoding="GB18030"%>

< %
pageContext.getSession().removeAttribute("user");
pageContext.getSession().removeAttribute("rights");
%>
退出成功

index.jsp

< %@ page language="java" pageEncoding="GB18030"%>
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>主页</title>
	</head>
	<body>
		<p>
			${tip }
		</p>
		<a href="login.jsp">登录</a>
		<br />
		<a href="logout.jsp">退出</a>
		<br />
		<a href="admin/test.action">权限页面</a>
	</body>
</html>

建好了这三个页面后,我们开始来写注解。

package org.huashui.authentication;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *@author Huashui
 *@blog http://huashui.org
 */
@Retention(RetentionPolicy.RUNTIME)//指定该注解是在运行期进行
@Target({ElementType.METHOD})//指定该注解要在方法上使用
public @interface AuthName {
	 String value() default "";

}

注解本身不能起作用,注解起作用关键在于后台有一个解析器。接下来来写下这个解析器。

package org.huashui.authentication;

import java.lang.reflect.Method;

/**
 * @author huashui
 * @blog http://huashui.org
 */
public class ParseAuthName {
	public static String parseAuthentication(Class< ?> clazz, String methodName,
			Class< ?>... parameterTypes) throws NoSuchMethodException {
		//根据方法名,取得方法,如果有则返回
		Method method = clazz.getMethod(methodName, parameterTypes);

		if (null != method) {
			AuthName authName = method.getAnnotation(AuthName.class);
			if (null != authName) {
				return authName.value();
			}
		}

		return null;
	}
}

接下来书写拦截器

package org.huashui.interceptor;

import org.huashui.authentication.ParseAuthName;

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

/**
 * @authorhuashui
 * @blog http://huashui.org
 */
@SuppressWarnings("serial")
public class AuthInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext context = invocation.getInvocationContext();
		String user = (String) context.getSession().get("user");
		String rights = (String) context.getSession().get("rights");
		if (null != user) {
			ActionProxy proxy = invocation.getProxy();
			String methodName = proxy.getMethod();
			Object action = proxy.getAction();
			String auth = null;
			try {
				auth = ParseAuthName.parseAuthentication(action.getClass(),
						methodName, null);

			} catch (NoSuchMethodException e) {
				e.printStackTrace();
				ActionContext.getContext().put("tip", "没有权限");
				return Action.LOGIN;
			}

			if (null != auth) {
				if ("TEST_AUTH".equals(auth)) {
					return invocation.invoke();
				}
			}
			ActionContext.getContext().put("tip", "没有权限");
			return Action.LOGIN;
		} else {
			ActionContext.getContext().put("tip", "没有登录");
			return Action.LOGIN;
		}

	}

}

接下来配置下拦截器

< ?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="huashui-default" namespace="/admin"
		extends="struts-default">
		<interceptors>
			<interceptor name="auth"
				class="org.huashui.interceptor.AuthInterceptor">
			</interceptor>
			<interceptor -stack name="authdefault">
				</interceptor><interceptor -ref name="defaultStack"></interceptor>
				<interceptor -ref name="auth"></interceptor>

		</interceptors>
		<default -interceptor-ref name="authdefault"></default>
	</package>
</struts>

配好这些后,我们开始写Action进行测试

package org.huashui.action;

import org.apache.struts2.convention.annotation.Action;

import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.huashui.authentication.AuthName;

/**
 * @author 曾华水
 * @email email@huashui.org
 */
@ParentPackage("huashui-default")
@Namespace("/admin")
public class UserListAction {

	@AuthName(value = "TEST_AUTH")
	@Action(value = "test", results = {
			@Result(name = "success", location = "/WEB-INF/content/success.jsp"),
			@Result(name = "login", location = "/index.jsp")

	})
	public String execute() {
		return com.opensymphony.xwork2.Action.SUCCESS;
	}

}

完成。

相关日志

  • jqGrid进阶教程:3、jqGrid的数据格式化二
    jqGrid是非常强大的,除了上一讲提到的预置的格式化外,还提供自定义的格式化方法,这种方法也是我比较喜欢的方法。 我们接上面的例子 $("#grid_id").jqGrid({ ... colModel : [ {name:'sex', edittype:'select', editoptions:{value:"1:男;2:女"}} ... ], ... }); ...
  • jqGrid例子文件下载
    最近慵懒了很多,很少来上面博一博,发下jqGrid的例子的全部文件。 jqGrid 由于文件太大,删掉了所有的jar包,jar是整合struts2.1+spring2.5+hibernate3.2...
  • jqGrid进阶教程:1、jqGrid的样式无法正确显示的原因和解决办法
    jqGrid引入后,执行,常常会碰到css无法像官方的demo一样正常显示,特别是字体还有一些弹出框, 例如 [caption id="attachment_407" align="alignnone" width="300" caption="CSS变样"][/caption] 这种问题的原因多半是因为html的标准问题,即其写法为 如果要让样式正常,要采用写法如下 ...
  • jqGrid基础学习:11jqGrid的查询时和后台的交互
    jqGrid查询时和后台交互是一个比较棘手的问题,因为发送过来的数据不规则。 单字段 我们通过Firefox的firebug来进行调试,我们发现提交搜索请求后,向后台发送的参数如下 [caption id="attachment_382" align="alignnone" width="300" caption="单字段同后台交互"][/caption] 由此,我们看出单字段查询...
  • jqGrid基础学习:10jqGrid的多字段查询
    多字段查询就是高级查询,在jqGrid中,高级查询的麻烦在于同后台的交互。 [caption id="attachment_379" align="alignnone" width="718" caption="jqGrid多字段查询"][/caption] 启用多条件查询的方法,是加上.searchGrid({multipleSearch:true}); 即可。 ...

  1. Nhuvmljq 说道:

    Canada>Canada Loli Imgboard Pthc wpjtaz

  2. Rsivibbp 说道:

    On another call Hussyfan Kids avt

PO一下