7

首先,我是一位经验丰富的程序员,但对 Java 知之甚少。八年前,我有大约两年的经验。

我在以下代码中收到 NullPointerException:

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);
        }
    }       
}

这是堆栈跟踪:

[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)

堆栈跟踪指向这一行:

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

该代码由一家离岸承包商维护,但该公司解雇了所有承包商。为了我的罪,我被赋予了修复它的工作。

如果有人可以帮助我弄清楚为什么会出现此错误,我将不胜感激。

4

5 回答 5

12

该错误表明gfexResponse对象本身是null(即在上面的代码action.execute(event)中返回null,并且没有抛出异常)

于 2013-06-18T18:46:04.857 回答
4

你的基本大纲是这样的:

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
    }       
}

这是一种不好的做法:您正在尝试使用异常处理来进行流控制。此外,您假设用于获取 gfexResponse 的方法在失败时抛出异常,显然它不会。(一些简单的调试/跟踪将直接揭示这一点。)

你应该做的是以下几点:

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.
    }       
}
于 2013-06-18T18:50:18.243 回答
1

其实问题出在一线gfexResponse = action.execute(event);

下面一行中唯一获得 NPE 的机会 gfexResponse 是 null

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

将其更改为

if(gfexResponse!=null && gfexResponse.getMessage()!= null){  <-------- this line
于 2013-06-18T18:46:37.370 回答
1

您确定从(在)gfexResponse中获得实际值吗?我猜那是返回null。action.execute(event);try {}action.execute(event);

于 2013-06-18T18:47:49.120 回答
1

为了解决眼前的痛苦 - 您的action.execute(event);电话可能会返回null。但是,可以通过多种方式缓解这种情况:

  • 空值检查,或
  • try-catch块转换为自己的单独方法调用,以返回Response.

从那里开始,该finally块成为您方法的主要焦点,您可以检查 null 而不必担心finally.

于 2013-06-18T19:02:57.147 回答