今天写了一个自定义拦截器.却遇到了以下问题
package dgut.ke.interceptors;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import dgut.ke.model.Catalog;
import dgut.ke.model.Publish;
import dgut.ke.model.Subject;
import dgut.ke.service.ICatalogService;
import dgut.ke.service.IPublishService;
import dgut.ke.service.ISubjectService;
public class AddBookInterceptor extends MethodFilterInterceptor {
/**
*
*/
private static final long serialVersionUID = 1135497226250835266L;
private ISubjectService subjectService ;
private ICatalogService catalogService ;
private IPublishService publishService ;
public ICatalogService getCatalogService() {
return catalogService;
}
public IPublishService getPublishService() {
return publishService;
}
public ISubjectService getSubjectService() {
return subjectService;
}
public void setCatalogService(ICatalogService catalogService) {
this.catalogService = catalogService;
}
public void setPublishService(IPublishService publishService) {
this.publishService = publishService;
}
public void setSubjectService(ISubjectService subjectService) {
this.subjectService = subjectService;
}
@Override
protected String doIntercept(ActionInvocation invoation) throws Exception {
// TODO 自动生成方法存根
System.out.println("-------- 拦截器开始执行 ----------");
List<Subject> subject_list = (ArrayList<Subject>)subjectService.findAll();
List<Catalog> catalog_list = (ArrayList<Catalog>)catalogService.findAll();
List<Publish> pubish_list = (ArrayList<Publish>)publishService.findAll();
//ActionContext act = ActionContext.getContext() ;
ActionContext act = invocation.getInvocationContext() ;
HttpServletRequest request = (HttpServletRequest) act.get(ServletActionContext.HTTP_REQUEST) ;
request.setAttribute("subject_list", subject_list) ;
request.setAttribute("catalog_list", catalog_list) ;
request.setAttribute("publish_list", pubish_list) ;
System.out.println("-------- 拦截器执行结束 ----------");
return Action.INPUT;
}
}
为了实现request.setAttribute(String str, Object obj) ;.最先是让上面的类实现ServletRequestAware 接口.
但是在运行的时候却出现了空指针异常。后来改成以上的代码就可以正常运行,但是还是
不太明白
曾经在一本书上看到一段话:构建interceptor最重要的原则:interceptor必须是无状态的,并且不能
够使用任何ActionInvocation提供范围以外的API
posted on 2007-10-06 21:54
Ke 阅读(2469)
评论(0) 编辑 收藏 所属分类:
exception 、
struts 2 、
问题区