JavaScript自写简单国际化

luozhangwen 2010-03-16 06:05:43
1.Action配置及代码
<action-mappings >
<action path="/common" type="com.lzw.action.CommonActionAction" parameter="method" />
</action-mappings>


public class CommonActionAction extends DispatchAction
{
public ActionForward getResource(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException
{
response.setCharacterEncoding("utf-8");
String lang = "../../lang/lang_ZH_CN.properties";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(lang);
Properties resource = new Properties();
resource.load(is);
is.close();
StringBuffer sb = new StringBuffer(500);
sb.append("<Res>\n");
for (Entry<Object, Object> entry : resource.entrySet())
{
//<key value = "123"/>
sb.append(" <" + entry.getKey() + " value=\"" + entry.getValue() + "\"/>" + "\n");
}
sb.append("</Res>");
response.getWriter().print(sb.toString());
return null;
}
}

2.WebRoot/lang/lang_EN_US.properties WebRoot/lang/lang_ZH_CN.properties
...全文
520 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangzzh29 2011-08-01
  • 打赏
  • 举报
回复
顶。。。。。。。
javamangguo 2011-08-01
  • 打赏
  • 举报
回复
ding l
amos1989 2010-09-08
  • 打赏
  • 举报
回复
不错。。顶一个。
zhangzhixxm 2010-03-29
  • 打赏
  • 举报
回复
顶一个
luozhangwen 2010-03-22
  • 打赏
  • 举报
回复
2.在DAO中使用

package com.lzw.dao;

import java.util.List;

import com.lzw.base.BaseDAO;
import com.lzw.pojo.Usertable;

public class UsertableDAO extends BaseDAO {
public static UsertableDAO INSTANCE = new UsertableDAO();

private UsertableDAO() {

}

public Usertable queryById(Integer id) {
return (Usertable) hibernateProxy.QueryById(Usertable.class, id);
}

public List<Usertable> findByPropertys(Object... propertys) {
return hibernateProxy.QueryByProperty(Usertable.TABLE_OBJECT_NAME,
propertys);
}

public List<Usertable> queryAll() {
return hibernateProxy.queryAll(Usertable.TABLE_OBJECT_NAME);
}

public void delete(Usertable usertable) {
hibernateProxy.delete(usertable);
hibernateProxy.evictObject(Usertable.class, usertable.getId());
}
public List executeByHqlForPage(int first, int max, Object... properties)
{
String hql = "from " + Usertable.TABLE_OBJECT_NAME;
return hibernateProxy.executeQueryByHqlForPage(hql, first, max, properties);
}

public boolean save(Usertable usertable) {
if (usertable.getId() != null) {
hibernateProxy.evictObject(Usertable.class, usertable.getId());
}
return hibernateProxy.save(usertable);
}

public boolean update(Usertable usertable) {
if (usertable.getId() != null) {
hibernateProxy.evictObject(Usertable.class, usertable.getId());
}
return hibernateProxy.update(usertable);
}

}
luozhangwen 2010-03-22
  • 打赏
  • 举报
回复
1.Hibernate的DAO封装

package com.lzw.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class CommonHibernateProxyDAO extends BaseHibernateDAO {
private Session session = this.getSession();

public boolean save(Object object) {
Transaction tran = session.beginTransaction();
try {
session.save(object);
tran.commit();
return true;
} catch (Exception e) {
tran.rollback();
e.printStackTrace();
}
return false;
}

public boolean update(Object object) {
Transaction trans = session.beginTransaction();
try {
session.update(object);
trans.commit();
return true;
} catch (Exception e) {
trans.rollback();
e.printStackTrace();
}
return false;
}

public void delete(Object object) {
Transaction trans = session.beginTransaction();
try {
session.delete(object);
trans.commit();
} catch (Exception e) {
trans.rollback();
e.printStackTrace();
}
}
public Object QueryById(Class clazz, Serializable id) {
return session.get(clazz, id);
}
/**逐出缓存id 主键*/
public void evictObject(Class clazz, Serializable id) {
session.getSessionFactory().evict(clazz, id);
}
/**根据包.类获得对象*/
public Object getObjectByClassName(String str, Serializable id) {
return getSession().get(str, id);
}

public List queryAll(String tableName) {
String hql = "from " + tableName;
Query query = getSession().createQuery(hql);
List result = query.list();
return result;
}

public List QueryByProperty(String tableName, Object... properties) {
StringBuffer hqlRoot = new StringBuffer("from ");
hqlRoot.append(tableName);
hqlRoot.append(" as model ");
hqlRoot.append(this.getQueryString(properties));
List paramaters = this.getQueryParameter(properties);
List result = this.executeQueryByHql(hqlRoot.toString(), paramaters);
return result;
}

/*分页查询*/
public List executeQueryByHqlForPage(String hql, int first, int max,
Object... properties) {
Query query = getSession().createQuery(hql);

int index = 0;

if(properties != null)
{
for (Object object : properties) {
query.setParameter(index++, object);
}
}
query.setFirstResult(first);
query.setMaxResults(max);

return query.list();
}

public List executeQueryByHql(String hql, List paramaters) {
Query query = getSession().createQuery(hql);
int index = 0;
for (Object object : paramaters) {
query.setParameter(index++, object);
}
return query.list();
}

private String getQueryString(Object... properties) {
StringBuffer hqlRoot = new StringBuffer(10);
if (properties != null && properties.length % 2 == 0) {
int loopTime = properties.length / 2;
if (loopTime > 0) {
hqlRoot.append("where ");
for (int i = 0; i < loopTime; i++) {
if (0 < i && i <= loopTime - 1) {
hqlRoot.append(" and ");
}
hqlRoot.append("model.");
hqlRoot.append(properties[i * 2]);
hqlRoot.append(" = ? ");
}
}
}
return hqlRoot.toString();
}

private List getQueryParameter(Object... propertys) {
List parameter = new ArrayList();
if (propertys != null && propertys.length % 2 == 0) {
int loopTime = propertys.length / 2;
for (int j = 0; j < loopTime; j++) {
parameter.add(propertys[j * 2 + 1]);
}
}
return parameter;
}
}

luozhangwen 2010-03-22
  • 打赏
  • 举报
回复
1.简单国际化,获取资源改进,增加缓存

package com.lzw.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

public class ResourceManager {
//资源缓存表
private Map<String, Properties> resourceMap = Collections
.synchronizedMap(new HashMap<String, Properties>());

public Properties getResource(String lang) throws IOException {

if (resourceMap.containsKey(lang))
{
return resourceMap.get(lang);
}
// ../../lang/lang_ZH_CN.properties
String langPath = "../../lang/lang_" + lang + ".properties";
Properties properties = this.getResourceByPath(langPath);
resourceMap.put(lang, properties);
return properties;
}
private Properties getResourceByPath(String path) throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(path);
Properties resource = new Properties();
resource.load(is);
is.close();
return resource;
}
/*
//使用
response.setCharacterEncoding("utf-8");
Properties resource = new ResourceManager().getResource("ZH_CN");
StringBuffer sb = new StringBuffer(500);
sb.append("<Res>\n");
for (Entry<Object, Object> entry : resource.entrySet())
{
//<key value = "123"/>
sb.append(" <" + entry.getKey() + " value=\"" + entry.getValue() + "\"/>" + "\n");
}
sb.append("</Res>");
response.getWriter().print(sb.toString());
return null;
*/
}

小明和小红 2010-03-16
  • 打赏
  • 举报
回复
还没看完,帮顶。
bbb332 2010-03-16
  • 打赏
  • 举报
回复
学习了。。。。
luozhangwen 2010-03-16
  • 打赏
  • 举报
回复
4.使用方法

<script type="text/javascript" src="common.js"></script>
<script type="text/javascript">
var resource = new ResourceMgr();
alert(resource.getResource("test"));
</script>
luozhangwen 2010-03-16
  • 打赏
  • 举报
回复
3.页面JS,common.js

function CommUtil(){}
CommUtil.createDomDoc = function()
{
var signatures = ["Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","Msxml2.DOMDocument.3.0","Msxml2.DOMDocument","MicroSoft.XmlDom"];
for(var i=0; i<signatures.length; i++)
{
try
{
var domDoc = new ActiveXObject(signatures[i]);
if(domDoc!=null)
{
return domDoc;
}
}
catch(e)
{
alert('CommUtil.createDomDoc():Create DOM Object failed.');
}
}
}
CommUtil.getResponseDom = function(responseTextXml)
{
var domDoc = CommUtil.createDomDoc();
domDoc.loadXML(responseTextXml);
if(domDoc.documentElement)
{
return domDoc.documentElement;
}
else
{
alert('CommUtil.createDomObj():Incorrect XML String.');
return null;
}
}
CommUtil.getXMLHttpRequest = function()
{
var xmlhttp;
try
{
xmlhttp= new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e)
{
try
{
xmlhttp= new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
try
{
xmlhttp= new XMLHttpRequest();
}
catch(e)
{
alert('Error: CommUtil.getXMLHttpRequest - Failed to init XMLHttpRequest.');
}
}
}
return xmlhttp;
}

function CommService()
{
this.xmlhttp = CommUtil.getXMLHttpRequest();//获得HttpXMLRequest对象
this.onreadystatechange = function(){};
this.objParas = new Object();//请求参数键值对,存放在一个对象中
function addPara(){}; //添加参数
function getSendStr(){}; //获得组装成URL传参数的字符串
function asyncSend(action,method,data){}; //异步请求
}

CommService.prototype =
{
asyncSend:function(action,method,data)
{
var xmlhttp = this.xmlhttp;
xmlhttp.open("Post", action+".do?", false); //建立对服务器的调用
var responseText = '';
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200)
{
responseText = xmlhttp.responseText;
}
}
}

this.addPara("method",method);
if(data)
{
this.addPara("data",data.xml);//添加action的data数据参数
}
var sendStr = this.getSendStr();
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send(sendStr);

if(responseText != null)
{
return responseText;
}
},
addPara:function(name,value)
{
this.objParas[name] = name + '=' + value;
},
getSendStr:function()
{
var paras = this.objParas;
var strParas = '';

for(var p in paras)
{
strParas += paras[p] + '&';
}
if(strParas)
{
strParas = strParas.substring(0,strParas.length -1);
}
return strParas;
}
}

function ResourceMgr()
{
var comm = new CommService();
var domXml = comm.asyncSend('common','getResource',null);

this.domResource = CommUtil.getResponseDom(domXml);;
function getResource(){};
}
ResourceMgr.prototype =
{
getResource:function(key)
{
alert(this.domResource.xml);
var values = this.domResource.getElementsByTagName(key);
if(values.length != 0)
{
return values[0].getAttribute('value');
}
else
{
return '[' + key + ']';
}
}
}

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧