因此,当我请求此servlet时,我正在尝试使用servlet将Java对象添加到用户的会话中.但是在servlet重定向到下一页并尝试检索对象之后,我得到了一个null对象.
以下是我将对象添加到HttpSession(在servlet中)的操作:
request.setAttribute("object", obj);
Run Code Online (Sandbox Code Playgroud)
然后我尝试通过(在JSP中)检索它:
Object obj = request.getAttribute("object");
Run Code Online (Sandbox Code Playgroud)
那么我如何让obj不为null?
更新:我也没试过这个:
HttpSession session = request.getSession();
session.setAttribute("object", obj);
Run Code Online (Sandbox Code Playgroud)
在JSP中有以下内容:
Object obj = request.getSession().getAttribute("object");
Run Code Online (Sandbox Code Playgroud)
两种方式仍然返回null.
我有两个类Server(使用main方法,启动服务器)和StartPageServletServlet.
代码中最重要的部分是:
public class Server {
public static void main(String[] args) throws Exception {
// some code
// I want to pass "anObject" to every Servlet.
Object anObject = new Object();
Server server = new Server(4000);
ServletContextHandler context =
new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(StartPageServlet.class, "/");
// more code
}
Run Code Online (Sandbox Code Playgroud)
和StartPageServlet:
public class StartPageServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Here I want to access "anObject"
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?