常见后台有效代码(第一期)

常见后台有效代码

一、不使用框架自带数据库连接池

导包

 常见后台有效代码(第一期)

配置文件:c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>

<default-config>

<property name="user">root</property>

<property name="password">1</property>

<property name="driverClass">com.mysql.jdbc.Driver</property>

<property name="jdbcUrl">jdbc:mysql://localhost:3306/shopdb?useUnicode=true&characterEncoding=UTF-8</property>

</default-config>

</c3p0-config>

工具类:DataSourceUtils.java(会自动读取配置文件,该过程隐藏)

package utils;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

private static DataSource dataSource = new ComboPooledDataSource();

private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

// 获取连接池

public static DataSource getDataSource() {

return dataSource;

}

public static Connection getConnection() throws SQLException{

return dataSource.getConnection();

}

// 获取连接对象

public static Connection getCurrentConnection() throws SQLException {

Connection con = tl.get();

if (con == null) {

con = dataSource.getConnection();

tl.set(con);

}

return con;

}

// 开启事务

public static void startTransaction() throws SQLException {

Connection con = getCurrentConnection();

if (con != null) {

con.setAutoCommit(false);

}

}

// 事务回滚

public static void rollback() throws SQLException {

Connection con = getCurrentConnection();

if (con != null) {

con.rollback();

}

}

// 提交并且 关闭资源及从ThreadLocall中释放

public static void commitAndRelease() throws SQLException {

Connection con = getCurrentConnection();

if (con != null) {

con.commit(); // 事务提交

con.close();// 关闭资源

tl.remove();// 从线程绑定中移除

}

}

 //释放结果集,语句和连接

    public static void free(ResultSet rs,Statement st,Connection con){

     try {

if(rs!=null){

rs.close();

}

} catch (Exception e) {

e.printStackTrace();

}finally{

if(con!=null){

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

    }

}

二、生成验证码

// 生成验证码

public void userCheckCode() throws Exception {

response.setContentType("image/jpeg");

int width = 60;

int height = 30;

// 设置浏览器不要缓存此图片

response.setHeader("Pragma", "No-caxhe");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

// 创建内存图像并获得其图形上下文

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics g = image.getGraphics();

// 产生随机验证码

// 定义验证码的字符表

String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

char[] rands = new char[4];

for (int i = 0; i < 4; i++) {

int rand = (int) (Math.random() * 36);

rands[i] = chars.charAt(rand);

}

// 产生图像

// 画背景

g.setColor(new Color(0x008080));

g.fillRect(0, 0, width, height);

// 随机产生120个干扰点

for (int i = 0; i < 120; i++) {

int x = (int) (Math.random() * width);

int y = (int) (Math.random() * height);

int red = (int) (Math.random() * 255);

int green = (int) (Math.random() * 255);

int blue = (int) (Math.random() * 255);

g.setColor(new Color(red, green, blue));

g.drawOval(x, y, 1, 0);// 干扰点

}

g.setColor(Color.BLACK);

g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));// 斜体|粗体

// 在不同的高度上输出验证码的不同字符

g.drawString("" + rands[0], 1, 19);

g.drawString("" + rands[1], 16, 18);

g.drawString("" + rands[2], 31, 20);

g.drawString("" + rands[3], 46, 21);

g.dispose();// 释放画笔资源

// 将图像输出到客户端

ServletOutputStream sos = response.getOutputStream();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ImageIO.write(image, "JPEG", baos);

byte[] buffer = baos.toByteArray();

response.setContentLength(buffer.length);

sos.write(buffer);

baos.close();

sos.close();

// 将验证码放在session

session.setAttribute("CheckCode", new String(rands));

}

// 注册页面刷新改变验证码

public String userRegisterChangeCheckCode() {

return "success";

}

前端使用时

 常见后台有效代码(第一期)

三、使用redis进行简单操作(使用时记得开启redis)

导包

 常见后台有效代码(第一期)

配置文件:redis.properties

redis.maxIdle=30

redis.minIdle=10

redis.maxTotal=100

redis.url=localhost

redis.port=6379

工具类:JedisPoolUtils

package utils;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtils {

private static JedisPool pool = null;

static{

//加载配置文件

InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties");

Properties pro = new Properties();

try {

pro.load(in);

} catch (IOException e) {

e.printStackTrace();

}

//获得池子对象

JedisPoolConfig poolConfig = new JedisPoolConfig();

poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));//最大闲置个数

poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));//最小闲置个数

poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));//最大连接数

pool = new JedisPool(poolConfig,pro.getProperty("redis.url") , Integer.parseInt(pro.get("redis.port").toString()));

}

 

//获得jedis资源的方法

public static Jedis getJedis(){

return pool.getResource();

}

}

具体使用:

//显示商品的类别的的功能

public void productCategoryList() throws Exception {

        ProductService service = new ProductService();

Jedis jedis = JedisPoolUtils.getJedis();//获得jedis对象 连接redis数据库

String categoryListJson = jedis.get("categoryListJson");

if(categoryListJson==null){//先从缓存中查询categoryListJson 如果有直接使用 没有在从数据库中查询存到缓存中

System.out.println("缓存没有数据 查询数据库");

//准备分类数据

List<Category> categoryList = service.findAllCategory();

Gson gson = new Gson();

categoryListJson = gson.toJson(categoryList);//利用GSON将集合转换成JSON格式

jedis.set("categoryListJson", categoryListJson);

}

response.setContentType("text/html;charset=UTF-8");

response.getWriter().write(categoryListJson);

}

 

四、使用第三方支付接口(易宝支付)

配置文件:merchantInfo.properties

p1_MerId=10001126856

keyValue=69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl

callback=http://localhost:8080/DayDayShop/callback

工具类:PaymentUtil

package utils;

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

 

public class PaymentUtil {

private static String encodingCharset = "UTF-8";

/**

 * 生成hmac方法

 *

 * @param p0_Cmd 业务类型

 * @param p1_MerId 商户编号

 * @param p2_Order 商户订单号

 * @param p3_Amt 支付金额

 * @param p4_Cur 交易币种

 * @param p5_Pid 商品名称

 * @param p6_Pcat 商品种类

 * @param p7_Pdesc 商品描述

 * @param p8_Url 商户接收支付成功数据的地址

 * @param p9_SAF 送货地址

 * @param pa_MP 商户扩展信息

 * @param pd_FrpId 银行编码

 * @param pr_NeedResponse 应答机制

 * @param keyValue 商户**

 * @return

 */

public static String buildHmac(String p0_Cmd,String p1_MerId,

String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat,

String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId,

String pr_NeedResponse,String keyValue) {

StringBuilder sValue = new StringBuilder();

// 业务类型

sValue.append(p0_Cmd);

// 商户编号

sValue.append(p1_MerId);

// 商户订单号

sValue.append(p2_Order);

// 支付金额

sValue.append(p3_Amt);

// 交易币种

sValue.append(p4_Cur);

// 商品名称

sValue.append(p5_Pid);

// 商品种类

sValue.append(p6_Pcat);

// 商品描述

sValue.append(p7_Pdesc);

// 商户接收支付成功数据的地址

sValue.append(p8_Url);

// 送货地址

sValue.append(p9_SAF);

// 商户扩展信息

sValue.append(pa_MP);

// 银行编码

sValue.append(pd_FrpId);

// 应答机制

sValue.append(pr_NeedResponse);

return PaymentUtil.hmacSign(sValue.toString(), keyValue);

}

/**

 * 返回校验hmac方法

 *

 * @param hmac 支付网关发来的加密验证码

 * @param p1_MerId 商户编号

 * @param r0_Cmd 业务类型

 * @param r1_Code 支付结果

 * @param r2_TrxId 易宝支付交易流水号

 * @param r3_Amt 支付金额

 * @param r4_Cur 交易币种

 * @param r5_Pid 商品名称

 * @param r6_Order 商户订单号

 * @param r7_Uid 易宝支付会员ID

 * @param r8_MP 商户扩展信息

 * @param r9_BType 交易结果返回类型

 * @param keyValue **

 * @return

 */

public static boolean verifyCallback(String hmac, String p1_MerId,

String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt,

String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid,

String r8_MP, String r9_BType, String keyValue) {

StringBuilder sValue = new StringBuilder();

// 商户编号

sValue.append(p1_MerId);

// 业务类型

sValue.append(r0_Cmd);

// 支付结果

sValue.append(r1_Code);

// 易宝支付交易流水号

sValue.append(r2_TrxId);

// 支付金额

sValue.append(r3_Amt);

// 交易币种

sValue.append(r4_Cur);

// 商品名称

sValue.append(r5_Pid);

// 商户订单号

sValue.append(r6_Order);

// 易宝支付会员ID

sValue.append(r7_Uid);

// 商户扩展信息

sValue.append(r8_MP);

// 交易结果返回类型

sValue.append(r9_BType);

String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue);

return sNewString.equals(hmac);

}

/**

 * @param aValue

 * @param aKey

 * @return

 */

public static String hmacSign(String aValue, String aKey) {

byte k_ipad[] = new byte[64];

byte k_opad[] = new byte[64];

byte keyb[];

byte value[];

try {

keyb = aKey.getBytes(encodingCharset);

value = aValue.getBytes(encodingCharset);

} catch (UnsupportedEncodingException e) {

keyb = aKey.getBytes();

value = aValue.getBytes();

}

 

Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);

Arrays.fill(k_opad, keyb.length, 64, (byte) 92);

for (int i = 0; i < keyb.length; i++) {

k_ipad[i] = (byte) (keyb[i] ^ 0x36);

k_opad[i] = (byte) (keyb[i] ^ 0x5c);

}

 

MessageDigest md = null;

try {

md = MessageDigest.getInstance("MD5");

} catch (NoSuchAlgorithmException e) {

 

return null;

}

md.update(k_ipad);

md.update(value);

byte dg[] = md.digest();

md.reset();

md.update(k_opad);

md.update(dg, 0, 16);

dg = md.digest();

return toHex(dg);

}

 

public static String toHex(byte input[]) {

if (input == null)

return null;

StringBuffer output = new StringBuffer(input.length * 2);

for (int i = 0; i < input.length; i++) {

int current = input[i] & 0xff;

if (current < 16)

output.append("0");

output.append(Integer.toString(current, 16));

}

 

return output.toString();

}

 

/**

 *

 * @param args

 * @param key

 * @return

 */

public static String getHmac(String[] args, String key) {

if (args == null || args.length == 0) {

return (null);

}

StringBuffer str = new StringBuffer();

for (int i = 0; i < args.length; i++) {

str.append(args[i]);

}

return (hmacSign(str.toString(), key));

}

 

/**

 * @param aValue

 * @return

 */

public static String digest(String aValue) {

aValue = aValue.trim();

byte value[];

try {

value = aValue.getBytes(encodingCharset);

} catch (UnsupportedEncodingException e) {

value = aValue.getBytes();

}

MessageDigest md = null;

try {

md = MessageDigest.getInstance("SHA");

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

return null;

}

return toHex(md.digest(value));

 

}

// public static void main(String[] args) {

// System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t"));

// }

}

 

具体实现:

// 确认订单---更新收获人信息+在线支付

  public void productConfirmOrder() throws Exception {

  // 1、更新收货人信息

  Map<String, String[]> properties = request.getParameterMap();// 通过name把请求参数封装到Map<String,String[]>

  Order order = new Order();

  BeanUtils.populate(order, properties);// 映射封装

  ProductService service = new ProductService();

  service.updateOrderAdrr(order);

  // 2、在线支付

  // 只接入第三方支付平台易宝支付

  // 获得 支付必须基本数据

  String orderid = request.getParameter("oid");

  String money = "0.01";// String money = order.getTotal()+"";为了测试支付0.01

  // 银行

  String pd_FrpId = request.getParameter("pd_FrpId");

  // 发给支付公司需要哪些数据

  String p0_Cmd = "Buy";

  String p1_MerId = ResourceBundle.getBundle("merchantInfo").getString("p1_MerId");

  String p2_Order = orderid;

  String p3_Amt = money;

  String p4_Cur = "CNY";

  String p5_Pid = "";

  String p6_Pcat = "";

  String p7_Pdesc = "";

  // 支付成功回调地址 ---- 第三方支付公司会访问、用户访问

  // 第三方支付可以访问网址

  String p8_Url = ResourceBundle.getBundle("merchantInfo").getString("callback");

  String p9_SAF = "";

  String pa_MP = "";

  String pr_NeedResponse = "1";

  // 加密hmac 需要**

  String keyValue = ResourceBundle.getBundle("merchantInfo").getString("keyValue");

  String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc,

  p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue);

 

  String url = "https://www.yeepay.com/app-merchant-proxy/node?pd_FrpId=" + pd_FrpId + "&p0_Cmd=" + p0_Cmd

  + "&p1_MerId=" + p1_MerId + "&p2_Order=" + p2_Order + "&p3_Amt=" + p3_Amt + "&p4_Cur=" + p4_Cur

  + "&p5_Pid=" + p5_Pid + "&p6_Pcat=" + p6_Pcat + "&p7_Pdesc=" + p7_Pdesc + "&p8_Url=" + p8_Url

  + "&p9_SAF=" + p9_SAF + "&pa_MP=" + pa_MP + "&pr_NeedResponse=" + pr_NeedResponse + "&hmac=" + hmac;

  response.sendRedirect(url);// 重定向到第三方支付平台

  }

前端代码:

 常见后台有效代码(第一期)

五、md5加密简单处理(统一输出32,不足前面补0)

工具类:MD5Utils

package utils;

import java.math.BigInteger;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class MD5Utils {

/* *

 * 使用md5的算法进行加密

 */

public static String md5(String plainText) {

byte[] secretBytes = null;

try {

secretBytes = MessageDigest.getInstance("md5").digest(

plainText.getBytes());

} catch (NoSuchAlgorithmException e) {

throw new RuntimeException("没有md5这个算法!");

}

String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字

// 如果生成数字未满32位,需要前面补0

for (int i = 0; i < 32 - md5code.length(); i++) {

md5code = "0" + md5code;

}

return md5code;

}

}

 

六、生成uuid

工具类:CommonsUtils

package utils;

import java.util.UUID;

public class CommonsUtils {

//生成uuid方法

public static String getUUID(){

return UUID.randomUUID().toString();

}

}

 

七、通过发送邮件**用户

 常见后台有效代码(第一期)

工具类:MailUtils

package utils;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

public static void sendMail(String email, String emailMsg)

throws AddressException, MessagingException {//email是收件人,emailMsg是**信息

//设置邮箱服务器

Properties props = new Properties();

props.setProperty("mail.transport.protocol", "SMTP");

props.setProperty("mail.host", "smtp.163.com");

props.setProperty("mail.smtp.auth", "true");// 指定验证为true

//设置发件人用户名和授权密码

Authenticator auth = new Authenticator() {

public PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication("15797768089", "pzm123");

}

};

Session session = Session.getInstance(props, auth);

Message message = new MimeMessage(session);

message.setFrom(new InternetAddress("[email protected]")); //发件人

message.setRecipient(RecipientType.TO, new InternetAddress(email)); //设置发送方式与收件人

message.setSubject("用户**");

message.setContent(emailMsg, "text/html;charset=utf-8");

Transport.send(message);//创建 Transport用于将邮件发送

}

}

具体使用:

 常见后台有效代码(第一期)