日期:2014-05-18  浏览次数:20661 次

明明已经创建出一个session但是到别的servlet里面竟然获取不到
本帖最后由 m75100313 于 2014-04-03 22:37:51 编辑
简单购物车!
写了个小练习  下面这段servlet代码作为首页 首先访问  HttpSession session = request.getSession();  创建了一个session


package com.mth.shopping;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ListBook extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletExceptionIOException {
HttpSession session = request.getSession();
Map<String, Book> map = DB.getMap();
session.setAttribute("map", map);
String url=response.encodeRedirectURL("/Session/BookIndex.jsp");
System.out.println(url);
response.sendRedirect(url);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}


但是在另外一个servlet里面 HttpSession session = request.getSession(false);  竟然获取到空的session

package com.mth.shopping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BuyBookServlet extends HttpServlet {
// private List<Book> list = null;

@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String bookId = request.getParameter("id");
Book book = DB.getMap().get(bookId);
HttpSession session = request.getSession(false);
List<Book> list  = (List<Book>) session.getAttribute("list");
if (list == null) {
list = new ArrayList<Book>();
session.setAttribute("list", list);
}
list.add(book);

String url = response.encodeRedirectURL("/Session/ListCart");
response.sendRedirect(url);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}

}




请教各位大神 为什么 ?
严重: Servlet.service() for servlet BuyBookServlet threw exceptio