1. 程式人生 > >jsp+servlet實現的驗證登陸

jsp+servlet實現的驗證登陸

可以將業務邏輯處理和檢視相分離,使用jsp介面表示檢視,使用servlet處理業務邏輯

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>
<%
String msg=(String)request.getAttribute("msg");
if(msg!=null){
out.print(msg);
}
%>
<form action="dologin" method="post">
username:<input type="text" name="username" /><br>
password:<input type="password" name="password" /><br>
<input type="submit" value="submit" />
</form>
</body>
</html>

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>
登陸成功 
<%
String username=request.getParameter("username");
out.print(username+"歡迎你");
 %>
</body>
</html>

fail.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>
登陸成功 
<%
String username=request.getParameter("username");
out.print(username+"歡迎你");
 %>
</body>
</html>

業務邏輯處理

com.zk.myservlet.dologin.java

public class dologin extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	//獲取表單資料
	String username=request.getParameter("username");
	String password=request.getParameter("password");
	//處理業務邏輯
	if("Tom".equals(username)&&"123".equals(password))
	{
	//分發轉向
	request.getSession().setAttribute("username", username);
	request.getRequestDispatcher("/success.jsp").forward(request, response);
	//response.sendRedirect(request.getContextPath()+"/success.jsp");//丟失 username引數值 ,一次請求
	}
	else
	{
	//分發轉向
	//request.getRequestDispatcher("/fail.jsp").forward(request,response);
	//response.sendRedirect(request.getContextPath()+"/fail.jsp");
          request.setAttribute("msg", "使用者名稱密碼不正確");
	  request.getRequestDispatcher("/login.jsp").forward(request,response);
	}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}

}