<servlet>
功能設計源碼以及思路-字典篇
功能說明:在項目中,將一些簡單的需要高頻率的使用的字段加載在緩存中,減少與數據庫的連接!
具體設計:
總體分爲兩塊:
第一塊是數據的加載:
1,首先是xml
<servlet>
<servlet>
<servlet-name>dhservlet</servlet-name>
<servlet-class>***.***.cache.servlet.DictionaryHelperServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
2然後是該指定類:
public class DictionaryHelperServlet extends HttpServlet{
/**
* 系統啓動初始化加載字典緩存
*/
@Override
public void init() throws ServletException {
DictionaryHelper dictionaryHelper = new DictionaryHelper();
dictionaryHelper.joinCache();
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
}
3然後在調用數據庫中的數據存入緩存中
public class DictionaryHelper {
private int t = 0;
/**
* 加入緩存
*/
public void joinCache(){
Map map = getDictCacheMap();
LoginCache.put(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER, map, 3600);
}
public static String toJson(String dictId){
DictionaryHelper dh = new DictionaryHelper();
return StringUtil.getSelectJson(dh.getDictById(dictId), false);
}
/**
* 重新封裝字典
* @return
*/
private Map getDictCacheMap(){
Map<String,List<DictDataInfo>> retMap = new HashMap<String, List<DictDataInfo>>();
List<DictManagerInfo> dmList = getDictionaryHelper();
List<DictDataInfo> ddList = getDictInfoList();
if(dmList != null){
List<DictDataInfo> retList = null;
for (int i = 0; i < dmList.size(); i++) {
DictManagerInfo managerInfo = dmList.get(i);
for(int j = 0; j < ddList.size(); j++){
DictDataInfo dataInfo = ddList.get(j);
if(managerInfo.getDict_code().equals(dataInfo.getDict_code())){
retList = retMap.get(managerInfo.getDict_code());
if(retList == null){
retList = new ArrayList<DictDataInfo>();
}
retList.add(dataInfo);
System.out.println("a"+managerInfo.getDict_code());
retMap.put(managerInfo.getDict_code(), retList);
}
}
}
}
return retMap;
}
/**
* 取所有父字典信息
* @return
*/
private List<DictManagerInfo> getDictionaryHelper(){
CompService com = BaseDAOFactory.getCompService();
Map dictmap = (Map)com.invoke("DictManagerData", "getDictManagerLists");
String rnt = "";
if(dictmap!=null){
rnt = StringUtil.toString(dictmap.get("rnt"));
}
List<DictManagerInfo> list = null;
if("1".equals(rnt)){
list = (List<DictManagerInfo>) dictmap.get("dmList");
}
return list;
}
/**
* 取所有子字典信息
* @return
*/
private List<DictDataInfo> getDictInfoList(){
CompService com = BaseDAOFactory.getCompService();
Map dictmap = (Map)com.invoke("DictManagerData", "getAllDictDataInfo");
String rnt = "";
if(dictmap!=null){
rnt = StringUtil.toString(dictmap.get("rnt"));
}
List<DictDataInfo> list = null;
if("1".equals(rnt)){
list = (List<DictDataInfo>) dictmap.get("ddList");
}
return list;
}
/**
* 取字典緩存
* @return
*/
private Map getDictCacheList(){
Map dictmap = (Map) LoginCache.get(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER);
if(dictmap == null){
joinCache();
t ++;
if(t < 3){
return getDictCacheList();
}
}
return dictmap;
}
/**
* 查詢指定表的信息,返回的兩列數據作爲菜單的optionValue 和optionText
* @param tableTag 要查詢的表的別名
* @param optionValue optionValue的列名
* @param optionText optionText的列名
* @param filterSql 其他約束條件 缺省值是“1=1”
* @return
*/
public List<CustomDictInfo> getCustonDict(String tableTag,String optionValue,String optionText,String filterSql){
List<CustomDictInfo> list = null;
if(tableTag!=null && !"".equals(tableTag)){
if(filterSql==null || "".equals(filterSql)){
filterSql = " 1=1 ";
}
CompService com = BaseDAOFactory.getCompService();
com.addParameter(tableTag);
com.addParameter(optionValue);
com.addParameter(optionText);
com.addParameter(filterSql);
Map dictmap = (Map)com.invoke("DictionaryHelperData", "getCustomDictList");
String rnt = "";
if(dictmap!=null){
rnt = StringUtil.toString(dictmap.get("rnt"));
}
if("1".equals(rnt)){
list = (List<CustomDictInfo>) dictmap.get("cdList");
}
}
return list;
}
/**
* 根據父字典ID查詢子項列表
* @param dictId
* @return
*/
public List<DictDataInfo> getDictById(String dictId){
Map dictmap = getDictCacheList();
List<DictDataInfo> dataInfos = (List<DictDataInfo>) dictmap.get(dictId);
return dataInfos;
}
/**
* 根據父字典ID和子字典ID查詢文本內容
* @param dictId
* @param id
* @return
*/
public String getDictTextById(String dictId,String id){
Map dictmap = getDictCacheList();
List<DictDataInfo> dataInfos = (List<DictDataInfo>) dictmap.get(dictId);
String text = "";
if(dataInfos != null){
for (int i = 0; i < dataInfos.size(); i++) {
DictDataInfo dataInfo = dataInfos.get(i);
if(id.equals(dataInfo.getDict_small_code())){
text = dataInfo.getDict_text();
break;
}
}
}
return text;
}
/**
* 根據父字典ID和子字典文本內容查詢子字典ID
* @param dictId
* @param id
* @return
*/
public String getDictIdByText(String dictId,String text){
Map dictmap = getDictCacheList();
List<DictDataInfo> dataInfos = (List<DictDataInfo>) dictmap.get(dictId);
String id = "";
if(dataInfos != null){
for (int i = 0; i < dataInfos.size(); i++) {
DictDataInfo dataInfo = dataInfos.get(i);
if(text.equals(dataInfo.getDict_text())){
id = dataInfo.getDict_code();
break;
}
}
}
return id;
}
/**
* 加入緩存
* @return
*/
public void setDictInfo(DictDataInfo dataInfo){
if(dataInfo != null){
Map dictmap = getDictCacheList();
String dictid = dataInfo.getParient_id();
String id = dataInfo.getDict_code();
List<DictDataInfo> dataInfos = (List<DictDataInfo>) dictmap.get(dictid);
if(dataInfos != null){
boolean b = true;
for (int i = 0; i < dataInfos.size(); i++) {
DictDataInfo info = dataInfos.get(i);
if(id.equals(info.getDict_code())){
b = false;
break;
}
}
if(b){
dataInfos.add(dataInfo);
}
LoginCache.remove(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER);
LoginCache.put(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER, dictmap, 3600);
}
}
}
/**
* 修改緩存字典內容
* @param dataInfo
*/
public void modifyDictInfo(DictDataInfo dataInfo){
if(dataInfo != null){
Map dictmap = getDictCacheList();
String dictid = dataInfo.getParient_id();
String id = dataInfo.getDict_code();
List<DictDataInfo> dataInfos = (List<DictDataInfo>) dictmap.get(dictid);
if(dataInfos != null){
boolean b = false;
for (int i = 0; i < dataInfos.size(); i++) {
DictDataInfo info = dataInfos.get(i);
if(id.equals(info.getDict_code())){
dataInfos.remove(i);
b = true;
break;
}
}
if(b){
dataInfos.add(dataInfo);
}
LoginCache.remove(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER);
LoginCache.put(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER, dictmap, 3600);
}
}
}
/**
* 刪除緩存字典內容
* @param dataInfo
*/
public void removeDictInfo(String dict_id,String id){
if(dict_id != null && !"".equals(dict_id) && id != null && !"".equals(id)){
Map dictmap = getDictCacheList();
List<DictDataInfo> dataInfos = (List<DictDataInfo>) dictmap.get(dict_id);
if(dataInfos != null){
for (int i = 0; i < dataInfos.size(); i++) {
DictDataInfo info = dataInfos.get(i);
if(id.equals(info.getDict_code())){
dataInfos.remove(i);
break;
}
}
LoginCache.remove(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER);
LoginCache.put(LoginConfig.USER_DICTIONARY_HELPER, LoginConfig.DICTIONARY_HELPER, dictmap, 3600);
}
}
}
public static void main(String[] args) {
DictionaryHelper dh = new DictionaryHelper();
DictDataInfo dataInfo = new DictDataInfo();
dataInfo.setParient_id("anticoagulant");
dataInfo.setDict_text("sssssssssssssssssss");
dataInfo.setDict_code("sda");
dh.setDictInfo(dataInfo);
List<DictDataInfo> list = dh.getDictById("anticoagulant");
for (int i = 0; i < list.size(); i++) {
DictDataInfo d = list.get(i);
System.out.println(d.getDict_text());
}
String text = dh.getDictIdByText("anticoagulant", "無肝素");
System.out.println("text:"+text);
String id = dh.getDictTextById("sys_sex", "1");
System.out.println("id:"+id);
}
}
public class LoginCache {
private static CacheManager singleton = CacheManager.getInstance();
/**
* 存入緩存
* @param cacheName 主緩存名稱
* @param key 子緩存主鍵名稱
* @param value 需要緩存的數據
* @param timeToIdleSeconds 緩存時間
*/
public static synchronized void put(String cacheName, Object key, Object value, int timeToIdleSeconds){
Cache cache = null;
if(StringHelper.isEmpty(cacheName)){
return;
}
if(key == null){
return;
}
if(!singleton.cacheExists(cacheName)){
singleton.addCache(cacheName);
cache = singleton.getCache(cacheName);
}
cache = singleton.getCache(cacheName);
Element e = new Element(key, value);
e.setTimeToIdle(timeToIdleSeconds);
cache.put(e);
}
/**
* 根據主鍵緩存獲取全部緩存內容
* @param cacheName 主鍵
* @return
*/
public static synchronized List<Map> getAllUserMessage(String cacheName){
List<Map> userlist = null;
try{
Cache cache = null;
if(StringHelper.isEmpty(cacheName)){
return userlist;
}
if(!singleton.cacheExists(cacheName))
return null;
cache = singleton.getCache(cacheName);
List list = cache.getKeys();
if(list != null && list.size() > 0){
userlist = new ArrayList<Map>();
int s = list.size();
for (int j = 0; j < s; j++) {
String key = (String)list.get(j);
Element e = cache.get(key);
if(e != null){
Map user = (Map)e.getObjectValue();
if(user != null)
userlist.add(user);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return userlist;
}
/**
* 刪除子項緩存
* @param cachename 主鍵緩存名稱
* @param key 子項緩存名稱
*/
public static synchronized void remove(String cachename, Object key){
try{
if(StringHelper.isEmpty(cachename)){
return;
}
if(!singleton.cacheExists(cachename)){
return;
}
Cache cache = singleton.getCache(cachename);
cache.remove(key);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 獲取緩存
* @param cachename 主鍵緩存名稱
* @param key 子項緩存名稱
* @return
*/
public static Object get(String cachename,Object key){
Object o = null;
if(!singleton.cacheExists(cachename)){
return o;
}
Cache cache = singleton.getCache(cachename);
if(!cache.isKeyInCache(key)){
return o;
}
Element e = cache.get(key);
if(e != null)
o = e.getObjectValue();
return o;
}
/**
* 獲取緩存子項
* @param cachename 主鍵緩存名稱
* @return
*/
public static Ehcache getCache(String cachename){
Cache cache = null;
if(!singleton.cacheExists(cachename)){
return cache;
}
cache = singleton.getCache(cachename);
return cache;
}
}
4在項目應用中,調用該類的changeDictValWithBeanList()方法,將數據庫中的比如(1,2,3等數字)轉化成對應的字典數據
/**
* 測試處理Bean多列字典的問題
* @author DongChao
*
*/
public class DictionaryUtil {
/**
* 依次將beanList中的項目(beanParams)用指定的字典(dictNames)替換
* beanParams 的順序要和dictNames一致
* @param beanList
* @param beanParams
* @param dictNames
* @return
*/
public static List changeDictValWithBeanList(List beanList,String [] beanParams,String[] dictNames){
DictionaryHelper dh = new DictionaryHelper();
if(beanList!=null && beanList.size()>0){// 入股list爲空,無法處理,原樣返回list
if(beanParams==null){//如果參數名爲空則無法處理,原樣返回list
return beanList;
}if(dictNames==null){//如果字典爲空則無法處理,原樣返回list
return beanList;
}
if(beanParams.length!=dictNames.length){//bean的內容和字典數量不匹配則無法處理,原樣返回list
return beanList;
}
HashMap paramsAndDicts = StringArrToHashMap(beanParams,dictNames);
for(int i=0;i<beanList.size();i++){
Object bean = beanList.get(i);
PropertyDescriptor[] props = null;
try {
props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (props != null) {
for(int j=0;j<props.length;j++){
String name = props[j].getName();//bean中的成員變量的名字
//Arrays.sort(beanParams);
String dictName = (String)paramsAndDicts.get(name);
if(dictName!=null && !"".equals(dictName)){
//取出原始值
try {
String oriaValue = props[j].getReadMethod().invoke(bean).toString() ;
//將value轉換成字典的文本值
//System.out.println(dictName+"=="+oriaValue);
String dictText=dh.getDictTextById(dictName, oriaValue);
//將轉換後的文本寫會到Bean中
Method methodSet=props[j].getWriteMethod();
methodSet.invoke(bean, dictText);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
return beanList;
}
private static HashMap StringArrToHashMap(String [] beanParams,String[] dictNames){
HashMap map = new HashMap();
for(int i=0;i<beanParams.length;i++){
map.put(beanParams[i], dictNames[i]);
}
return map ;
}
}
5.實際的調用的例子:
DictionaryUtil dt = new DictionaryUtil();
String []beanParams = new String []{"sex","blood_type","rh_blood_type","charge_type","insurance_type","patient_state"};
String []dictNames = new String []{"sys_sex","sys_blood_type","sys_rh_blood_type","sys_charge_type","sys_insurance_type","sys_patient_state"};
list = dt.changeDictValWithBeanList(list, beanParams, dictNames);//獲取緩存中對應的數據值
DictionaryHelper dh = new DictionaryHelper();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.