1. 程式人生 > >JavaWeb-登入的驗證與自動跳轉到登入頁面

JavaWeb-登入的驗證與自動跳轉到登入頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%-- 本行程式碼可以防止亂碼出現 --%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>Task04-login</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

</head>

<body>

	<!--傳值到"login_action.jsp"  方式是post隱式傳遞。-->
	<form action="/FridayJob/Task/Task04/login_action.jsp" method="post">
		<!-- 通過正則表示式決定輸入的字元 -->
		使用者名稱:<input pattern="[a-zA-Z0-9]{6,12}" name="username">(只能由字母數字組成,長度在6-12位之間)<br />
		密碼:<input pattern="[a-zA-Z0-9]{6,12}" type="password" name="password">(只能由字母數字組成,長度在6-15位之間)<br /> <input
			type="submit" value="登入"><br>


	</form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>Task04-login_action</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">


</head>

<body>
	<%
		String username = request.getParameter("username");
		String password = request.getParameter("password");
	%>
	<!-- 判斷字串是否為空,為空就轉到最初的登入頁面 -->
	<%
		if (username.equals("") && password.equals("")) {
			response.setHeader("refresh",
					"3;URL=/FridayJob/Task/Task04/login.jsp");//這裡的3,是你要確定的時間秒 URL是要跳轉的地址
	%><font color="red" size="5"> 您的登入資訊為空<br> 三秒後將跳轉到登入頁面 <br>
		如果沒有跳轉,請點選 <a href="/FridayJob/Task/Task04/login.jsp">這裡</a>!!! <br>
	</font>
	<%
		} else {
			out.print("使用者名稱:" + username);
	%><br>
	<%
		out.print("密碼:" + password);
	%><br>
	<%
		if (username != null) {
				if (username.equals("sweety") && password.equals("123456")) {
					out.print("welcome!!!");
				} else {
					response.setHeader("refresh",
							"3;URL=/FridayJob/Task/Task04/login.jsp");
	%><font color="red" size="5"> 您的登入資訊有誤<br> 三秒後將跳轉到登入頁面 <br>
		如果沒有跳轉,請點選 <a href="/FridayJob/Task/Task04/login.jsp">這裡</a>!!! <br>
	</font>
	<%
		}
			}
		}
	%>


</body>
</html>

輸入內容為空的話,會自動跳轉的

錯誤的話,也會自動跳轉到登入頁面

成功