1. 程式人生 > >用jsp實現登入,登入成功則跳轉到登入成功頁面,失敗則跳轉到失敗頁面

用jsp實現登入,登入成功則跳轉到登入成功頁面,失敗則跳轉到失敗頁面

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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<div>
		<form action="dologin.jsp" method="post">
			<span>使用者名稱</span>
			<input type="text" name="username" />
			<span>密碼</span>
			<input type="text" name="password" />
			<input type="submit" value="登入"/>
		</form>
	
	</div>
</body>
</html>


dologin.jsp

<%@ 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+"/";
	String username="";
	String password="";
	request.setCharacterEncoding("utf-8");
	username=request.getParameter("username");
	password=request.getParameter("password");
	out.println(username);
	out.println(password);
	if("admin".equals(username) && "admin".equals(password)){
		session.setAttribute("loginUsername", username);
		session.setAttribute("loginUser",username);
		request.getRequestDispatcher("login_success.jsp").forward(request,response);
	}else{
		response.sendRedirect("login_failure.jsp");
	}	
%>

login_success.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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<div>
		歡迎<h3><%=session.getAttribute("loginUsername") %></h3>,登入成功!!!!
	</div>
</body>
</html>

login_failure.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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<div>
		登入失敗,請檢查使用者名稱或者密碼!!!
		<a href="login.jsp">login</a>
	</div>
</body>
</html>