1扁凛、建立login.jsp文件病附,將如下代碼寫入
<%
Cookie[] cookie_arr=request.getCookies();
%>
<form action="LoginServlet" method="post">
<pre>
用戶名:<input type="text" name="userName" value="<%
if(cookie_arr!=null){
for(Cookie cookie:cookie_arr){
if(cookie.getName().equals("login_uname")){
out.print(cookie.getValue());
}
}
}
%>">
密碼:<input type="password" name="userPassword" value="<%
//判斷是否有用戶信息存入cookie,如果有則讀取
if(cookie_arr!=null){
for(Cookie cookie:cookie_arr){
if(cookie.getName().equals("login_pwd")){
out.print(cookie.getValue());
}
}
}
%>">
<input type="checkbox" value="check" name="check">記住密碼
<input type="submit" name="sub" value="登錄" >
</pre>
</form>
2、建立服務(wù)器端文件LoginServlet.servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//修改編碼
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//1峰髓、獲得用戶信息
String userName=request.getParameter("userName");
String userPassword=request.getParameter("userPassword");
//2傻寂、判斷用戶登錄成功(未連接數(shù)據(jù)庫)
if(userName.equals("zhangsan")&& userPassword.equals("123")) {
//3、如果登錄成功 判斷是否要記住密碼
if(request.getParameter("check")!=null) {
//4携兵、如果客戶選擇了記住密碼則將用戶名和密碼存入cookie中
Cookie uname_cookie=new Cookie("login_uname", userName);
Cookie pwd_cookie=new Cookie("login_pwd", userPassword);
uname_cookie.setPath("/session_cookie");
pwd_cookie.setPath("/session_cookie");
uname_cookie.setMaxAge(15*24*3600);//以秒為單位
pwd_cookie.setMaxAge(15*24*3600);//15天
response.addCookie(uname_cookie);
response.addCookie(pwd_cookie);
}
response.sendRedirect("index.jsp");
}else {
response.getWriter().println("用戶名或密碼出錯");
}
3疾掰、如果使用數(shù)據(jù)庫查詢登錄信息,則使用如下代碼代替2
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
//1徐紧、獲得用戶信息
String userName=request.getParameter("userName");
String userPassword=request.getParameter("userPassword");
//2静檬、從數(shù)據(jù)庫獲取信息
String sql="select * from mymarket where userName=? && userPassword=?";
List<Object> paramList=new ArrayList<Object>();
paramList.add(userName);
paramList.add(userPassword);
DbHelper dbHelper=new DbHelper();
List<Map<String, Object>> list= dbHelper.executeQuery(sql, paramList);
//3炭懊、如果查詢到則將判斷cookie是否被選中
if(list!=null && list.size()>0) {
if(request.getParameter("check")!=null) {
//4、如果客戶選擇了記住密碼則將用戶名和密碼存入cookie中
Cookie uname_cookie=new Cookie("login_uname", userName);
Cookie pwd_cookie=new Cookie("login_pwd", userPassword);
uname_cookie.setPath("/session_cookie");
pwd_cookie.setPath("/session_cookie");
uname_cookie.setMaxAge(15*24*3600);
pwd_cookie.setMaxAge(15*24*3600);
response.addCookie(uname_cookie);
response.addCookie(pwd_cookie);
}//如果查詢到并將數(shù)據(jù)存入cookie拂檩,則重定向到index.jsp文件侮腹。
response.sendRedirect("index.jsp");
}else {
//如果沒有查詢到,則輸出用戶名或密碼出錯
response.getWriter().println("用戶名或密碼出錯");
}
}
4稻励、建立index.jsp文件父阻,模擬正文
<body>
主頁
</body>