【问题标题】:request.getSession() is nullrequest.getSession() 为空
【发布时间】:2012-02-08 22:53:12
【问题描述】:

如果有人帮助我解决以下问题,我将不胜感激。 我有一份碧玉报告,我填写了PrintingBean,一切都很好。当我点击打印预览按钮(打开小程序)时,我的应用程序在以下位置引发空指针异常:

if (bean.getPrintingDataList() != null && !bean.getPrintingDataList().isEmpty())

它似乎创建了新会话(但我在 gui 上看不到,一切都很好)。我的 manageBean 是一个 SessionScoped。这是我的整个方法:

private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    JasperPrint jasperPrint = null;

    try {
        PrintingBean bean = (PrintingBean) request.getSession().getAttribute("printMB");
        if (bean.getPrintingDataList() != null && !bean.getPrintingDataList().isEmpty()) {
            jasperPrint = printManager.print(bean.getPrintingDataList());
        }
    } catch (Exception ex) {
        Logger.getLogger(JasperPrintServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (jasperPrint != null) {
        response.setContentType("application/octet-stream");
        ServletOutputStream ouputStream = response.getOutputStream();

        ObjectOutputStream oos = new ObjectOutputStream(ouputStream);
        oos.writeObject(jasperPrint);
        oos.flush();
        oos.close();

        ouputStream.flush();
        ouputStream.close();
    }
}

【问题讨论】:

  • 那是不可能的。难道你实际上的意思是它在给定的行上返回null,并且NullPointerException实际上被扔到if块之后你访问bean?这会更有意义,并且可以得到回答。
  • 是的,你是对的,它在 if 块中抛出 NPE,因为 request.getSession() 没有属性(大小为 0)并且 .getAttribute("printMB") 根本不存在。你知道为什么以及如何处理这个问题吗?感谢您的宝贵时间

标签: jsf servlets jasper-reports


【解决方案1】:

会话由名为 JSESSIONID 的 cookie 维护。通常,此 cookie 由服务器在会话开始时设置,并且此 cookie 在整个会话期间的每个后续单个 HTTP 请求中从客户端返回到服务器。客户端(网络浏览器)透明地完成这一切。另见How do servlets work? Instantiation, sessions, shared variables and multithreading

在小程序中,您需要模拟与网络浏览器相同的操作。当 applet 连接到 servlet 并需要访问与为 applet 提供服务的页面相同的会话时,您应该确保将相同的会话 cookie 附加到 applet 发送的 HTTP 请求中。

最简单的方法是将会话 ID 作为参数传递给小程序:

<param name="JSESSIONID" value="#{session.id}">

(注意:我假设您使用 Facelets 作为视图技术,如果您使用 JSP,那么您应该改用 ${pageContext.session.id}

这样您就可以在小程序中相应地设置所需的会话cookie:

String jSessionID = getParameter("JSESSIONID");
URL servletURL = new URL(getCodeBase(), "yourServletURL");
URLConnection connection = servletURL.openConnection();
connection.setRequestProperty("Cookie", "JSESSIONID=" + jSessionID);
// ...

这应该会在 request.getSession() 上的 servlet 中返回相同的会话。

【讨论】:

  • 我将它添加到小程序中,我的会话终于有了属性.. 但我有另一个错误,所以我在 jasper 4.0.2 版本中运行我的报告,因此我更改了我的项目中的 pom 文件和它工作正常:) 谢谢你
【解决方案2】:

如果有请求,则必须有会话。我认为.getAttribute("printMB") 为空。您必须在将其转换为 PrintingBean 之前进行检查。

【讨论】:

  • null 转换为其他类型不会抛出 NPE。
猜你喜欢
  • 1970-01-01
  • 2015-09-07
  • 2012-12-07
  • 1970-01-01
  • 2011-09-07
  • 2015-06-23
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多