自定义拦截器实现用户未登录自动跳转到登录页面
程序员文章站
2022-05-28 23:48:34
...
1、编写拦截器类
需要继承struts2框架的MethodFilterInterceptor
(1)工具类
/**
* BOS项目的工具类
* @author newbie
*
*/
public class BOSUtils {
//获取session对象
public static HttpSession getSession(){
return ServletActionContext.getRequest().getSession();
}
//获取登录用户对象
public static User getLoginUser(){
return (User) getSession().getAttribute("loginUser");
}
}
/**
* 自定义的拦截器,实现用户未登录自动跳转到登录页面
* @author zhaoqx
*
*/
public class BOSLoginInterceptor extends MethodFilterInterceptor{
//拦截方法
protected String doIntercept(ActionInvocation invocation) throws Exception {
//从session中获取用户对象
User user = BOSUtils.getLoginUser();
if(user == null){
//没有登录,跳转到登录页面
return "login";
}
//放行
return invocation.invoke();
}
}
2、配置拦截器类
在struts.xml中配置
<interceptors>
<!-- 注册自定义拦截器 -->
<interceptor name="bosLoginInterceptor" class="com.itheima.bos.web.interceptor.BOSLoginInterceptor">
<!-- 指定哪些方法不需要拦截 -->
<param name="excludeMethods">login</param>
</interceptor>
<!-- 定义拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="bosLoginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"/>
<!-- 全局结果集定义 -->
<global-results>
<result name="login">/login.jsp</result>
</global-results>
上一篇: flask部署pytorch模型
下一篇: 远程登录jupyter notebook