一、要实现自定义拦截器就要实现
1、com.opensympony.xwork2.interceptor.Interceptor接口:
public class Permission implements Interceptor{
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("进入拦截器!");
if (ActionContext.getContext().getSession().get("user") != null) {
return invocation.invoke();
} else {
ActionContext.getContext().put("message", "您还没有登录!");
}
return "message";
}
}
2、如果你想对某个Action里面的一些方法进行拦截可以在配置文件下做如下配置:
(注:该配置用了intereptorStack,将Struts2框架默认的拦截器和自定义的拦截器放在 栈里面)
<interceptors>
<!-- 注册自定义拦截器 -->
<interceptor name="permission" class="cn.winney.interceptor.Permission"/>
<interceptor-stack name="permissionStack">
<!-- 在拦截器栈中导入Struts2框架定义的栈 -->
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="permission"/>
</interceptor-stack>
</interceptors>
3、当访问该Action的任意放方法都会进入拦截器的配置:
<action name="hello_*" class="cn.itcast.action.LoginAction" method="{1}">
<result name="success">/WEB-INF/index.jsp</result>
<interceptor-ref name="permissionStack"/>
</action>
4、cn.itcast.action.LoginAction下的方法:
public String execute() {
this.message = "execute";
return "message";
}
public String login() throws IOException {
String filePath = ServletActionContext.getServletContext().getRealPath("/image");
System.out.println(filePath);
if (images != null) {
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
System.out.println(images.length);
for (int i = 0; i < images.length; i++) {
File toSave = new File(file, imagesFileName[i]);
FileUtils.copyFile(images[i], toSave);
}
}
this.message = "login";
return "message";
}