一聚教程网:一个值得你收藏的教程网站

热门教程

java中使用cookie记录用户登录

时间:2022-11-14 23:25:42 编辑:袖梨 来源:一聚教程网

正在模仿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.*"%>




home page


<%

Cookie c[] = request.getCookies();
String path = "form.jsp";
String cuser=null;
String crand=null;
if(c!=null)
{
for(int i=0;i {
//out.println("Name:"+c[i].getName()+"-->"+c[i].getValue()+"
");
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);
}

%>




form.jsp

代码如下 复制代码

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>




Servlet and Form



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.

*
* 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+"
");
//user = MyFunc.setEncrypt(user);
//random = MyFunc.setEncrypt(random);
//out.println(user+"
");
//out.println(random+"
");
//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.

*
* 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 String[] 加密后字符串
* @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 if(j==sn.length())
j=0;
snNum[i]=str.charAt(i)^sn.charAt(j);
}

for(int k=0;k

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

/**
* 密码解密,虽然用不到
* @return String[] 加密后字符串
* @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 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 result+=snNum[k];
}
return result;
}




}

热门栏目