繁体   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