读取jsp中的会话属性

发布于 2024-10-31 09:55:38 字数 605 浏览 1 评论 0原文

我正在一个名为 cartList 的 servlet 中设置一个会话属性,它是一个像这样的字符串数组,

request.getSession().setAttribute("cartList", items);

其中 items 是 String 类型的对象数组。

在jsp中,我像这样调用上面的属性,

line123:String[] cartItems = (String[]) request.getSession().getAttribute("cartList");
line124:for (int i = 0; i < cartItems.length; i++) {
    line125:String[] cartItem = cartItems[i].split("\\|");

cartItems[i]永远不会为空,并且将包含像这样的字符串,[AAA-000|2]。

我在第 125 行收到一个异常,它是一个空指针异常。我不知道为什么我会收到此错误。我正在检查 servlet 中“items”的内容,它很好并且不为空。 我花了一整天的时间试图解决这个问题。我已经无计可施了!任何帮助表示赞赏!

i am setting a session attribute in a servlet called cartList which is an array of strings like this,

request.getSession().setAttribute("cartList", items);

where items is an array of objects of type String.

In a jsp, i'm calling the above attribute like this,

line123:String[] cartItems = (String[]) request.getSession().getAttribute("cartList");
line124:for (int i = 0; i < cartItems.length; i++) {
    line125:String[] cartItem = cartItems[i].split("\\|");

cartItems[i] will never be empty and will contain a string like this,[AAA-000|2].

I'm getting an exception at line 125 which is a nullpointerexception. I have no idea why i'm getting this error. I'm checking the contents of 'items' in the servlet, its fine and not empty.
I have spent a whole day trying to solve this. I'm at my wit's end! Any help is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗藏城府 2024-11-07 09:55:38

问题不在于您没有从会话中获取 cartItems。问题是 cartItems 的某些值包含 null。在调用 split() 之前,打印 cartItems[i] 的值以查看它携带的内容。

String[] cartItems = (String[]) request.getSession().getAttribute("cartList");
for (int i = 0; i < cartItems.length; i++) {
    out.println("cartItems["+i+"]: "+cartItems[i]);
    String[] cartItem = null;
    if(cartItems[i]!=null)
        cartItem = cartItems[i].split("\\|");
}

如果您看到某些值 null,请返回您的 servlet 并确保在将它们放入 cartList 之前为它们分配一些值。

The problem is not that you are not getting cartItems from session. The problem is that some values of cartItems contain null. Before invoking split(), print the value of cartItems[i] to see what it is carrying.

String[] cartItems = (String[]) request.getSession().getAttribute("cartList");
for (int i = 0; i < cartItems.length; i++) {
    out.println("cartItems["+i+"]: "+cartItems[i]);
    String[] cartItem = null;
    if(cartItems[i]!=null)
        cartItem = cartItems[i].split("\\|");
}

If you see null for some values, go back to your servlet and make sure you assign them some value before putting them into cartList.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文