GlassFishServer中的java.lang.NullPointerException

时间:2014-09-15 17:36:42

标签: java jdbc web

尝试使用共享连接(在初始化请求时创建连接)将记录添加到数据库中这里我是request.getAttribute()方法,用于从RequestListener.java检索属性并将其分配给连接类型引用。 / p>

这是我的代码:RequestListener.java

public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
    try {
        Connection connection=(Connection) sre.getServletContext().getAttribute("conn");
        connection.close();
    } catch (SQLException ex) {
        Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@Override
public void requestInitialized(ServletRequestEvent sre) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
           Connection connection= DriverManager.getConnection("jdbc:mysql://localhost/school?user=root&password=mysql"); 
            sre.getServletContext().setAttribute("conn",connection);
        } catch (Exception ex) {
        Logger.getLogger(RequestListener.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

 error:java.lang.NullPointerException
      at servlets.One.processRequest(One.java:45)
      at servlets.One.doGet(One.java:89)

//////   One.java(servlet)

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        String t1=request.getParameter("text1");
        out.println("A");
         Connection connection = (Connection) request.getAttribute("conn");
  //line45 **PreparedStatement ps = connection.prepareStatement("insert into tb1 values(?)");**
        ps.setString(1, t1);
        ps.executeUpdate();
        ps.close();
        request.setAttribute("conn", connection);
        request.getRequestDispatcher("B").forward(request, response);
            request.getRequestDispatcher("Two").forward(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(One.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

1 个答案:

答案 0 :(得分:0)

RequestListener.java

" sre.getServletContext()的setAttribute("康恩",连接)"必须更正为sre.getServletRequest()。setAttribute(" conn",connection)并避免将请求发送到两个servlet作为" request.getRequestDispatcher(" B")。forward (要求,回应);             request.getRequestDispatcher(" Two")。forward(request,response);"这会导致illegalStateException