标签:
1.首先要有一个登录界面:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 7 8 <title>My JSP ‘1-1.jsp‘ starting page</title> 9 <% 10 String username = ""; 11 String password = ""; 12 // 13 Cookie[] cookies = request.getCookies(); 14 for(int i=0 ; i<cookies.length;i++){ 15 if("username".equals(cookies[i].getName())){ 16 username = cookies[i].getValue(); 17 } 18 else if("password".equals(cookies[i].getName())){ 19 password = cookies[i].getValue(); 20 } 21 } 22 23 %> 24 25 26 27 28 </head> 29 30 <body> 31 32 <form action="login_handler.jsp" method="post"> 33 username:<input type="text" name="name" value="<%=username%>"/><br> 34 password:<input type="password" name="pwd" value="<%=password%>"/><br> 35 <input type="checkbox" value="y" name="isLogin">自动登录<br> 36 <input type="submit" value="登录"/> 37 </form> 38 39 </body> 40 </html>
2.在有一个后台来处理表单提交内容
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 3 4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 5 <html> 6 <head> 7 8 <title>1-2.jsp</title> 9 10 11 </head> 12 13 <% 14 String name = request.getParameter("name"); 15 String pwd = request.getParameter("pwd"); 16 String flag = request.getParameter("isLogin"); 17 18 if(!"admin".equals(name)&&!"123".equals(pwd)){ 19 response.sendRedirect("error.jsp"); 20 } 21 else{ 22 if("y".equals(flag)){ 23 Cookie nameCookie =new Cookie("username",name); 24 nameCookie.setMaxAge(3600); 25 Cookie pwdCookie =new Cookie("password",pwd); 26 pwdCookie.setMaxAge(3600); 27 response.addCookie(nameCookie); 28 response.addCookie(pwdCookie); 29 } 30 response.sendRedirect("sucess.jsp"); 31 } 32 33 %> 34 <body> 35 36 </body> 37 </html>
如果选中自动登录的话,以后登录就可以进行自动登录了~
登录成功画面:
登录失败画面:
这是一个简单的输出Cookie值来检验cookie的存在~
1 <!--Cookie.jsp 这里可以任选哦~ --> 2 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 3 <%request.setCharacterEncoding("utf-8"); %> 4 5 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 6 <html> 7 <head> 8 9 <title>login-2.jsp</title> 10 11 12 <!-- 13 <link rel="stylesheet" type="text/css" href="styles.css"> 14 --> 15 16 </head> 17 18 <body> 19 <% 20 Cookie c[] = request.getCookies(); 21 for(int i=0;i<c.length;i++) 22 { 23 Cookie temp = c[i]; 24 %> 25 <%=temp.getName() %>:<%=temp.getValue() %><br> 26 <% 27 } 28 %> 29 30 31 32 <br> 33 </body> 34 </html>
获取到Cookie~
标签:
原文地址:http://www.cnblogs.com/DeepinSky/p/5674107.html