Web项目框架设计-原生态Java

数据库操作封装-DBUtils

DBoptions.properties↓

DRIVER=com.mysql.jdbc.Driver
URL=jdbc:mysql://localhost:3306/comicexam?useUnicode&characterEncoding=utf-8
USERNAME=root
PASSWORD=

DBUtils.java↓

package com.soft.system.db;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;

public class DBUtils 
{
	private static String DRIVER = null;
	private static String URL = null;
	private static String USERNAME = null;
	private static String PASSWORD = null;
	private static final ThreadLocal<Connection> threadlocal = new ThreadLocal<>();  //线程副本
	
	/**
     * 静态块 加载JDBC驱动
     */
	static
	{
		try
		{
			ResourceBundle bundle = ResourceBundle.getBundle("DBoptions");  //加载 .properties文件
			DRIVER = bundle.getString("DRIVER");
			URL = bundle.getString("URL");
			USERNAME = bundle.getString("USERNAME");
			PASSWORD = bundle.getString("PASSWORD");
			Class.forName(DRIVER);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	private DBUtils(){};
	
	/********************************************************************************************
	 *                                    事务处理_Begin
	 ********************************************************************************************/
	/**
	 * 事务开启
	 * @throws Exception
	 */
	public static void beginTransaction()throws Exception
	{
		DBUtils.getConnection().setAutoCommit(false);
	}
	
	/**
	 * 事务执行
	 * @throws Exception
	 */
	public static void commit()throws Exception
	{
		DBUtils.getConnection().commit();
	}
	
	/**
	 * 事务回滚
	 */
	public static void rollback()
	{
		try
		{
			DBUtils.getConnection().rollback();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 事务结束
	 */
	public static void endTransaction() 
	{
		try
		{
			DBUtils.getConnection().setAutoCommit(true);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	/********************************************************************************************
	 *                                    事务处理_End                 
	 ********************************************************************************************/
	
	/********************************************************************************************
	 *                                    编译SQL_Begin
	 ********************************************************************************************/
	/**
	 * 编译SQL语句
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	public static final PreparedStatement PrepareStatement(String sql)throws Exception
	{
		return DBUtils.getConnection().prepareStatement(sql);
	}
	
	/**
	 * 创建数据库连接对象
	 * @return
	 * @throws Exception
	 */
	private static final Connection getConnection()throws Exception
	{
		Connection conn = threadlocal.get();
		if(conn==null || conn.isClosed())
		{
		    conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
			threadlocal.set(conn);
		}
		return conn;
	}
		
	/**
	 * 关闭数据库连接---Connection
	 */
	public static final void close()
	{
		try
		{
			Connection conn = threadlocal.get();
			if(conn!=null && !conn.isClosed())
			{
				threadlocal.remove();
				conn.close();
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭数据库连接---ResultSet
	 */
	public static final void close(ResultSet rs) 
	{
		try 
		{
			if(rs!=null)
			{
				rs.close();
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭数据库连接---PreparedStatement
	 */
	public static final void close(PreparedStatement pstm)
	{
		try 
		{
			if(pstm!=null)
			{
				pstm.close();
			}
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	/********************************************************************************************
	 *                                    编译SQL_End 
	 ********************************************************************************************/
	
	/**
	 * main函数测试数据库连接是否成功,以及线程副本创建是否成功
	 * @param args
	 */
	public static void main(String[] args) 
	{
        try 
        {
            for(int i=1;i<=10;i++)
            {
            	System.out.println(DBUtils.getConnection());
            }
		} 
        catch (Exception e) 
        {
			e.printStackTrace();
		}
	}
	
}

服务层封装-BaseService-JdbcService-PstmMetaData

BaseService.java↓

package com.soft.services.support;

import java.util.List;
import java.util.Map;

public interface BaseServices 
{
	/**
	 * 为子类Services,传递DTO
	 * @param dto
	 */
	void initDto(Map<String,Object> dto);
	
	/**
	 * 单一实例查询
	 * @return
	 * @throws Exception
	 */
    Map<String,String> findById()throws Exception;
	
	/**
	 * 数据分页查询
	 * @return
	 * @throws Exception
	 */
    List<Map<String,String>> queryForPage()throws Exception;
 
	/**
	 * 包含Services中所有更新类行为
	 * @param updateType
	 * @return
	 * @throws Exception
	 */
	boolean update(String updateType)throws Exception;
	
	/**
	 * 返回一行一列数据
	 * @return
	 * @throws Exception
	 */
    Object queryForObject()throws Exception;
	
}

JdbcService.java↓

package com.soft.web.support;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.soft.services.support.BaseServices;

public abstract class ControllerSupport implements BaseController
{
	private Map<String,Object> dto = null;
	private BaseServices services = null;
	private final Map<String, Object> attribute = new HashMap<>();//装载属性的容器
	
	/********************************************************************************************
	 *                                    处理Services_Begin
	 ********************************************************************************************/
	/**
	 * 向services传递DTO
	 */
	public final void initServices()
	{
		this.services.initDto(this.dto);
	}
	
	/**
	 * 子类调用BaseServices对象将其实例化
	 * @param services
	 */
	protected final void setServices(BaseServices services)
	{
		this.services = services;
	}
	/********************************************************************************************
	 *                                    处理Services_End
	 ********************************************************************************************/
	
	
	/********************************************************************************************
	 *                                    数据输入处理_Begin
	 ********************************************************************************************/
	/**
	 * 向Servlet注入DTO
	 */
	public final void setDto(Map<String,Object> dto)
	{
		this.dto = dto;
	}
	
	/**
	 * 子类获取DTO中属性的字符串类型
	 * @param key
	 * @return
	 */
	protected final String getVal(String key)
	{
		if(this.dto.containsKey(key)) 
		{
			return this.dto.get(key).toString();
		}
		else
		{
			return "";
		}
	}
	
	/**
	 * 子类获取DTO中的属性Object类型
	 * @param key
	 * @return
	 */
	protected final Object getVal(Object key)
	{
		return this.dto.get(key);
	}
	
	/**
	 * 打印DTO内容
	 */
	protected final void showDto()
	{
		System.out.println(this.dto);
	}
	/********************************************************************************************
	 *                                    数据输入处理_End
	 ********************************************************************************************/
	
	
	/********************************************************************************************
	 *                                    数据输出处理_Begin
	 ********************************************************************************************/
	/**
	 * 装入Servlet产生的数据
	 * @param key
	 * @param value
	 */
	protected final void addAttribute(String key,Object value)
	{
		this.attribute.put(key, value);
	}
	
	/**
	 * 添加msg
	 * @param msgText
	 */
	protected final void addMsg(String msgText)
	{
		this.attribute.put("msg", msgText);
	}
	
	/**
	 * 获取Servlet的送出的数据
	 */
	public final Map<String, Object> getAttribute()
	{
		return this.attribute;
	}
	/********************************************************************************************
	 *                                    数据输出处理_End
	 ********************************************************************************************/
	

	/********************************************************************************************
	 *                                    业务流程调度_Begin 
	 ********************************************************************************************/
	/**
	 * 分页查询
	 * @throws Exception
	 */
	protected final void savePageData()throws Exception
	{
		List<Map<String,String>> rows = this.services.queryForPage();
		if(rows.size()>0)
		{
			this.addAttribute("rows", rows);
		}
		else
		{
			this.addMsg("没有符合条件的数据");
		}
	}
	
	/**
	 * 删除后检索
	 * @throws Exception
	 */
	protected final void savePageData_del()throws Exception
	{
		List<Map<String,String>> rows = this.services.queryForPage();
		if(rows.size()>0)
		{
			this.addAttribute("rows", rows);
		}
	}
	
	/**
	 * 单一实例查询
	 * @throws Exception
	 */
	protected final void saveInstances()throws Exception
	{
        Map<String,String> ins = this.services.findById();
        if(ins.size()>0)
        {
        	this.addAttribute("ins", ins);
        }
        else
        {
        	this.addMsg("没有符合条件的数据");
        }
	}
	
	/**
	 * 单一行单一列数据存储
	 * @param dataName
	 * @throws Exception
	 */
	protected final void saveData(final String dataName)throws Exception
	{
		this.addAttribute(dataName, this.services.queryForObject());
	}
	
	/**
	 * 数据更新
	 * @param updateType
	 * @param msg
	 * @throws Exception
	 */
	protected final void update(String updateType,String fore_msg)throws Exception
	{
		String msg = this.services.update(updateType)?"成功":"失败";
	    this.addMsg(fore_msg+msg);
	}
	/********************************************************************************************
	 *                                    业务流程调度_End 
	 ********************************************************************************************/

}

PstmMetaData.java↓

package com.soft.services.support;

import java.sql.PreparedStatement;
import com.soft.system.db.DBUtils;

@SuppressWarnings("serial")
class PstmMetaData implements java.io.Serializable
{
	private PreparedStatement pstm = null;//语句对象
	private boolean isBatch = false;//语句对象的执行方式
	
	public PstmMetaData(PreparedStatement pstm,boolean isBatch)
	{
		this.pstm = pstm;
		this.isBatch = isBatch;
	}
	
	/**
	 * 默认语句对象,非批处理
	 * @param pstm
	 */
	public PstmMetaData(PreparedStatement pstm)
	{
		this.pstm = pstm;
	}
	
	/**
	 * 执行pstm
	 * @throws Exception
	 */
	public void executePstm()throws Exception
	{
		if(this.isBatch)
		{
			this.pstm.executeBatch();
		}
		else
		{
			this.pstm.executeUpdate();
		}
	}
	
	/**
	 * 关闭pstm
	 */
	public void close()
	{
		DBUtils.close(this.pstm);
	}
	
}

控制层封装-BaseController-ControllerSupport-BaseServlet

BaseController.java↓

package com.soft.web.support;

import java.util.Map;

public interface BaseController 
{
	/**
	 * 初始化Services
	 */
	void initServices();
	
	/**
	 * 业务控制器通过该方法实例化需要的Services对象
	 */
	void createServices();

    /**
     * 业务流程处理
     * @return --- 业务流程跳转的目标页面的,主文件名
     * @throws Exception
     */	
	String execute()throws Exception;
	
	/**
	 * 织入DTO
	 * @param dto
	 */	
	void setDto(Map<String,Object> dto);
	
	/**
	 * BaseServlet通过该方法,读取所有的属性
	 * @return
	 */	
	Map<String,Object> getAttribute();
	
	/**
	 * 初始化控制器,子类重写该方法,完成页面动态下拉列表
	 */
	void initController()throws Exception;
	
}

ControllerSupport.java↓

package com.soft.web.support;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.soft.services.support.BaseServices;

public abstract class ControllerSupport implements BaseController
{
	private Map<String,Object> dto = null;
	private BaseServices services = null;
	private final Map<String, Object> attribute = new HashMap<>();//装载属性的容器
	
	/********************************************************************************************
	 *                                    处理Services_Begin
	 ********************************************************************************************/
	/**
	 * 向services传递DTO
	 */
	public final void initServices()
	{
		this.services.initDto(this.dto);
	}
	
	/**
	 * 子类调用BaseServices对象将其实例化
	 * @param services
	 */
	protected final void setServices(BaseServices services)
	{
		this.services = services;
	}
	/********************************************************************************************
	 *                                    处理Services_End
	 ********************************************************************************************/
	
	
	/********************************************************************************************
	 *                                    数据输入处理_Begin
	 ********************************************************************************************/
	/**
	 * 向Servlet注入DTO
	 */
	public final void setDto(Map<String,Object> dto)
	{
		this.dto = dto;
	}
	
	/**
	 * 子类获取DTO中属性的字符串类型
	 * @param key
	 * @return
	 */
	protected final String getVal(String key)
	{
		if(this.dto.containsKey(key)) 
		{
			return this.dto.get(key).toString();
		}
		else
		{
			return "";
		}
	}
	
	/**
	 * 子类获取DTO中的属性Object类型
	 * @param key
	 * @return
	 */
	protected final Object getVal(Object key)
	{
		return this.dto.get(key);
	}
	
	/**
	 * 打印DTO内容
	 */
	protected final void showDto()
	{
		System.out.println(this.dto);
	}
	/********************************************************************************************
	 *                                    数据输入处理_End
	 ********************************************************************************************/
	
	
	/********************************************************************************************
	 *                                    数据输出处理_Begin
	 ********************************************************************************************/
	/**
	 * 装入Servlet产生的数据
	 * @param key
	 * @param value
	 */
	protected final void addAttribute(String key,Object value)
	{
		this.attribute.put(key, value);
	}
	
	/**
	 * 添加msg
	 * @param msgText
	 */
	protected final void addMsg(String msgText)
	{
		this.attribute.put("msg", msgText);
	}
	
	/**
	 * 获取Servlet的送出的数据
	 */
	public final Map<String, Object> getAttribute()
	{
		return this.attribute;
	}
	/********************************************************************************************
	 *                                    数据输出处理_End
	 ********************************************************************************************/
	

	/********************************************************************************************
	 *                                    业务流程调度_Begin 
	 ********************************************************************************************/
	/**
	 * 分页查询
	 * @throws Exception
	 */
	protected final void savePageData()throws Exception
	{
		List<Map<String,String>> rows = this.services.queryForPage();
		if(rows.size()>0)
		{
			this.addAttribute("rows", rows);
		}
		else
		{
			this.addMsg("没有符合条件的数据");
		}
	}
	
	/**
	 * 删除后检索
	 * @throws Exception
	 */
	protected final void savePageData_del()throws Exception
	{
		List<Map<String,String>> rows = this.services.queryForPage();
		if(rows.size()>0)
		{
			this.addAttribute("rows", rows);
		}
	}
	
	/**
	 * 单一实例查询
	 * @throws Exception
	 */
	protected final void saveInstances()throws Exception
	{
        Map<String,String> ins = this.services.findById();
        if(ins.size()>0)
        {
        	this.addAttribute("ins", ins);
        }
        else
        {
        	this.addMsg("没有符合条件的数据");
        }
	}
	
	/**
	 * 单一行单一列数据存储
	 * @param dataName
	 * @throws Exception
	 */
	protected final void saveData(final String dataName)throws Exception
	{
		this.addAttribute(dataName, this.services.queryForObject());
	}
	
	/**
	 * 数据更新
	 * @param updateType
	 * @param msg
	 * @throws Exception
	 */
	protected final void update(String updateType,String fore_msg)throws Exception
	{
		String msg = this.services.update(updateType)?"成功":"失败";
	    this.addMsg(fore_msg+msg);
	}
	/********************************************************************************************
	 *                                    业务流程调度_End 
	 ********************************************************************************************/

}

BaseServlet.java↓

package com.soft.web.support;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
@WebServlet("*.html")
public final class BaseServlet extends HttpServlet
{
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		String toPath = null; //跳转到页面路径
		try
		{
			String uri = request.getRequestURI();
	        String path = uri.substring(uri.lastIndexOf("/")+1).replace(".html", "");
	        String className = path.substring(0, 1).toUpperCase() + path.substring(1) + "Servlet";
	        String servletDir = "com.soft.web."+path.substring(0,1)+".impl.";
	         //System.out.println(servletDir); //Servlet路径输出
	        String all_path = servletDir + className; //跳转到具体servlet路径
	        BaseController controller = (BaseController)Class.forName(all_path).newInstance();
	        controller.setDto(this.creatDto(request)); //织入DTO
	        controller.initController(); //初始化Controller
	        controller.createServices(); //创建services
	        controller.initServices(); //初始化services
	        toPath = controller.execute(); //执行业务逻辑
	        Map<String,Object> attribute = controller.getAttribute(); //获取投射到页面的属性
	        this.parseAttribute(request, attribute); //属性进行切片
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("404!当访问路径,不存在映射类的时候,进行统一处理。。。。。。");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		request.getRequestDispatcher("/"+toPath+".jsp").forward(request, response);
	}
	
    /**
     * 属性解析切片
     * @param request
     * @param attributes
     */
	private void parseAttribute(HttpServletRequest request,Map<String,Object> attribute)
	{
		Set<Entry<String,Object>> entrySet = attribute.entrySet();
		for(Entry<String,Object> entry:entrySet)
		{
			request.setAttribute(entry.getKey(), entry.getValue());
		}
	}
	
	/**
	 * 数据传输对象(Data Transfer Object)的创建
	 * @param request
	 * @return
	 */
	private final Map<String,Object> creatDto(HttpServletRequest request)
	{
		Map<String,String[]> temp = request.getParameterMap();
		Set<Entry<String,String[]>> entrySet = temp.entrySet();
		int initsize = (int)(temp.size()/0.75)+1+16;
		Map<String,Object> dto = new HashMap<>(initsize);
		String[] value = null;
		for(Entry<String,String[]> entry:entrySet)
		{
			value = entry.getValue();
			if(value.length==1)
			{
  			     if(value[0]!=null && !value[0].equals(""))
  			     {
  				      dto.put(entry.getKey(), value[0]);
  			     } 
			}
			else
			{
				dto.put(entry.getKey(), value);
			}
		}
		return dto;
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException 
	{
		this.doGet(request, response);
	}
	
}

工具类-Tools

Tools.java↓

package com.soft.system.tools;

import java.security.MessageDigest;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import org.mywq.util.LabelValueBean;

import com.soft.system.db.DBUtils;

public class Tools 
{
	 private static String baseCode = null;
	 
     private Tools(){};
     
     static//读取基础码
     {
    	 ResourceBundle bundle = ResourceBundle.getBundle("basecode");
    	 baseCode = bundle.getString("BASECODE");
     }
     
    /********************************************************************************************
	 *                                    底层辅助方法_Begin
	 ********************************************************************************************/
    /**
     * 字符串数组转换字符串
     * @param value
     * @return
     */
    public static String joinArray(Object value)
     {
    	 if(value==null)
    	 {
    		 return "";
    	 }
    	 if(value instanceof java.lang.String[])
    	 {
    		 String[] array = (String[])value;
    		 int len = array.length;
    		 StringBuilder text = new StringBuilder(array[0]);
    		 for(int i=1;i<len;i++)
    		 {
    			 text.append(",").append(array[i]);
    		 }
    		 return text.toString();
    	 }
    	 else
    	 {
    		 return value.toString();
    	 }
     }
    
    /**
     * 生成主键流水号
     * @param firstName
     * @return
     * @throws Exception
     */
    public static final int getSequence(String firstName)throws Exception
    {
    	String sql1 = "select x.svalue from sequence x where x.sname=?";
    	StringBuilder sql2 = new StringBuilder()
    			.append("update sequence ")
			    .append("   set svalue=?")
			    .append(" where sname=?");
    	StringBuilder sql3 = new StringBuilder()
    			.append("insert into sequence(svalue,sname)")
			    .append("  values(?,?)");
    	return Tools.getNumber(firstName, sql1, sql2.toString(), sql3.toString());
    }
    
    /** 
     * 查序列表,获取当前流水号
	 * @param sname
	 * @return
	 * @throws Exception
	 */
	private static int getNumber(final String firstName,final String sql1,final String sql2,final String sql3)throws Exception
	{
   	PreparedStatement pstm1 = null;//查询序列当前值
   	PreparedStatement pstm2 = null;//更新序列当前值
   	ResultSet rs = null;
   	String sql = new String();
   	try
   	{
   		pstm1 = DBUtils.PrepareStatement(sql1);
   		pstm1.setObject(1, firstName);
   		rs = pstm1.executeQuery();
   		int current_val = 0;
   		if(rs.next())
   		{
   			current_val = rs.getInt(1);
   	        sql = sql2;
   		}
   		else
   		{
   			sql = sql3;
   		}
   		pstm2 = DBUtils.PrepareStatement(sql);
   		pstm2.setObject(1, ++current_val);
   		pstm2.setObject(2, firstName);		
   		pstm2.executeUpdate();
   	    return current_val;
   	}
   	finally
   	{
   		DBUtils.close(rs);
   		DBUtils.close(pstm1);
   		DBUtils.close(pstm2);
   	}
	}
    /********************************************************************************************
	 *                                    底层辅助方法_End
	 ********************************************************************************************/
    
	
	/********************************************************************************************
	 *                                    试题类型处理_Begin
	 ********************************************************************************************/
	/**
	 * 根据试题类型名为类型创建流水号,并加入syscode表用以翻译
	 * @param fvalue
	 * @return
	 * @throws Exception
	 */
	public static final Object getIbtypeCode(Object fvalue)throws Exception
	{
		PreparedStatement pstm1 = null;
		PreparedStatement pstm2 = null;
		ResultSet rs = null;
		try
		{
			String sql1 = "select fcode from syscode where fname = ? and fvalue = ?";
			String sql2 = "insert into syscode(fname,fcode,fvalue,pfcode) values(?,?,?,?)";
			pstm1 = DBUtils.PrepareStatement(sql1);
			pstm1.setObject(1, "IBTYPE");
			pstm1.setObject(2, fvalue);
			rs = pstm1.executeQuery();
			if(rs.next())
			{
				return rs.getString(1);
			}
			else
			{
				int fcode = Tools.getSequence("IBTYPE");
				pstm2 = DBUtils.PrepareStatement(sql2);
				pstm2.setObject(1, "IBTYPE");
				pstm2.setObject(2, fcode);
				pstm2.setObject(3, fvalue);
				pstm2.setObject(4, "0");
				pstm2.executeUpdate();
				return fcode;
			}
		}
		finally
		{
			DBUtils.close(rs);
			DBUtils.close(pstm1);
			DBUtils.close(pstm2);
		}
	}
	
	/********************************************************************************************
	 *                                    试题类型处理_End
	 ********************************************************************************************/
    
	
	/********************************************************************************************
	 *                                    生成用户登录名and生成流水号_Begin
	 ********************************************************************************************/ 
    /**
     * 基于年度原则,生成编号;  firstName(随机编号)+年份+尾码(序列号)
     * @param firstName
     * @return
     * @throws Exception
     */
    public static final String getLoginName()throws Exception
    {
    	String firstName = Tools.getfirstName();
    	int lastNumber = Tools.getLastNumber(firstName);
    	String formatnumber = Tools.formatLastNumber(lastNumber);
    	return firstName+Tools.getCurrentYear().substring(0, 4)+formatnumber;
    }
    
    /**
	 * 格式化尾码
	 * @param lastNumber
	 * @return
	 */
	private static String formatLastNumber(int lastNumber)
	{
		int len=String.valueOf(lastNumber).length();//计算尾码宽度
		return baseCode.substring(len)+lastNumber;//返回格式化的尾码
	}
	
	/**
	 * 获取尾码流水号
	 * @param firstName
	 * @return
	 * @throws Exception
	 */
	private static int getLastNumber(final String firstName)throws Exception
	{
		StringBuilder sql1 = new StringBuilder()
				.append("select svalue")
				.append("  from sequence")
				.append(" where date_format(syear,'%Y')=date_format(current_date,'%Y')")
				.append("   and sname=?")
				;
		StringBuilder sql2 = new StringBuilder()
				.append("update sequence")//修改序列当前值
			    .append("   set svalue=?")
			    .append(" where date_format(syear,'%Y')=date_format(current_date,'%Y')")
			    .append("   and sname=?")
			    ;		
		StringBuilder sql3 = new StringBuilder()
				.append("insert into sequence(svalue,sname,syear)")
			    .append("     values (?,?,current_date)")
			    ;
		return Tools.getNumber(firstName, sql1.toString(), sql2.toString(), sql3.toString());
	}

    /**
     * 获取当前年度
     * @return
     * @throws Exception
     */
    private static String getCurrentYear()
    {
    	Date date = new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//yyyy-MM-dd HH:mm:ss
    	String sdate = sdf.format(date);
    	//System.out.println(sdate);
    	return sdate;
    }
    
    /**
     * 得到firstName数字编码
     * @return
     */
    private static String getfirstName()
    {
    	char[] code = {'1','1','6','5','7','4','8','3','9','2'};
    	String date = Tools.getCurrentYear().substring(4);
    	System.out.println(date);
    	StringBuilder firstName = new StringBuilder();
    	for(int i=1;i<=3;i++)
    	{
    		int j = i-1;
    		int a = Integer.parseInt(date.substring(j,i));
    		firstName.append(code[a]);
   	    }
    	return firstName.toString();
    }
	/********************************************************************************************
	 *                                    生成用户登录名and生成流水号_End
	 ********************************************************************************************/
   
	
	/********************************************************************************************
	 *                                    页面动态下拉列表生成_Begin
	 ********************************************************************************************/ 
    /**
     * 获取角色下拉列表
     * @param fname
     * @return
     * @throws Exception
     */
    public static List<LabelValueBean> getOptions_type(String fname)throws Exception
    {
    	StringBuilder sql = new StringBuilder()
				.append("select ssa202,ssa201 ")
				.append("  from sa02 ")
				.append(" where ssa203!='3'")
				;
    	if(!fname.equals(""))
    	{
    		sql.append("   and ssa203!=?");
    	}
    	return executegetOptions(sql.toString(),fname);
    }
    
    /**
     * 从syscode表中查找对应中文
     * @param fname---需要翻译的属性类型名
     * @return
     * @throws Exception
     */
    public static List<LabelValueBean> getOptions_syc(String fname)throws Exception
    {
    	StringBuilder sql = new StringBuilder()
				.append("select fvalue,fcode ")
				.append("  from syscode ")
				.append(" where fname=?")
				.append(" order by fcode")		
				;
    	return executegetOptions(sql.toString(),fname);
    }
    
    /**
     * 页面动态下拉列表
     * @return
     * @throws Exception
     */
    private static List<LabelValueBean> executegetOptions(String sql,String fname)throws Exception
    {
    	PreparedStatement pstm = null;
    	ResultSet rs = null;
    	try
    	{
    		pstm = DBUtils.PrepareStatement(sql);
    		if(!fname.equals(""))
    		{
    			pstm.setObject(1, fname);
    		}   		
    		rs = pstm.executeQuery();    		
    		
    		List<LabelValueBean> opts = new ArrayList<>();
    		LabelValueBean bean = null;
    		while(rs.next())
    		{
    			bean = new LabelValueBean(rs.getString(1), rs.getString(2));
    			opts.add(bean);
    		}
    		return opts;
    	}
    	finally
    	{
    		DBUtils.close(rs);
    		DBUtils.close(pstm);
    	}
    }
    /********************************************************************************************
	 *                                    页面动态下拉列表生成_End
	 ********************************************************************************************/
    
    
    /********************************************************************************************
     *                                    MD5_Begin                  
     ********************************************************************************************/
    /**
     * 用户初始密码
     */
    public static final String INIT_PW="51ee7c97dda8bd6e0ed31ea01f50e7b1";//0000
   
    /**
     * 获取MD5密文
     * @param pwd
     * @return
     * @throws Exception
     */
    public static String getMd5Code(Object password)throws Exception
    {
	    //1.生成MD5密文
    	String md5pw1=Tools.MD5Encode(password);
    	//2.基于一次加密的密文,生成二次混淆明文
    	String md5pw2=md5pw1+"以ちねぉ無限иㄆㄚㄔㄉㄅяáǐр為有限,以無法為паセヵヱ有法,隱āγωáǎà技ㄓㄤㄖ巧于ぁゐモェィナ無形"+md5pw1;
    	//3.对混淆明文进行加密
    	String md5pwd2=Tools.MD5Encode(md5pw2);
    	return md5pwd2;
    }
   
    private final static String[] hexDigits = {
	     "0", "1", "2", "3", "4", "5", "6", "7",
	     "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
	 * 转换字节数组为16进制字串
	 * @param b 字节数组
	 * @return 16进制字串
	 */
    private static String byteArrayToHexString(byte[] b)
	{
	      StringBuffer resultSb = new StringBuffer();
	      for (int i = 0; i < b.length; i++)
	      {
	         resultSb.append(byteToHexString(b[i]));
	      }
	      return resultSb.toString();
	}
    
	/**
	 * 转换字节为16进制字符串
     * @param b byte
     * @return String
	 */
	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];
	}
  
	/**
	 * 得到MD5的秘文密码
	 * @param origin String
     * @throws Exception
     * @return String
     */
	private static String MD5Encode(Object origin) throws Exception
	{
	       String resultString = null;
	       try
	       {
	           resultString=new String(origin.toString());
	           MessageDigest md = MessageDigest.getInstance("MD5");
	           resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
	           return resultString;
	       }
	       catch (Exception ex)
	       {
	          throw ex;
	       }
    }	
    /********************************************************************************************
	 *                                    MD5_End
	 ********************************************************************************************/
    
    /**
     * main()测试
     * @param args
     */
    public static void main(String[] args)
    {
    	try 
    	{
    		System.out.println(getMd5Code("admin"));
    		/*System.out.println(Tools.baseCode);
			System.out.println(Tools.getLoginName("sta"));
			System.out.println(Tools.getMd5Code("0000"));
			System.out.println(Tools.getSequence("SSA"));*/
    		System.out.println(Tools.getfirstName());
		} catch (Exception e) 
    	{
			e.printStackTrace();
		}
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值