使用拦截器实现通用的登陆验证和日志记录

本文介绍了如何使用Java手动实现拦截器,包括登录验证拦截器和日志记录拦截器,同时讲解了在Struts配置文件中添加拦截器标签和对应action的方法。
摘要由CSDN通过智能技术生成


拦截器手动实现,要实现相应的拦截器接口

登陆验证的拦截器:

@Component
public class CheckLoginInterceptor implements Interceptor {
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		Action action = (Action) invocation.getAction();
		if (action instanceof LoginAction) {
			String method = invocation.getProxy().getMethod();
		         if (method.equals("logout")) {
				 HttpServletRequest request = (HttpServletRequest) invocation
                                   .getInvocationContext().get(
				 ServletActionContext.HTTP_REQUEST);
				HttpSession session = request.getSession();
				 invocation.getInvocationContext().getSession();
				session.invalidate();// 清除缓存
				return "toLogin";
			} else {
				return invocation.invoke();
			}
		}else {
			BackUserModel pm = (BackUserModel) invocation.getInvocationContext()
					.getSession().get("personLogin");
			if (pm != null) {
				return invocation.invoke();
                        } else {
				return "toLogin";
			}
		}
	}

日志记录的拦截器:

@Component
public class LogInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = 2075536070042451457L;

	@Resource
	private LogService LogServiceImpl;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		// 获取当前用户
		BackUserModel user = (BackUserModel) ActionContext.getContext()
				.getSession().get(Keys.LOGINUSERKEY);

		// 获取请求参数
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();

		// 获取action
		String actionName = invocation.getProxy().getActionName();

		// 获取执行前的时间
		Long startTime = System.currentTimeMillis();
		// 执行方法
		String invoke = invocation.invoke();
		// 获取执行后的时间
		Long endTime = System.currentTimeMillis();

		if (!IContents.LOGINGOREACTIONLIST.contains(actionName)) {
			// 保存日志
			LogServiceImpl.save(new Log(user == null ? "未知用户" : user
					.getBuserLoginName(), (actionName != null && actionName
					.indexOf("_") >= 0) ? actionName.substring(0,
					actionName.indexOf("_")) : actionName, actionName,
					toIpAddr(request), String.valueOf(endTime - startTime),
					new Date()));
		}
		return invoke;
	}

	
	/**
	 * 返回用户的IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String toIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}


struts文件添加拦截器标签和相应action

<package name="xx-default" extends="json-default">
		<interceptors>
			<interceptor name="checkLogin" class="checkLoginInterceptor" /><!-- 登陆拦截器 -->
			<interceptor name="checkPrivilege" class="checkPrivilegeInterceptor" /><!-- 权限拦截器 -->
			<interceptor name="log" class="logInterceptor" /><!-- 日志拦截器 -->
			
			<interceptor-stack name="commonStack">
				<interceptor-ref name="defaultStack" /><!-- 默认包 -->
				<interceptor-ref name="checkLogin" />
				<interceptor-ref name="checkPrivilege" />
				<interceptor-ref name="log" />
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="commonStack" />
		<global-results><!-- 全局返回结果拦截 -->
			<result name="toLogin" type="redirect">/back/login_loginUI.action</result>
			<result name="noPrivilegeError">/noPrivilegeError.jsp</result>
			<result name="fileNotExists">/fileNotExists.jsp</result>
			<result name="error">/error.jsp</result>
			<result name="message">/message.jsp</result>
		</global-results>
	</package>
<pre name="code" class="html">       <!-- 登陆action -->
<package name="xxx" namespace="/back" extends="xxx-default">
<action name="login_*" class="loginAction" method="{1}">
            <result name="loginUI">/WEB-INF/back/login.jsp</result>
            <result name="logout">login_loginUI.action</result>
            <result name="loginOK" type="redirect">home_mainUI.action</result>
            <result name="success">/WEB-INF/back/test.jsp</result>
        </action>
</package>

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值