【问题标题】:Forwarding a request from one servlet to another using Request dispatcher使用请求分派器将请求从一个 servlet 转发到另一个
【发布时间】:2017-02-04 17:14:53
【问题描述】:

我试图在一个 servlet 中创建一个 cookie,将其添加到 response() 并使用 DisaptcherServlet 将其转发到另一个 servlet,并尝试使用 request.getCookies() 检索 cookie。但这总是无效。

//Servlet one 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = request.getParameter("username");
String password = request.getParameter("password");

Cookie cookie = new Cookie("name", "value");
cookie.setMaxAge(30);
response.addCookie(cookie);

if(userName.equals("username") && password.equals("*****")){

RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Welcome");
requestDispatcher.forward(request, response);
}
else{
System.out.println("invalid credentials");
}
}

//welcome servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie []  cookie = request.getCookies();

if(cookie != null){
System.out.println("sucess");
}
else{
System.out.println("cookieis null");
}
}

【问题讨论】:

    标签: java servlets cookies requestdispatcher sessiontracking


    【解决方案1】:

    当你转发一个请求时,你基本上是在说“不,我不想处理这个请求,而是把它交给这个其他资源”。这意味着转发的请求使用与原始请求相同的请求和响应。

    在您的示例 servlet 中,在响应上设置了一个 cookie,欢迎 servlet 无法访问,因为响应对象上没有获取 cookie 的 API。如果您想要这种模式 servlet,则应在请求对象上设置一个参数,然后欢迎 servlet 可以从请求对象中获取该参数。

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 1970-01-01
      • 2012-04-24
      • 2014-06-07
      • 2012-06-07
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多