Struts2怎么配置登录拦截器
程序员文章站
2022-07-09 17:16:31
...
编写拦截器的两种方法:
1、继承AbstractInterceptor类,重写intercept方法()这里对拦截到的内容进行处理
/**
* 登录拦截器
*/
package com.abc.hotel.interceptor;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.abc.hotelsys.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author 别说难忘记
*
*/
public class LoginInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String path = ServletActionContext.getRequest().getRequestURI();
if(path.contains("getImageCode")||path.contains("checkLogin")||path.contains("toLogin")) {
return invocation.invoke();
}
ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
User user = (User) session.get("loginUser");
if(user!=null) {
return invocation.invoke();
}else {
System.out.println("未登录,进行拦截!"+path);
return "login_page";
}
}
}
2、实现Interceptor接口
/**
* 登录拦截器
*/
package com.abc.hotel.interceptor;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.abc.hotelsys.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* @author 别说难忘记
*
*/
public class LoginInterceptor implements Interceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String path = ServletActionContext.getRequest().getRequestURI();
if(path.contains("getImageCode")||path.contains("checkLogin")||path.contains("toLogin")) {
return invocation.invoke();
}
ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
User user = (User) session.get("loginUser");
if(user!=null) {
return invocation.invoke();
}else {
System.out.println("未登录,进行拦截!"+path);
return "login_page";
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
}
对Struts配置文件进行配置拦截器
struts.xml
<package name="hotelsysPkg" abstract="true" extends="struts-default" >
<interceptors >
<interceptor name="loginValidate" class="com.abc.hotel.interceptor.LoginInterceptor" />
<interceptor-stack name="mystack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="loginValidate"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="mystack" />
<global-results>
<result name="login_page">../WEB-INF/views/login.jsp</result>
</global-results>
</package>
运行截图如下: