簡體   English   中英

將對象從jsp傳遞給Servlet時出現NullPointerException

[英]NullPointerException when passing object from jsp to Servlet

我試圖使用會話對象將我的DTO對象從jsp傳遞給servlet,但我得到空指針異常,最初我嘗試使用請求對象,這給出了同樣的錯誤,因此我轉移到了會話對象。

在第一個servlet中

request.getSession().setAttribute("datadto", dataDTO);
request.getRequestDispatcher("success.jsp").forward(request, response);

在jsp中

<% 
        DataDTO dataDTO = (DataDTO) request.getAttribute("datadto");
        HttpSession session420 = request.getSession();
        session420.setAttribute("object", dataDTO);
%>

在第二個servlet中

HttpSession session=request.getSession(false);
DataDTO dataDTO = (DataDTO) session.getAttribute("object");

MyService myService = ServiceFactory.getMyService();
myService.generateExcel(dataDTO); <--nullpointerexception

在谷歌搜索我發現我實施的以下鏈接 ,他說仍然我得到空指針異常

在jsp中

DataDTO dataDTO = myService.getData(keyword, nor);
String myObjectId = UUID.randomUUID().toString();
request.getSession().setAttribute(myObjectId, dataDTO);
request.setAttribute("myObjectId", myObjectId);

在第二個servlet中

String myObjectId = request.getParameter("myObjectId");
Object myObject = request.getSession().getAttribute(myObjectId);
DataDTO dataDTO = (DataDTO) myObject;
request.getSession().removeAttribute(myObjectId);

請幫我。

您的DTO已在第一個servlet中設置為session 因此,只需從JSP中刪除此代碼,因為它實際上是通過將DTO設置為null來從session刪除它。

<% 
    DataDTO dataDTO = (DataDTO) request.getAttribute("datadto");
    HttpSession session420 = request.getSession();
    session420.setAttribute("object", dataDTO);
%>

並使用原始密鑰名稱datadto檢索第二個servlet中的DTO

HttpSession session=request.getSession(false);
DataDTO dataDTO = (DataDTO) session.getAttribute("datadto");

在你說的JSP中。

 DataDTO dataDTO = (DataDTO) request.getAttribute("datadto");

相反它應該是request.getSession().getAttribute("datadto");

您的代碼在以下行中進行了修改

<% 
        DataDTO dataDTO = (DataDTO) request.getSession().getAttribute("datadto");
        HttpSession session420 = request.getSession();
        session420.setAttribute("object", dataDTO);
%>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM