ServletContext存储对象后无法在重定向获取值
RedirectContext.java
@WebServlet("/RedirectContext")
public class RedirectContext extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,
IOException {
String name = request.getParameter("username");
ServletContext context = getServletContext();
context.setAttribute("name", name);
response.setStatus(302);
response.setHeader("location", "http://localhost:8080/web1/ToContextRedirect");
}
}
----------------------------------------------
ToContextRedirect.java
@WebServlet("/ToContextRedirect")
public class ToContextRedirect extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
String name = (String) context.getAttribute("name");
response.getWriter().write("welcome!" + name);
}
}
为什么通过ServletContext存储对象后,无法在重定向后的servlet中获取值,ServletContext表示当前应用程序的环境,重定向
后是两次不同的请求,但是运行的环境没有变化,怎么输出到浏览器的name为null????????
------解决方案--------------------
你的这个属性在设置的地方有值吗?调试过吗? 还是调试一下吧,看看在设置的地方有没有值