request.getRequestDispatcher("login.jsp").forward(request, response) 带数据返回页面
response.sendRedirect("login.jsp"); 不带数据返回页面
LoginServlet.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>接收客户端数据页面</title>
</head>
<body>
<%
//接收页面传递过来的数据
//JSP内置对象之请求对象1.request
//接收帐号信息
String strid = request.getParameter("userid");
//接收密码信息
String strpwd = request.getParameter("userpwd");
//JSP内置对象之打印对象2.out
// out.println("帐号是:"+strid);
// out.println("密码是:"+strpwd);
if(strid.equals("admin")&&strpwd.equals("123456")){
response.sendRedirect("index.jsp"); //地址重定向
}else{//登录失败
//response.sendRedirect("login.jsp"); //返回登录页面,不带数据过去
request.setAttribute("msg", "登录失败"); //带数据,在LoginServlet定义一个变量msg,值 为"登录失败"
request.getRequestDispatcher("login.jsp").forward(request, response);
}
%>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录界面</title>
</head>
<body>
<!-- 表单数据提交到哪个地方action(服务器页面)去
method="get/post",提交数据的方式
get(默认): 1.地址栏上可以看见提交的数据 2.一般提交的数据最大为1K
post: 1.地址栏上信息不可见 2.提交的数据可以超过1K
-->
<form action="LoginServlet.jsp" method="post">
请输入帐号:<input type="text" name="userid"/><br/>
请输入密码:<input type="password" name="userpwd"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
hello,欢迎来到index.jsp
</body>
</html>