⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbexceptionservlet.java

📁 在 MyEclipse 中log4j的使用实例
💻 JAVA
字号:
package lvyi;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;

public class DBExceptionServlet extends HttpServlet
{
    static Logger logger=Logger.getRootLogger();
    static Logger bookLogger=Logger.getLogger("bookstoreLogger");
    
    public void init() throws ServletException
    {
        String prefix =  getServletContext().getRealPath("/");
        String file = getInitParameter("log4j-init-file");
        
        if(file != null)
        {
            PropertyConfigurator.configure(prefix+file);
         //   DOMConfigurator.configure(prefix+file);
        }

        try
        {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            
        }
        catch(ClassNotFoundException ce)
        {
            throw new UnavailableException("加载数据库驱动失败!");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
               throws ServletException,IOException
    {   
        Connection conn=null;
        Statement stmt=null;
        try
        {
            conn=DriverManager.getConnection(
            "jdbc:microsoft:sqlserver://localhost:1433;databasename=pubs","sa","");
            stmt=conn.createStatement();
            stmt.executeUpdate("delete from jobs where job_id=13");
        }
        catch(SQLException se)
        {
            NDC.push(req.getRemoteHost());
            logger.warn("数据库操作失败! "+se);
            logger.error("数据库操作失败! "+se);
            
            bookLogger.warn("数据库操作失败! "+se);
            bookLogger.error("数据库操作失败! "+se);
            
            NDC.pop();
            NDC.remove();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "数据库操作出现问题,请联系管理员。");
        }
        finally
        {
            if(stmt!=null)
            {
                try
                {
                    stmt.close();
                }
                catch(SQLException se)
                {
                    bookLogger.error("关闭Statement失败!",se);
                }
                stmt=null;
            }
            if(conn!=null)
            {
                try
                {
                    conn.close();
                }
                catch(SQLException se)
                {
                    bookLogger.error("关闭数据库连接失败!",se);
                }
                conn=null;
            }
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -