首先自定义一个javaEE项目,更改项目运行名称,创建数据库连接,创建上下文 对象,正常运行,会创建两个上下文对象,一个原本项目名称的对象,一个更改后的项目名称对象,由于两个上下文对象,导致数据库无法更新。
解决方法:在上下文销毁的方法里做判断
if ("zk12".equals(attribute)) {
new ContextDao().updateCount(attribute);
}
示例代码:
第一步连接数据库
public Integer findCount() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zs12","root","123456");
String sql="SELECT count FROM count";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
rs.next();
return rs.getInt("count");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
public void updateCount(Integer arr) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zs12","root","123456");
conn.setAutoCommit(false);
PreparedStatement pst=conn.prepareStatement("update count SET count=?");
pst.setInt(1, arr);
System.out.println("arr = ");
System.out.println(arr);
int executeUpdate = pst.executeUpdate();
conn.commit();
System.out.println(executeUpdate);
} catch (Exception e) {
e.printStackTrace();
}
}
第二步
创建上下文监听
//创建方法
@Override
public void contextInitialized(ServletContextEvent sce) {
Integer count = new ContextDao().findCount();
ServletContext context = sce.getServletContext();
System.out.println("上下文创建" + context);
context.setAttribute("count", count);
String contextPath = context.getContextPath();
String servletContextName = context.getServletContextName();
String realPath = context.getRealPath("/");
System.out.println(contextPath);
System.out.println(servletContextName);
System.out.println(realPath);
}
//销毁方法 没做判断之前的写法:
@Override
public void contextDestroyed(ServletContextEvent sce){
ServletContext context = sce.getServletContext();
Integer attribute = (Integer) context.getAttribute("count");
System.out.println("上下文监听销毁 :" + attribute);
new ContextDao().updateCount(attribute);
}
没做判断之前的方法的运行效果,有两个不同的数据数据导致数据库无法更新,
//销毁方法 做判断的写法:
@Override
public void contextDestroyed(ServletContextEvent sce){
ServletContext context = sce.getServletContext();
Integer attribute = (Integer) context.getAttribute("count");
System.out.println("上下文监听销毁 :" + attribute);
//判断要运行的项目名称
if ("zk12".equals(attribute)) {
new ContextDao().updateCount(attribute);
}
}
做判断之后的运行结构
虽然还是两个上下文对象但是数据是一样的数据库可以正常运行
注意:如果没有更改运行项目的名称,使用创建项目的本身名称,那么只创建一个上下文对象没有以上问题。。