2013-06-18 38 views
7

Trước hết, tôi là một lập trình viên có kinh nghiệm, nhưng có rất ít sự quen thuộc với Java. Tôi có khoảng hai năm kinh nghiệm với nó, tám năm trước.Nullpointerexception java

Tôi nhận được một NullPointerException trong đoạn mã sau:

public static void handle(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException { 

    Response gfexResponse = null; 

    try { 

     ActionFactory actionFactory = ActionFactory.getInstance(); 
     String requestURL = request.getRequestURI(); 
     String actionId = actionFactory.getActionId(requestURL); 

     IAction action = actionFactory.createAction(actionId); 

     ActionEvent event = new ActionEvent(request, 0, actionId); 
     gfexResponse = action.execute(event); 

    } catch (Exception ex) {   
     gfexResponse = new Response(); 
     gfexResponse.setError(ex.getMessage()); 
     gfexResponse.setOutcome(IViewConstants.ERROR); 

    } finally { 

     if(request.getParameter("loginId") != null){ 
      request.setAttribute("loginId", request.getParameter("loginId")); 
     } 

     if(gfexResponse.getMessage()!= null){ 
      request.setAttribute("message", gfexResponse.getMessage()); 
     } 

     if(gfexResponse.getError()!= null){ 
      request.setAttribute("error", gfexResponse.getError()); 
     } 

     if (gfexResponse.getContentType() != null) { 
      response.setContentType(gfexResponse.getContentType()); 
      OutputStream outputStream = response.getOutputStream(); 
      outputStream.write(gfexResponse.getOutputData()); 
      outputStream.flush(); 
      outputStream.close(); 
     } 

     if(gfexResponse.getOutcome() != null){ 
      RequestDispatcher dispatcher = request.getRequestDispatcher(gfexResponse.getOutcome()); 
      dispatcher.forward(request, response); 
     } 
    }  
} 

Đây là StackTrace:

[6/18/13 17:10:04:518 GMT] 00000023 ServletWrappe E SRVE0068E: Uncaught exception thrown in one of the service methods of the servlet: GfexServlet. Exception thrown : java.lang.NullPointerException 
    at com.svl.gfex.handlers.RequestHandler.handle(RequestHandler.java:44) 
    at com.svl.gfex.servlets.GfexServlet.processRequest(GfexServlet.java:43) 
    at com.svl.gfex.servlets.GfexServlet.doPost(GfexServlet.java:39) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:763) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:856) 
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:966) 
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:907) 
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:118) 
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:87) 
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:701) 
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:646) 
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:475) 
    at com.ibm.ws.wswebcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:463) 
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3129) 
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:238) 
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:811) 
    at com.ibm.ws.wswebcontainer.WebContainer.handleRequest(WebContainer.java:1433) 
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:93) 
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:465) 
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:394) 
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:102) 
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:152) 
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:213) 
    at com.ibm.io.async.AbstractAsyncFuture.fireCompletionActions(AbstractAsyncFuture.java:195) 
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:136) 
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:194) 
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:741) 
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:863) 
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1510) 

Những điểm stacktrace để dòng này:

 if(gfexResponse.getMessage()!= null){ <-------- this line 
      request.setAttribute("message", gfexResponse.getMessage()); 
     } 

Mã này đã được duy trì bởi một nhà thầu nước ngoài, nhưng công ty đã sa thải tất cả các nhà thầu. Vì tội lỗi của tôi, tôi được giao công việc sửa chữa nó.

Nếu có ai có thể giúp tôi tìm ra lý do tại sao tôi nhận được lỗi này, tôi sẽ đánh giá cao điều đó.

+2

Thêm séc để xem liệu 'gfexResponse == null'. Các ngoại lệ con trỏ rỗng trong Java thường rất dễ gỡ lỗi, bởi vì bạn đang cố gắng gọi một phương thức trên một đối tượng null. –

Trả lời

11

lỗi đó chỉ ra rằng các đối tượng gfexResponse chính nó là null (tức action.execute(event) đang trở lại null trong đoạn code trên, và không có ngoại lệ được ném)

+1

+1 Rất hay về 'action.execute (event)'. Câu trả lời của bạn là câu trả lời duy nhất cho biết tại sao 'gfexResponse' là' null' .. –

1

Thực ra vấn đề nằm ở dòng gfexResponse = action.execute(event);

chỉ cơ hội trong dòng dưới đây để lấy NPE ở đây là gfexResponse là null

if(gfexResponse.getMessage()!= null){ <-------- this line 

đổi thành

if(gfexResponse!=null && gfexResponse.getMessage()!= null){ <-------- this line 
+0

Cảm ơn. Tôi đã thử nó, vẫn nhận được cùng một ngoại lệ tại cùng một điểm. – Kevin

+0

Các bạn đóng đinh nó, cảm ơn! Tôi đã nhầm lẫn về nó nổ tung tại cùng một điểm. – Kevin

1

Bạn có chắc chắn rằng gfexResponse là nhận được một giá trị thực tế từ action.execute(event); (trong try {})? Tôi đoán rằng action.execute(event); đang trả về giá trị rỗng.

+0

Tôi đoán tôi sẽ phải tìm ra cách sử dụng chế độ gỡ lỗi. – Kevin

4

phác thảo cơ bản của bạn là:

public static void handle(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException { 

    Response gfexResponse = null; 

    try { 
     //Try to get your gfexResponse 
    } catch (Exception ex) {   
     //Provide a default gfexResponse 
    } finally { 
     //Do some stuff with gfexResponse 
    }  
} 

Đây là thói quen xấu: bạn đang cố gắng sử dụng ngoại lệ xử lý để kiểm soát dòng chảy. Hơn nữa, bạn cho rằng phương pháp bạn sử dụng để có được gfexResponse sẽ ném một ngoại lệ nếu nó không thành công, rõ ràng là không. (Một số lỗi đơn giản/tracing sẽ tiết lộ này trực tiếp.)

Những gì bạn nên làm như sau:

public static void handle(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException { 

    Response gfexResponse = null; 

    try { 
     //Try to get your gfexResponse 
     //Make sure you got your response object and throw SomeAppropriateException if not 
     //Do some stuff with gfexResponse 
    } catch (SomeAppropriateException e) { 
     //properly handle this case 
    } catch (Exception ex) { 
     //properly handle the general case that something else failed (But you should try to be more specific) 
    } finally { 
     //remove any resources that might not be properly cleaned up if an exception is thrown. 
    }  
} 
+0

Bạn đúng về điều này là thực tế xấu, @Nathaniel Ford. Thật không may, đó là cách nó đã được mã hóa ban đầu, và không ai trong quản lý là sẽ không sao các chi phí để sửa chữa tất cả những điều đó. Đây chỉ là một trang web nhỏ, nhưng các nhà phát triển ban đầu xử lý kiểm soát dòng chảy trong cùng một cách ở khắp mọi nơi. – Kevin

1

Để giải quyết sự đau đớn ngay lập tức - gọi action.execute(event); của bạn có khả năng trở null. Tuy nhiên, điều này có thể được giảm nhẹ bằng nhiều cách:

  • kiểm tra Null, hoặc
  • Biến khối try-catch vào lời gọi phương thức riêng biệt của riêng mình, để trở về Response.

Từ đó, khối finally trở thành trọng tâm chính của phương pháp của bạn và bạn có thể kiểm tra null mà không phải lo lắng về finally.

Các vấn đề liên quan