【发布时间】:2014-03-20 12:13:31
【问题描述】:
我有一个 JSP 页面,比如 xyz.jsp,我在其中设置了会话
request.getSession().setAttribute("path", loc);
在 a.java 中我成功使用了这个会话并将响应发送回 jsp 页面,
String fpath = request.getSession().getAttribute("path").toString();
但是,当我在 b.java 中使用相同的会话值时,我得到了空指针异常。
my.jsp->on button click->a.java->get session1->send response to my.jsp->my.jsp reloads->b.java 试图使用 session1->NullPointerExceptionError
我试过了,
-
使用不同的会话变量
session.setAttribute("session1", loc); session.setAttribute("session2", loc); 在 a.java 中创建一个新的会话变量并在 b.java 中访问它
还是同样的错误。
my.jsp 看起来像,
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/" + ip +"/" +timeStamp;
session.setAttribute("path", loc);
a.java 看起来像
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String fpath = session.getAttribute("path").toString();
if(!new File(fpath).exists())
{
File uploadedFile = new File(fpath, fileName);
item.write(uploadedFile);
two_file = "Right file " +fileName;
request.setAttribute("file2", two_file);
String f2 = "<span class='blue'>" +"Uploaded file " +fileName+ " at " +uploadedFile.getAbsolutePath()+ "<br>" + "</span>";
request.setAttribute("f2stat", f2);
}
RequestDispatcher rd = request.getRequestDispatcher("geco.jsp");
rd.forward(request, response);
b.java 的样子
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String b = session.getAttribute("path").toString();
File file = new File(b);
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("hi");
bw.close();
}
【问题讨论】:
-
你能再添加一些代码吗?
-
你想要哪一部分?
-
向我们展示您的 servlet 代码?
-
您的 String fpath 是否具有正确的值?我的意思是您是否正确设置了会话属性。为什么不 request.getSession().setAttribute("session1", loc);
-
我将分享我尝试过的代码。基本上它应该可以工作,你可以和我的比较一下,如果你在处理会话的方式上有一些变化,请告诉我