大家好,又见面了,我是你们的朋友全栈君。
在web的工程如果想使用db4o,是不能直接使用的,如果想使用的就得做一些初始化的工作,以便在servlet中使用,具体可以看下面的两个网页有详细的介绍:
http://java.dzone.com/articles/db4o-java
可以如此使用:
Db4oServletContextListener.java
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.db4o.Db4oEmbedded;
import com.db4o.EmbeddedObjectContainer;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;
public class Db4oServletContextListener
implements ServletContextListener {
public static final String PREFIX_PATH = "E:/Pattern/PDFBox-v2/";
public static final String KEY_DB4O_FILE_NAME = "db4oFileName";
public static final String KEY_DB4O_SERVER = "db4oServer";
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("context oK");
ServletContext context = event.getServletContext();
String filePath = PREFIX_PATH + context.getInitParameter(KEY_DB4O_FILE_NAME);
EmbeddedConfiguration configEmbedded = Db4oEmbedded.newConfiguration();
EmbeddedObjectContainer rootContainer = Db4oEmbedded.openFile(configEmbedded,
filePath);
context.setAttribute(KEY_DB4O_SERVER, rootContainer);
/* ArrayList<exam> result = new ArrayList<exam>();
ObjectSet<exam> objectSet = rootContainer.query(exam.class);
while (objectSet.hasNext()) {
result.add((exam) objectSet.next());
}
exam[] exams = result.toArray(new exam[result.size()]);
System.out.println(exams.length);*/
context.log("db4o startup on " + filePath);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext context = event.getServletContext();
ObjectContainer rootContainer = (ObjectContainer) context.getAttribute(KEY_DB4O_SERVER);
context.removeAttribute(KEY_DB4O_SERVER);
close(rootContainer);
context.log("db4o shutdown");
}
private void close(ObjectContainer container) {
if(container != null) {
container.close();
}
}
}
自己的servlet代码:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.db4o.EmbeddedObjectContainer;
public class CategoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("OK");
EmbeddedObjectContainer container = (EmbeddedObjectContainer)
request.getServletContext().getAttribute("db4oServer");
}}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/162583.html原文链接:https://javaforall.cn