java中使用cookie记录用户登录

正在模仿mvc模式,不过没有写代理类与工厂类,这个只是实现功能,连数据库都没有关。

过程:打开index.jsp,若是cookie为null则跳到form.jsp 若不为null则查找固定的cookie_user的值,再找数据库取出对应的随机码。然后加密得出的字符串与cookie_random的值相比若都相等则输入welcom.表示登录成功。

index.jsp //在if 那里用response.send 这个跳转,一定要在下面加return 不然出错。

 代码如下 复制代码

<%@ page contentType="text/html; charset=utf-8" language="java" import="wen.func.*" errorPage="" %>
<%@ page import="admin.dao.*"%>
<%@ page import="admin.dbc.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>home page</title>
</head>
<body>
<%

    Cookie c[] = request.getCookies();
    String path = "form.jsp";
    String cuser=null;
    String crand=null;
    if(c!=null)
    {
        for(int i=0;i<c.length;i++)
        {
            //out.println("Name:"+c[i].getName()+"-->"+c[i].getValue()+"<br>");
            if(c[i].getName().equals("cookie_user")) //cookie_user 固定名
            {
                cuser = c[i].getValue(); //cookie_user的值 就是保存的用户名
            }
            if(c[i].getName().equals("cookie_random"))
            {
                crand = c[i].getValue();
            }
           
        }
        /*if (!MyFunc.checkStr(cuser))//是null or ""
        {
            response.sendRedirect(path);
        }
        if (!MyFunc.checkStr(crand))
        {
            response.sendRedirect(path);
        }*/
        if(crand==null || "".equals(crand))
        {
            response.sendRedirect(path);
            return;
            //out.println("exxxxx");
        }
        if(cuser==null || "".equals(cuser))
        {
            response.sendRedirect(path);
            return;
        }

       

            ConnData conn=new ConnData();
            DoData doCheck = new DoData(conn.getConn());
            String randtemp = doCheck.GetRandom(cuser); //取随机码
            randtemp = MyFunc.MD5(randtemp);
            randtemp = MyFunc.MD5(randtemp+"login_random");
            if(randtemp.equals(crand)) //相等
            {
                out.println("Hello "+cuser+",Welcom My Web Server!");
            }else
            {
                response.sendRedirect(path);
                //out.println("cccc");
                return;
            }
               
       
    }else
    {
        //out.println("No cookies");
        response.sendRedirect(path);
    }
   
%>

</body>
</html>

 

form.jsp

 代码如下 复制代码

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Servlet and Form</title>
<link href="css/clogin.css" rel="stylesheet" type="text/css" />
</head>

<body>

<div class="login">
<table width="100%" height="114" border="0" cellpadding="0" cellspacing="0" class="table">
<form id="form1" name="form1" method="post" action="clogin">
  <tr>
    <td width="30%" height="33"><div align="right">用户名:</div></td>
    <td width="70%"><input type="text" name="user" id="user" /></td>
  </tr>
  <tr>
    <td height="23"><div align="right">密码:</div></td>
    <td><input type="text" name="pass" id="pass" /></td>
  </tr>
  <tr>
    <td height="25"><div align="right">登录期限:</div></td>
    <td><select name="age" id="age">
      <option value="60" selected="selected">一分</option>
      <option value="86400">一天</option>
      <option value="604800">一周</option>
      <option value="31536000">一年</option>
    </select>    </td>
  </tr>
  <tr>
    <td height="31" colspan="2">
      <div align="center">
        <input type="submit" name="button" id="button" value="提交" />
        &nbsp;
        <input type="reset" name="button2" id="button2" value="重置" />   
      </div></td>
    </tr>
        </form>
</table>
</div>
</body>
</html>

 

 

servlet 接受数据。这里没有关闭数据库操作。

 代码如下 复制代码

package admin.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
//import wen.func.*;
//import admin.dbc.*;
//import admin.dao.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import wen.func.MyFunc;
import admin.dao.DoData;
import admin.dbc.ConnData;

public class CheckLogin extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path ="form.jsp";
        String pathok = "index.jsp";
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");
        String age = request.getParameter("age");
        String random = null;
        boolean check=true;
        if (!MyFunc.checkStr(user))
        {
            check = false;
        }
        if (!MyFunc.checkStr(pass))
        {
            check = false;
        }

        if(!check)
        {
            response.sendRedirect(path); //client jmp
        }

        check =false;
        try {
            ConnData conn=new ConnData();
            DoData doCheck = new DoData(conn.getConn());
            try {
                check = doCheck.CheckUserPass(user, pass);
                random = doCheck.GetRandom(user); //取随机码
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
       

        if(check)
        {
            if(random!=null)
            {
                //PrintWriter out = response.getWriter();
                //out.println(random+"<br>");
                //user = MyFunc.setEncrypt(user);
                //random = MyFunc.setEncrypt(random);
                //out.println(user+"<br>");
                //out.println(random+"<br>");
                //user = MyFunc.MD5(user);
                //user =  MyFunc.MD5(user+"login_cookie");
                random = MyFunc.MD5(random);
                random = MyFunc.MD5(random+"login_random");
                Cookie cuser = new Cookie("cookie_user",user);
                Cookie cpass = new Cookie("cookie_random",random); //加密随机码
                int ag = Integer.parseInt(age);
                cuser.setMaxAge(ag);
                cpass.setMaxAge(ag);
                response.addCookie(cuser);
                response.addCookie(cpass);
            }
            response.sendRedirect(pathok);   
        }else{
            response.sendRedirect(path);
        }
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

 

 

操作数据库,看mvc模式,一般是先定义一个接口,然后再定义一个实现接口的类,,这里没有接口,直接操作数据库类。

 代码如下 复制代码

package admin.dao;
import java.sql.*;

import wen.func.MyFunc;
public class DoData {
    private Connection conn=null;
    public DoData(Connection conn)
    {
        this.conn = conn;
    }
   
    public boolean AddUser(String user,String pass,String rand) throws SQLException
    {
        PreparedStatement pstmt = null;
        boolean flag = false;
        String sql = "insert into users(userid,userpass,randomstr) values(?,?,?)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,user);
        pstmt.setString(2, pass);
        pstmt.setString(3, rand);
        if (pstmt.executeUpdate()>0)
        {
            flag = true;
        }
        pstmt.close();   
        return flag;
    }
   

    public boolean CheckUserPass(String user,String pass) throws SQLException
    {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        boolean flag = false;
        String sql = "select userpass,randomstr from users where userid=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,user);
        rs = pstmt.executeQuery();
        if(rs.next())
        {
            pass = MyFunc.MD5(pass);
            pass = pass+rs.getString(2);//randomstr
            pass = MyFunc.MD5(pass);
            if (pass.equals(rs.getString(1)))
            {
                flag = true;
            }
        }
        pstmt.close();   
        return flag;
    }
    public String GetRandom(String user) throws SQLException
    {
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String result = null;
        String sql = "select randomstr from users where userid=?";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,user);
        rs = pstmt.executeQuery();
        if(rs.next())
        {
            result = rs.getString(1);
        }
        return result;
    }
   
   
   
}

 

连接数据库类。,mvc里的是也单独一个类,关闭操作是放在代理类里。

 代码如下 复制代码

package admin.dbc;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnData {
    private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
    private static final String DBURL = "jdbc:mysql://localhost:3306/onepc";
    private static final String DBUSER = "root";
    private static final String DBPASS="root";
    private Connection conn = null;
   
    public ConnData() throws Exception
    {
        try
        {
            Class.forName(DBDRIVER);
            this.conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
        }catch (Exception e)
        {
            throw e;
        }
       
    }
    public Connection getConn()
    {
        return this.conn;
    }
   
    public void close() throws Exception
    {
        if(this.conn!=null)
        {
            try
            {
                this.conn.close();
            }catch(Exception e)
            {
                throw e;
            }
        }
    }
   
   
   
}

 

md5加密,网上搜来的代码。随机的是用查表方式,打出数组用 for int i=0; i<255;i++用char转就,用stringbuffer.append加就可以了。

 代码如下 复制代码

package wen.func;
//import java.sql.*;
import java.util.Random;
import java.security.MessageDigest;

public class MyFunc {
    private static char chartable[] = {'~','!','#','$','%','^','&','0','1','2','3','4','5','6','7','8','9','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','+','_','-','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    //private String strRandom;
    //private String strMd5;
   
    //public MyFunc()
    //{
    //    setRand();
    //}
   
   
    public static String MD5(String source)
    {    //byte[] source
        //String temp;
        try{
                MessageDigest md = MessageDigest.getInstance("MD5");    
                md.update( source.getBytes() );           
                StringBuffer buf=new StringBuffer();           
                for(byte b:md.digest())
                    buf.append(String.format("%02x", b&0xff) );            
                return buf.toString();
                //temp =     buf.toString()   
            }catch( Exception e ){
                e.printStackTrace();
                return null;
                //temp = null;
            }
        //this.strMd5 = temp;
     }
   
    public static String getRand()
    {
        StringBuffer str= new StringBuffer();
        Random rd = new Random();
        for(int i=0;i<8;i++)
        {
            str.append(chartable[rd.nextInt(chartable.length)]);
        }
        return str.toString();
    }

   
    public static boolean checkStr(String str)
    {
        boolean flag=true;
        if(str==null || "".equals(str))
        {
            flag = false;
        }
        return flag;
    }
   
   
    //public String getRand()
    //{
    //    return this.strRandom;
    //}
   
    /**
     * 使用异或进行简单的密码加密
     * @return <code>String[]</code> 加密后字符串
     * @author Administrator
     * @since 1.0 2005/11/28
     */

    public static String setEncrypt(String str){
        String sn="onepc"; //密钥
        int[] snNum=new int[str.length()];
        String result="";
        String temp="";

        for(int i=0,j=0;i<str.length();i++,j++){
            if(j==sn.length())
                j=0;
            snNum[i]=str.charAt(i)^sn.charAt(j);
        }

        for(int k=0;k<str.length();k++){

            if(snNum[k]<10){
                temp="00"+snNum[k];
            }else{
                if(snNum[k]<100){
                    temp="0"+snNum[k];
                }
            }
            result+=temp;
        }
        return result;
    }

    /**
     * 密码解密,虽然用不到
     * @return <code>String[]</code> 加密后字符串
     * @author Administrator
     * @since 1.0 2005/11/28
     */
    public static String getEncrypt(String str){
        String sn="onepc"; //密钥
        char[] snNum=new char[str.length()/3];
        String result="";

        for(int i=0,j=0;i<str.length()/3;i++,j++){
            if(j==sn.length())
                j=0;
            int n=Integer.parseInt(str.substring(i*3,i*3+3));
            snNum[i]=(char)((char)n^sn.charAt(j));
        }

        for(int k=0;k<str.length()/3;k++){
            result+=snNum[k];
        }
        return result;
    }

   
   
   
}

时间: 2024-07-28 16:09:15

java中使用cookie记录用户登录的相关文章

关于jsp中利用cookie记录上次登录时间和IP的问题

问题描述 关于jsp中利用cookie记录上次登录时间和IP的问题 <% String IP = request.getRemoteAddr(); Cookie[] cookies = request.getCookies(); Cookie serverCookie=null; for(int i=0;i<cookies.length;i++) if(IP.equals(cookies[i].getName())){ serverCookie=cookies[i];} if(serverCo

asp.net Cookie记录用户登录次数与防止同一账户重复登录

asp教程.net cookie记录用户登录次数与防止同一账户重复登录 放在登陆成功的地方:  string key = textbox1.text; //用户名文本框设为cache关键字  string uer = convert.tostring(cache[key]); //读取cache中用户相应的值 if (uer == null || uer == string.empty)//判断cache中是否有用户的信息,如果没有相关的值,说明用户未登陆 {   //定义cache过期时间  

java中使用Filter控制用户登录权限具体实例_java

学jsp这么长时间,做的项目也有七八个了,可所有的项目都是用户登录就直接跳转到其拥有权限的页面,或者显示可访问页面的链接.使用这种方式来幼稚地控制访问权限.从来没有想过如果我没有登录,直接输入地址也可以直接访问用户的页面的. 在jsp中权限的控制是通过Filter过滤器来实现的,所有的开发框架中都集成有Filter,如果不适用开发框架则有如下实现方法: LoginFilter.java 复制代码 代码如下: public class LoginFilter implements Filter {

详细学习Java Cookie技术(用户登录、浏览、访问权限)_java

本章文章详细讲解: 1.Cookie基本用法演示 2.演示Cookie的访问权限 3.演示Cookie的删除 4.利用Cookie显示用户上次登录的时间 5.利用Cookie技术显示用户最近浏览的若干个图片 6.测试火狐浏览器到底支持多少个Cookie和一个Cookie最大为多大 1.Cookie基本用法演示 index.jsp: <%@ page language="java" import="java.util.*" pageEncoding="

jsp中使用cookie显示上次登录时间

问题描述 jsp中使用cookie显示上次登录时间 显示结果: 当前的时间:Sat Dec 06 20:32:36 CST 2014 上次访问时间:FAC2291FFA5623F835BDCB6F1CAE51C6 代码: <% Cookie[] cookies= request.getCookies(); Cookie cookie_response = null; if(cookies!=null){ cookie_response=cookies[0]; } out.println("

php使用cookie保存用户登录的用户名实例_php技巧

本文实例讲述了php使用cookie保存用户登录的用户名的方法.分享给大家供大家参考.具体实现方法如下: 用户登录文件:login.php 复制代码 代码如下: <html> <head> <title>用户登录</title> </head> <body> <?php function getCookieUsername(){  if(empty($_COOKIE['username'])){   return "&

java web项目。每个用户登录都会开启几个线程,这样登录用户多了会不会导致线程太多

问题描述 java web项目.每个用户登录都会开启几个线程,这样登录用户多了会不会导致线程太多 使用的socket通讯,一个用户登录都开启一个socket并无限接收或发送报文信息,如果登录用户超过一定数量线程是否会达到服务器可开启的线程数?,如果会,该怎么优化?实在没有分了,求各位帮忙 解决方案 如果你用的是Tomcat的话,那么它默认的处理请求的方式就是开启线程去处理用户请求的,所以当用户数量达到Tomcat的最大并发数临界时,它就会拒绝再处理超额的请求了,而且这种方式是socket阻塞模式

基于 Jquery操作Cookie记录用户查询过信息

这是一个Cookie数据生成的列表, 每次单击查询会存储一个域名,并把最后一次查询的域名放在最上方.本例子最多存储10个,大家可以根据自己情况进行设置 下在咱们一起来看看是怎么实现的吧. 先写一个操作Cookie的JS文件如下 Code  代码如下 复制代码 function getid(id) {return (typeof id == 'string') ? document.getElementById(id) : id};function getOffsetTop(el, p) {var

c++-如何用C++代码设计记录用户登录的顺序以及次数

问题描述 如何用C++代码设计记录用户登录的顺序以及次数 如何用C++代码设计记录用户登录的顺序以及次数.用户登录后写下感言,退出登陆后再次登陆可以看见自己之前写的感言,并且可以按次序显示用户写下的感言.类似于贴吧回帖一样.