druid连接数据库

 一.封装连接数据

package Util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DruidUtil {
	static 	DruidDataSource dataSource;
	static{
		Properties pt = new Properties();
		try {
      
  pt.load(DruidUtil.class.getClassLoader().getResourceAsStream("alibaba.properties"));
			dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(pt);
			
		    }
			catch (Exception e) {
		
				e.printStackTrace();
			}
	}
     //连接数据库
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		
		} catch (SQLException e) {
		
			e.printStackTrace();
		}
	   return null;
		
		
	}
    //关闭数据库
	public static void close(){
		dataSource.close();
	}

}

二.验证数据库账号和密码:

package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.java12.javaweb.demo.util.PasswordUtil;

import Util.DruidUtil;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取用户和密码
		String user = request.getParameter("username");
		String pwd = request.getParameter("password");
		//加密
		String cp= PasswordUtil.createPassword(pwd);
		//调用工具类的连接
		Connection con = DruidUtil.getConnection();
		String sql="select * from users where name=? and password=?";
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, user);
			ps.setString(2, pwd);
			ResultSet res = ps.executeQuery();
	
			if(res.next()){
			
				request.setAttribute("username", user);
				request.getRequestDispatcher("/welcome").forward(request, response);
		
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	
		//response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

三.密码加密文件

package Util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class PasswordUtil {
	// 16进制下数字到字符的映射数组
	private static String[] hexDigits = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
			"d", "e", "f" };

	// 将inputstr加密
	public static String createPassword(String inputstr) {
		return encodeByMD5(inputstr);
	}

	// 验证密码是否正确
	public static boolean authenticatePassword(String pass, String inputstr) {
		if (pass.equals((encodeByMD5(inputstr)))) {
			return true;
		} else {
			return false;
		}
	}

	// 对字符串进行MD5编码
	private static String encodeByMD5(String originstr) {
		if (originstr != null) {
			try {
				// 创建具有指定算法名称的信息摘要
				MessageDigest md = MessageDigest.getInstance("MD5");
				// 使用指定的字节数组对摘要进行最后的更新,然后完成摘要计算
				byte[] results = md.digest(originstr.getBytes());
				// 将得到的字节数组编程字符窜返回
				String resultString = byteArrayToHexString(results);
				return resultString.toUpperCase();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

	// 转换字节数组为十六进制字符串
	private static String byteArrayToHexString(byte[] b) {
		StringBuffer resultsb = new StringBuffer();
		int i = 0;
		for (i = 0; i < b.length; i++) {
			resultsb.append(byteToHexString(b[i]));
		}
		return resultsb.toString();
	}

	// 将字节转化成十六进制的字符串
	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n / 16;
		return hexDigits[d1] + hexDigits[d2];
	}
	
	/**
	 * @param decript 要加密的字符串
	 * @return 加密的字符串
	 * SHA1加密
	 */
	public final static String SHA1(String decript) {
	    try {
	        MessageDigest digest = java.security.MessageDigest
	                .getInstance("SHA-1");
	        digest.update(decript.getBytes());
	        byte messageDigest[] = digest.digest();
	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        // 字节数组转换为 十六进制 数
	        for (int i = 0; i < messageDigest.length; i++) {
	            String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
	            if (shaHex.length() < 2) {
	                hexString.append(0);
	            }
	            hexString.append(shaHex);
	        }
	        return hexString.toString();

	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	    return "";
	}

	

	public static void main(String[] args) {
		String password = PasswordUtil.createPassword("123456");
		System.out.println("对123456用MD5加密后:" + password);
		String inputstr = "1234";
		System.out.println("1234与密码相同?" + PasswordUtil.authenticatePassword(password, inputstr));
		inputstr = "123456";
		System.out.println("123456与密码相同?" + PasswordUtil.authenticatePassword(password, inputstr));
	}
}

 四.alibaba.properties文件内容配置

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=false
username=root
password=root
filters=stat
initialSize=21
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200

五.index.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="get">
姓名:<input type="text" name=username>
密码:<input type="password" name="password">
<input type="submit" value="提交">

</form>
</body>
</html>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值