页面跳转是开发一个web应用经常会发生的事情。
比如登录成功或是失败后,分别会跳转到不同的页面。
跳转的方式有两种,服务端跳转和客户端跳转
步骤1:首先准备两个页面 success.html fail.html
步骤2:服务端跳转
步骤3:客户端跳转
步骤4:服务端跳转与客户端跳转图示
步骤 1 : 首先准备两个页面 success.html fail.html
首先在web目录下准备两个页面 success.html,fail.html
分别用于显示登录成功 或者登录失败
如果登录成功了,就服务端跳转到success.html
如果登录失败了,就客户端跳转到fail.html
![首先准备两个页面 success.html fail.html]()
|
<div style="color:green">login success</div>
|
|
<div style="color:red">login fail</div>
|
步骤 2 : 服务端跳转
在Servlet中进行服务端跳转的方式:
|
request.getRequestDispatcher("success.html").forward(request, response);
|
服务端跳转可以看到浏览器的地址依然是/login 路径,并不会变成success.html
![服务端跳转]()
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
if ("admin".equals(name) && "123".equals(password)) {
request.getRequestDispatcher("success.html").forward(request, response);
}
}
}
|
步骤 3 : 客户端跳转
在Servlet中进行客户端跳转的方式:
|
response.sendRedirect("fail.html");
|
可以观察到,浏览器地址发生了变化
![客户端跳转]()
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
if ("admin".equals(name) && "123".equals(password)) {
request.getRequestDispatcher("success.html").forward(request, response);
}
else{
response.sendRedirect("fail.html");
}
}
}
|
步骤 4 : 服务端跳转与客户端跳转图示
![服务端跳转与客户端跳转图示]()
更多内容,点击了解: https://how2j.cn/k/servlet/servlet-jump/551.html