在我的上一篇文章中说到,将DB4O的DAO类放入到ServeltContext中去,然后我们在struts2的ACTION中要去拿到这个DAO必然要得到servletcontext;
方法:
在ACTION中实现implements ServletContextAware。
然后实现该类的方法:
public static ServletContext context;
public void setServletContext(ServletContext context) {
// TODO Auto-generated method stub
this.context = context;
}
这样就可以在ACTION中得到servletcontext了。为什么在这我要用静态的属性来存放呢?
因为在我的该ACTION中,我用到了拦截器,拦截器的代码如下:
package common.interceptor;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import com.login.LoginAction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import common.util.db4o.LogMessageDao;
public class LogInterceptor extends AbstractInterceptor {
private Logger logger = Logger.getLogger(this.getClass().getName());
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
//logger.info("拦截器-"+this.name+":开始记录日志");
String LogFileName="";
LoginAction action = (LoginAction)invocation.getAction();
//通过拦截器得到了LoginAction的引用。然后通过action.context就可以得到servletcontext了,然后从context取出DAO的实例
String result = invocation.invoke();
HttpServletRequest request = action.getRequest();
// **************日期******************************
java.util.Date date = new java.util.Date();
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate = df.format(date); //当天日期
/***获得远程IP***/
String remoteIP=request.getRemoteAddr();
String logstr = action.getPerID()+";登陆IP:"+remoteIP+"登陆时间:"+strDate;
LogFileName=strDate.substring(0,10);
logger.info(logstr);
//改段代码可以将登陆日志记录到文件中Log.writeFile(logstr, request.getRealPath(".") + "\\log\\"+LogFileName+".log",true);
//DB4oUtil db = new DB4oUtil();
LogMessageDao db = (LogMessageDao)action.context.getAttribute("LogDao");
db.save(request.getRealPath(".")+"\\log\\log.db", action.getPerID(),remoteIP);
return result;
}
}