1.在登录的session中设置一个属性。
在登录的action中的execute方法中加入以下代码。
@SuppressWarnings("unchecked")
public String execute() throws Exception {
if ("lirongxing".equals(this.getUsername().trim()) && "lrx".equals(this.getPassword().trim())) {
Map map = ActionContext.getContext().getSession();
map.put("user","valid");
return "success";
} else {
this.addFieldError("username", "username or password error");
return "failer";
}
}
在这里我们假设用户名和密码分别为“lirongxing”和“lrx”,即可通过验证,当然在实际开发中是需要到数据库中去查询的。先取得map,在map中设置一个值,其实就是在session中设置了一个值。
2.写一个控制器类。
public class AuthInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map map = invocation.getInvocationContext().getSession();
if (map.get("user") == null) {
return Action.LOGIN;
} else {
return invocation.invoke();
}
}
}
注意:这里的map其实是struts2将session转化而来的,map里装的就是session里的东西。如果map中的user为空,说明没有进行登录。
3.配置struts.xml文件
<struts>
<package name="struts" extends="struts-default" >
<interceptors>
<interceptor name="authInterceptor" class="cn.com.showd.interceptor.AuthInterceptor"/>
<interceptor-stack name="myInterceptorStack">
<interceptor-ref name="authInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<!--<default-interceptor-ref name="myInterceptorStack"/>-->
<global-results>
<result name="login">/login/login.jsp</result>
</global-results>
<action name="login" class="cn.com.showd.action.LoginAction">
<result name="input">/login/login.jsp</result>
<result name="success">/register.jsp</result>
<result name="failer">/login/login.jsp</result>
</action>
<action name="register" class="cn.com.showd.action.RegisterAction" method="register">
<result name="success">/success.jsp</result>
<result name="input">/register.jsp</result>
<interceptor-ref name="myInterceptorStack"/>
</action>
</package>
</struts>
注意:这里不能配置<default-interceptor-ref name="myInterceptorStack"/>,因为这样配置会拦截所有的action,包括权限验证的Action,使得其永远不能登录,造成死循环。