JAVA Web 编程技术 实验四

login.html

<html>
  <head> <title>用户登录</title>
    <meta http-equiv="content-type" content="text/html; charset=GBK">
  </head>
 <body>
  <form method="POST"  action="loginValidate.jsp">
      用户:    <input type=text name=username><br>
      密码:<input type=password name=password><br><br>
       <input type="radio" name="age" value="7"> 将登录信息保存一周 <br>
       <input type="radio" name="age" value="30"> 将登录信息保存一个月<br>
       <input type="radio" name="age" value="0" checked="checked"> 不保存<br>
      <input type=submit value="提交">&nbsp;&nbsp;
             <input type=reset vlaue="重置">
  </form>   
  </body>
</html>

loginValidate.jsp

<%@ page  pageEncoding="GBK"%>
<%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String age  = request.getParameter("age");
    int cookieAge = (age==null)? 0: Integer.parseInt(age);
    //用户信息验证,这里是简单设定两合法用户,实际中访问有数据库进行验证
    if("web".equals(username) && "123456".equals(password) ||
        "jsp".equals(username) && "888888".equals(password) ) 
     {
        Cookie mycookie =  new Cookie("cookie_username",null);//新建
        //把登录信息存入Cookie
        mycookie.setValue(username);
        if(cookieAge!=0) mycookie.setMaxAge(cookieAge*24*3600); //设置最大的存活期,单位为秒
        response.addCookie(mycookie);
        response.sendRedirect("work.jsp");
    }
    else{
        out.print("<p><b>你没有登录或用户名密码错误!请重新登录!</b><p>");
        pageContext.include("login.html");
        }
 %>

work.jsp

<%@ page  pageEncoding="GBK" %>
<% 
    String username = null;
    Cookie c[] = request.getCookies();//读出所有Cookies
    if(c!=null){ //存在Cookie
        for(int i=0; i < c.length; i++) //遍历所有Cookies,查找需要的Cookie
        {
            String cookieName = c[i].getName(); 
            if(cookieName.equals("cookie_username")) //找到
                username = c[i].getValue(); //取出值
        }
    }
    else{//不存在Cookie,重定向
       response.sendRedirect("login.html");
    }
    
    if(null==username || 0 == username.length()) //遍历结束后没找到所需的Cookie
        response.sendRedirect("login.html");  //转重新登录
    else{ //找到所需Cookie
        out.print("<p><b>欢迎"+ username + "</b></p>");
        out.print("这里是工作页面的内容......");
    }
%>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值