用struts2的interceptor做简单的访问权限验证。
struts配置文件方面嘛,两个文件:
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="auth-default" extends="struts-default" namespace="/"> <interceptors> <interceptor name ="authorizationInterceptor" class ="com.xxx.xxx.interceptor.AuthorizationInterceptor" /> <interceptor-stack name="auth"> <interceptor-ref name="defaultStack"/><!-- 不加这个好多东西用不了=。= --> <interceptor-ref name="authorizationInterceptor"/><!-- 重点~ --> </interceptor-stack> </interceptors> <!-- Interceptor验证失败的时候需要用到的跳转结果 --> <global-results> <result name="authInterceptor" type="redirectAction">authInterceptor</result> </global-results> <action name="authInterceptor" class="com.xxx.xxx.interceptor.AuthorizationInterceptor"> <result name="success">index.jsp</result> </action> </package> <include file="accountmgt_struts.xml"/> </struts>
为什么这个AuthorizationInterceptor是个Interceptor又是个Action捏? 因为我不知道怎么在Interceptor中设置错误消息。。。就借用了Action的setActionError();这种东西。。。当然,我是初学者,别信我。。
accountmgt_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="accountmgt" extends="auth-default" namespace="/"> <!-- 需要控制权限的类 --> <action name="doSomthing" class="com.xxx.xxx.accountmgt.action.SomeAction" method="addMethod"> <interceptor-ref name ="auth"/><!-- 我一个一个action加的,所以这么写 --> <result name="success">success.jsp</result> <result name="input">error.jsp</result> </action> <!-- 不需要控制权限的类 --> <action name="login" class="com.xxx.xxx.accountmgt.action.LoginAction" method="login"> <result name="success" type="redirectAction">successAction</result> </action> </package> </struts>
类方面:
AuthorizationInterceptor.java
package com.xxx.xxx.interceptor; import java.util.Map; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ValidationAwareSupport; import com.opensymphony.xwork2.interceptor.Interceptor; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; /** * @version 0.1 BETA * @author fengym <[email protected]> * Description 拦截器实现基本的权限验证 因为没有spring而却不让用SpringSecurityT_T */ public class AuthorizationInterceptor extends ActionSupport implements Interceptor { /** * 权限验证。 */ private static final Logger LOG = LoggerFactory.getLogger(AuthorizationInterceptor.class); private static final long serialVersionUID = 1L; private final ValidationAwareSupport validationAware = new ValidationAwareSupport(); @Override public String intercept(ActionInvocation invocation) throws Exception { Map<String, Object> session = invocation.getInvocationContext() .getSession(); long user_id = -1l; boolean authflag = false; if(session != null && session.get("userid") != null){ user_id=(long)session.get("userid"); if(user_id > 0){ authflag = true; } } if(authflag){ return invocation.invoke(); }else{ return "authInterceptor"; } } @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init() { // TODO Auto-generated method stub } public String execute() { addActionError("您还没有登录,请登陆系统");//白痴实现方法。。。 return SUCCESS; } }
核心好像就是这些。
自己看代码理解吧,反正我也不是很明白。
补充:
这个东西实际上少了对jsp的拦截。
所以最好追加一个filter来对jsp进行权限验证:
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://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4"> <display-name>Account Manager</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter> <filter-name>auth</filter-name> <filter-class>com.xxx.xxx.filter.AuthorizationFilter</filter-class> <init-param> <param-name>noAuthURLs</param-name> <param-value>index.jsp,login.jsp,Register.jsp</param-value> </init-param> <init-param> <param-name>redirectPath</param-name> <param-value>index.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>auth</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp </welcome-file> </welcome-file-list> </web-app>
AuthorizationFilter.java
package com.xxx.xxx.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; /** * @version 0.1 BETA * @author fengym <[email protected]> * Description JSP页面基本的权限验证 */ public class AuthorizationFilter implements Filter{ private static final Logger LOG = LoggerFactory.getLogger(AuthorizationFilter.class); private String redirectPath = ""; private String [] noAuthURLs ; @Override public void destroy() { // nothing } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response); String currentURL = request.getRequestURI(); HttpSession session = request.getSession(false); // if(isContains(currentURL)){ // chain.doFilter(request, response); // return; // } // //所验证页面属于非验证页面,或者session不为空,session中含有userid并且userid>0的情况下,通过验证。 if(isContains(currentURL) || ( session!=null && session.getAttribute("userid")!=null && (long)session.getAttribute("userid")>0)){ chain.doFilter(request, response); return; }else{ wrapper.sendRedirect(redirectPath); return; } } /** * 判断是否是需要拦截的页面。 * @param url * @return 判断结果 */ public boolean isContains(String url){ if(LOG.isDebugEnabled()){ LOG.debug("判断是否是需要拦截的页面!"); } boolean checkResult = false; for(String noAuthURL : noAuthURLs){ checkResult = url.indexOf(noAuthURL)>-1?true:false; if(checkResult){ break; } } return checkResult; } /** * filter初期化 * @param filterConfig */ @Override public void init(FilterConfig filterConfig) throws ServletException { if(LOG.isDebugEnabled()){ LOG.debug("初始化 Filter"); } noAuthURLs = filterConfig.getInitParameter("noAuthURLs").split(","); redirectPath = filterConfig.getInitParameter("redirectPath"); } }
搞定
下次直接copy了,哇哈哈哈。