一证芭、要實現(xiàn)自定義攔截器就要實現(xiàn)
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";
}