我想从html页面向servlet发送请求,然后在java servlet中创建一个列表,然后我想将此列表返回到同一个html页面。
答案 0 :(得分:1)
问题是您永远不会初始化HttpSession s
变量:
@WebServlet(urlPatterns = {"/ShowPersonServlet"})
public class ShowPersonServlet extends HttpServlet {
HttpSession s; //null by default
//...
protected void processRequest(...) {
//...
//since never initialized, s is null
user.add((Person) s.getAttribute("person"));
}
@Override
protected void doGet(...) {
//...
//since never initialized, s is null
s.setAttribute("person",person);
}
}
Make-it-work 解决方案:设置s
s = request.getSession();
真实世界解决方案:
HttpSession s
的范围更改为每种方法的本地范围。另外,将其名称从s
更改为session
或更有用的内容。所以,你的代码看起来像这样:
@WebServlet(urlPatterns = {"/ShowPersonServlet"})
public class ShowPersonServlet extends HttpServlet {
/*
HttpSession s ; //moved as local variable
Person person = new Person(); //moved as local variable
private List<Person> user = new ArrayList<Person>(); //not sure where you want to store this
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession();
List<Person> personList = (List<Person>) session.getAttribute("personList");
if (personList == null) {
personList = new ArrayList<>();
session.setAttribute("personList", personList);
}
personList.add((Person) session.getAttribute("person"));
/*
try (PrintWriter out = response.getWriter()) {
//removed to shorten this answer
}
*/
request.getRequestDispatcher("/showPerson.jsp").forward(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Person person = new Person();
person.setKey(request.getParameter("txt_Key"));
person.setFirstName(request.getParameter("txt_firstName"));
person.setLastName(request.getParameter("txt_lastName"));
processRequest(request, response);
HttpSession session = request.getSession();
session.setAttribute("person",person);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
更多信息:
答案 1 :(得分:0)
您需要从request获取会话,您不能简单地期望通过HttpSession s ;
获取会话 - s
为null
。
// Something like this (in processRequest), although I
// would prefer a local session variable.
s = request.getSession();
答案 2 :(得分:0)
您需要提供异常的堆栈跟踪。但它看起来可能在两个地方:
答案 3 :(得分:0)
未定义var s
的值。它为null,因此使用s.getAttribute("str")
会抛出异常。
HttpSession s ;
s = request.getSession(false);