1、转发(forward)
首先在简单修改下index.jsp以实现最基本的登录功能:接下来编写servlet接收该请求并执行简单的登录校验:
package com.zx.demo;
import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String loginName = req.getParameter("loginName"); String password = req.getParameter("password");
if (loginName == null || loginName.trim().equals("")) {
resp.getWriter().write("username must not null");
return;
}
if (password == null || password.trim().equals("")) {
resp.getWriter().write("password must not null");
return;
}
if (loginName.equals("admin") && password.equals("123456")) {
req.getRequestDispatcher("helloworld").forward(req, resp);
} else {
resp.getWriter().write("username or password wrong");
}
}
}
运行程序,输入正确账号密码,请求会被转发到
helloworld
servlet,转发不会改变请求url和参数,结果如下:
2、重定向(redirect)
延用上述jsp,修改servlet代码实现重定向,重定向url既可以是本容器,也可以是外部地址:
package com.zx.demo;
import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String loginName = req.getParameter("loginName"); String password = req.getParameter("password");
if (loginName == null || loginName.trim().equals("")) {
resp.getWriter().write("username must not null");
return;
}
if (password == null || password.trim().equals("")) {
resp.getWriter().write("password must not null");
return;
}
if (loginName.equals("admin") && password.equals("123456")) {
// req.getRequestDispatcher("helloworld").forward(req, resp);
resp.sendRedirect("helloworld");
// resp.sendRedirect("https://www.baidu.com");
} else {
resp.getWriter().write("username or password wrong");
}
}
}
输入正确账号密码后,servlet会向客户端发送302重定向code并附带url地址,客户端收到后会重新请求新的地址,重定向会改变url和请求参数,结果如下:
3、区别
转发和重定向有以下区别:转发 | 重定向 |
服务器行为 | 客户端行为 |
执行一次请求 | 执行两次请求 |
请求地址不变 | 请求地址改变 |
同一服务器 | 服务器不限 |