<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>曾华水的博客 &#187; Java</title>
	<atom:link href="http://www.mrzeng.com/topics/java/feed" rel="self" type="application/rss+xml" />
	<link>http://www.mrzeng.com</link>
	<description>NO.1 or Nothing</description>
	<lastBuildDate>Wed, 07 Sep 2011 12:47:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Json下的Positioned Update not supported解决方法</title>
		<link>http://www.mrzeng.com/post/json-positioned-update-not-supported.html</link>
		<comments>http://www.mrzeng.com/post/json-positioned-update-not-supported.html#comments</comments>
		<pubDate>Fri, 10 Jun 2011 05:03:08 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=275</guid>
		<description><![CDATA[今天使用json输出的时候报了这个错误，原因找了一下，发现使用hibernate自动生成的一些类会出现这个情况，主要是因为hibernate使用了延迟加载所造成的缘故。 因为我的系统前台使用的jquery-easeyui的dataGrid表格，所以，只能重新建一个类来进行。代码如下 package com.mrzeng.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.huashui.authentication.AuthName; import org.huashui.dto.PageBean; import org.huashui.service.IPaginate; import org.huashui.util.StringUtils; import org.huashui.util.WebUtils; import com.mrzeng.hibernate.Category; import com.mrzeng.hibernate.Crawlrecord; import com.mrzeng.hibernate.Saleinfo; import com.mrzeng.hibernate.Shop; import com.mrzeng.hibernate.Shopdetail; import com.mrzeng.service.IAnalysisService; /** * @fileName ShopdetailAction.java * @author 曾华水 [...]]]></description>
			<content:encoded><![CDATA[<div>今天使用json输出的时候报了这个错误，原因找了一下，发现使用hibernate自动生成的一些类会出现这个情况，主要是因为hibernate使用了延迟加载所造成的缘故。<br />
因为我的系统前台使用的jquery-easeyui的dataGrid表格，所以，只能重新建一个类来进行。代码如下
</div>
<pre class=prettyprint>
package com.mrzeng.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.huashui.authentication.AuthName;
import org.huashui.dto.PageBean;
import org.huashui.service.IPaginate;
import org.huashui.util.StringUtils;
import org.huashui.util.WebUtils;

import com.mrzeng.hibernate.Category;
import com.mrzeng.hibernate.Crawlrecord;
import com.mrzeng.hibernate.Saleinfo;
import com.mrzeng.hibernate.Shop;
import com.mrzeng.hibernate.Shopdetail;
import com.mrzeng.service.IAnalysisService;

/**
 * @fileName ShopdetailAction.java
 * @author  曾华水
 * @email zenghuashui@gmail.com
 * @date Jun 10, 2011
 * @time 9:07:13 AM
 * 代码类代码编写规约：add-增加，edit修改，remove删除，list列出全部，排除用ex，tree代表树
 */
@ParentPackage("huashui-default")
@Namespace("/admin")
@Results( {
		@Result(name = "saleinfo", location = "/WEB-INF/data/saleinfo.jsp"),
		@Result(name = "json", location = "/WEB-INF/view/json.jsp"),
		@Result(name = "jsonfilter", location = "/WEB-INF/view/jsonfilter.jsp"),
		@Result(name = "jsonfiltertype", location = "/WEB-INF/view/jsonfiltertype.jsp") })
public class SaleinfoAction {

	@Resource
	private IPaginate paginate;
	@Resource
	private IAnalysisService analysisService;
	private Integer rows;
	private Integer page;
	private Integer total;
	private String sort;
	private String order;

	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public Integer getRows() {
		return rows;
	}
	public void setRows(Integer rows) {
		this.rows = rows;
	}
	public Integer getPage() {
		return page;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	public Integer getTotal() {
		return total;
	}
	public void setTotal(Integer total) {
		this.total = total;
	}
	@Action("data_saleinfo")
	@AuthName("DATA_SALEINFO")
	public String index(){
		List<shop> shops = analysisService.listShop();
		List<crawlrecord> crawls = analysisService.listCrawlrecord();
		StringBuilder sb = new StringBuilder();
		for (Shop shop : shops) {
			if (!StringUtils.isNull(sb.toString())) {
				sb.append(",\r\n");
			}
			sb.append("{").append("id:").append(shop.getId()).append(
					",name:\"").append(shop.getName()).append(
					"\"}\r\n");
		}
		WebUtils.getRequest().setAttribute("shops", sb.toString());

		StringBuilder sb2 = new StringBuilder();
		for (Crawlrecord crawlrecord : crawls) {
			if (!StringUtils.isNull(sb2.toString())) {
				sb2.append(",\r\n");
			}
			sb2.append("{").append("id:").append(crawlrecord.getId()).append(
					",name:\"").append(StringUtils.dateToString(crawlrecord.getCrawltime(), "yyyy-MM-dd hh:mm:ss")).append(
					"\"}\r\n");
		}
		WebUtils.getRequest().setAttribute("crawls", sb2.toString());
		return "saleinfo";
	}
	@Action("data_saleinfo_list")
	@AuthName("DATA_SALEINFO")
	public String list(){
		Map<string , Object> data = new HashMap</string><string , Object>();
		StringBuilder sql = new StringBuilder();
		sql.append("from ").append(Saleinfo.class.getSimpleName());
		sql.append(" where 1=1");

		if (!StringUtils.isNull(sort) &#038;&#038; !StringUtils.isNull(order)) {
			if (order.trim().equalsIgnoreCase("desc")
					|| order.trim().equalsIgnoreCase("asc"))
				sql.append(" order by ").append(sort).append(" ").append(order);
		}
		PageBean pageBean = new PageBean();
		pageBean.setPage(page);
		pageBean.setPageSize(rows);

		pageBean.setListSQL(sql.toString());
		try {
			pageBean.setCount(paginate.getTotalCount(pageBean).intValue());
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<saleinfo> list = paginate.getList(pageBean);
		List<saleinfobean> rList = new ArrayList</saleinfobean><saleinfobean>();
		for (Saleinfo saleinfo : list) {
			SaleinfoBean bean = new SaleinfoBean();
			bean.setBuyer(saleinfo.getBuyer());
			bean.setBuyerCode(saleinfo.getBuyerCode());
			bean.setBuyerLevel(saleinfo.getBuyerLevel());
			bean.setBuyNum(saleinfo.getBuyNum());
			bean.setBuyTime(saleinfo.getBuyTime());
			bean.setCrawlId(saleinfo.getCrawlrecord().getId());
			bean.setGoodDesc(saleinfo.getGoodDesc());
			bean.setGoodPrice(saleinfo.getGoodPrice());
			bean.setGoodTitle(saleinfo.getGoodTitle());
			bean.setGoodUrl(saleinfo.getGoodUrl());
			bean.setId(saleinfo.getId());
			bean.setShopId(saleinfo.getShop().getId());
			rList.add(bean);
		}
		data.put("rows", rList);
		data.put("total", pageBean.getCount());

		WebUtils.getRequest().setAttribute("data", data);
		WebUtils.getRequest().setAttribute("type", "Set");
		return "jsonfiltertype";

	}

	public class SaleinfoBean{
		private Long id;
		private Integer shopId;
		private Long  crawlId;
		private Date buyTime;
		private Integer buyNum;
		private String buyer;
		private String buyerCode;
		private Integer buyerLevel;
		private String goodTitle;
		private String goodDesc;
		private Double goodPrice;
		private String goodUrl;
		public Long getId() {
			return id;
		}
		public void setId(Long id) {
			this.id = id;
		}
		public Integer getShopId() {
			return shopId;
		}
		public void setShopId(Integer shopId) {
			this.shopId = shopId;
		}
		public Long getCrawlId() {
			return crawlId;
		}
		public void setCrawlId(Long crawlId) {
			this.crawlId = crawlId;
		}
		public Date getBuyTime() {
			return buyTime;
		}
		public void setBuyTime(Date buyTime) {
			this.buyTime = buyTime;
		}
		public Integer getBuyNum() {
			return buyNum;
		}
		public void setBuyNum(Integer buyNum) {
			this.buyNum = buyNum;
		}
		public String getBuyer() {
			return buyer;
		}
		public void setBuyer(String buyer) {
			this.buyer = buyer;
		}
		public String getBuyerCode() {
			return buyerCode;
		}
		public void setBuyerCode(String buyerCode) {
			this.buyerCode = buyerCode;
		}
		public Integer getBuyerLevel() {
			return buyerLevel;
		}
		public void setBuyerLevel(Integer buyerLevel) {
			this.buyerLevel = buyerLevel;
		}
		public String getGoodTitle() {
			return goodTitle;
		}
		public void setGoodTitle(String goodTitle) {
			this.goodTitle = goodTitle;
		}
		public String getGoodDesc() {
			return goodDesc;
		}
		public void setGoodDesc(String goodDesc) {
			this.goodDesc = goodDesc;
		}
		public Double getGoodPrice() {
			return goodPrice;
		}
		public void setGoodPrice(Double goodPrice) {
			this.goodPrice = goodPrice;
		}
		public String getGoodUrl() {
			return goodUrl;
		}
		public void setGoodUrl(String goodUrl) {
			this.goodUrl = goodUrl;
		}

	}
}

</saleinfobean></saleinfo></string></crawlrecord></shop></pre>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/json-utils.html" title="Json工具类">Json工具类</a><br /><small>jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。

代码如下：

@SuppressWarnings("unchecked")
public class JsonUtils {

	

	/**
	 * 从一个JSON 对象字符...</small></li><li><a href="http://www.mrzeng.com/post/sql-server-jdbc.html" title="SQL Server的JDBC驱动问题">SQL Server的JDBC驱动问题</a><br /><small>最近公司换服务器把数据库从SQL Server 2005 升级到 SQL Server 2008。这样，以这个数据库对接的两个系统全部瘫痪，无法进行数据库对接。
首先立即判断是是数据库的驱动问题，好不容易从网上找到了了驱动，下载下来，发现里面有两个文件一个是sqljdbc.jar，另外一个是sqljdbc4.jar,于是将驱动换掉，两个全部导进去，加到CLASSPATH路径，发现，还是不行。两个...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/json-positioned-update-not-supported.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Json工具类</title>
		<link>http://www.mrzeng.com/post/json-utils.html</link>
		<comments>http://www.mrzeng.com/post/json-utils.html#comments</comments>
		<pubDate>Wed, 03 Mar 2010 08:06:40 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JAVA]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=155</guid>
		<description><![CDATA[jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。 代码如下： @SuppressWarnings("unchecked") public class JsonUtils { /** * 从一个JSON 对象字符格式中得到一个java对象，形如： * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}} * @param object * @param clazz * @return */ public static Object getDTO(String jsonString, Class clazz) { JSONObject jsonObject = null; try { setDataFormat2JAVA(); jsonObject = JSONObject.fromObject(jsonString); } catch (Exception e) [...]]]></description>
			<content:encoded><![CDATA[<p>jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。<br />
<span id="more-155"></span><br />
代码如下：</p>
<pre class=prettyprint>
@SuppressWarnings("unchecked")
public class JsonUtils {

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，形如：
	 * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}}
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz) {
		JSONObject jsonObject = null;
		try {
			setDataFormat2JAVA();
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject, clazz);
	}

	/**
	 * 从一个JSON 对象字符格式中得到一个java对象，其中beansList是一类的集合，形如：
	 * {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...},
	 * beansList:[{}, {}, ...]}
	 * @param jsonString
	 * @param clazz
	 * @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class)
	 * @return
	 */
	public static Object getDTO(String jsonString, Class clazz, Map map) {
		JSONObject jsonObject = null;
		try {
			setDataFormat2JAVA();
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject, clazz, map);
	}

	/**
	 * 从一个JSON数组得到一个java对象数组，形如：
	 * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static Object[] getDTOArray(String jsonString, Class clazz) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i &lt; array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz);
		}
		return obj;
	}

	/**
	 * 从一个JSON数组得到一个java对象数组，形如：
	 * [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
	 * @param object
	 * @param clazz
	 * @param map
	 * @return
	 */
	public static Object[] getDTOArray(String jsonString, Class clazz, Map map) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		Object[] obj = new Object[array.size()];
		for (int i = 0; i &lt; array.size(); i++) {
			JSONObject jsonObject = array.getJSONObject(i);
			obj[i] = JSONObject.toBean(jsonObject, clazz, map);
		}
		return obj;
	}

	/**
	 * 从一个JSON数组得到一个java对象集合
	 * @param object
	 * @param clazz
	 * @return
	 */

	public static List getDTOList(String jsonString, Class clazz) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}

	/**
	 * 从一个JSON数组得到一个java对象集合，其中对象中包含有集合属性
	 * @param object
	 * @param clazz
	 * @param map 集合属性的类型
	 * @return
	 * class MyBean{
	 *   private List data;
	 *		   // getters &#038; setters
	 *	}
	 *
	 * class Person{
	 *	   private String name;
	 *	   // getters &#038; setters
	 *	}
	 *
	 *	...
	 *
	 *	String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";
	 *  Map classMap = new HashMap();
	 *	classMap.put( "data", Person.class );
	 *	MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );
	 */
	public static List getDTOList(String jsonString, Class clazz, Map map) {
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for (Iterator iter = array.iterator(); iter.hasNext();) {
			JSONObject jsonObject = (JSONObject) iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz, map));
		}
		return list;
	}

	/**
	 * 从json HASH表达式中获取一个map，该map支持嵌套功能
	 * 形如：{"id" : "johncon", "name" : "小强"}
	 * 注意commons-collections版本，必须包含org.apache.commons.collections.map.MultiKeyMap
	 * @param object
	 * @return
	 */
	public static Map getMapFromJson(String jsonString) {
		setDataFormat2JAVA();
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Map map = new HashMap();
		for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
			String key = (String) iter.next();
			map.put(key, jsonObject.get(key));
		}
		return map;
	}

	/**
	 * 从json数组中得到相应java数组
	 * json形如：["123", "456"]
	 * @param jsonString
	 * @return
	 */
	public static Object[] getObjectArrayFromJson(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);
		return jsonArray.toArray();
	}

	/**
	 * 把数据对象转换成json字符串
	 * DTO对象形如：{"id" : idValue, "name" : nameValue, ...}
	 * 数组对象形如：[{}, {}, {}, ...]
	 * map对象形如：{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...}
	 * @param object
	 * @return
	 */
	public static String getJSONString(Object object) throws Exception {
		String jsonString = null;
		//日期值处理器
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new JsonDateValueProcessor());
		if (object != null) {
			if (object instanceof Collection || object instanceof Object[]) {
				jsonString = JSONArray.fromObject(object, jsonConfig)
						.toString();
			} else {
				jsonString = JSONObject.fromObject(object, jsonConfig)
						.toString();
			}
		}
		return jsonString == null ? "{}" : jsonString;
	}

	private static void setDataFormat2JAVA() {
		//设定日期转换格式
		JSONUtils.getMorpherRegistry().registerMorpher(
				new DateMorpher(new String[] { "yyyy-MM-dd",
						"yyyy-MM-dd HH:mm:ss" }));
	}

	public static void main(String[] arg) throws Exception {
		String s = "{status : 'success'}";
		System.out.println(" object : " + JsonUtils.getJSONString(s));
	}
}
</pre>
<p></code>
<pre class=prettyprint>
public class JsonDateValueProcessor implements JsonValueProcessor {

	private String format = "yyyy-MM-dd HH:mm:ss";

	public JsonDateValueProcessor() {

	}

	public JsonDateValueProcessor(String format) {
		this.format = format;
	}

	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	private Object process( Object value, JsonConfig jsonConfig ) {
		if (value instanceof Date) {
			String str = new SimpleDateFormat(format).format((Date) value);
			return str;
		}
		return value == null ? null : value.toString();
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

}
</pre>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/json-positioned-update-not-supported.html" title="Json下的Positioned Update not supported解决方法">Json下的Positioned Update not supported解决方法</a><br /><small>今天使用json输出的时候报了这个错误，原因找了一下，发现使用hibernate自动生成的一些类会出现这个情况，主要是因为hibernate使用了延迟加载所造成的缘故。
因为我的系统前台使用的jquery-easeyui的dataGrid表格，所以，只能重新建一个类来进行。代码如下


package com.mrzeng.action;

import java.util.Array...</small></li><li><a href="http://www.mrzeng.com/post/sql-server-jdbc.html" title="SQL Server的JDBC驱动问题">SQL Server的JDBC驱动问题</a><br /><small>最近公司换服务器把数据库从SQL Server 2005 升级到 SQL Server 2008。这样，以这个数据库对接的两个系统全部瘫痪，无法进行数据库对接。
首先立即判断是是数据库的驱动问题，好不容易从网上找到了了驱动，下载下来，发现里面有两个文件一个是sqljdbc.jar，另外一个是sqljdbc4.jar,于是将驱动换掉，两个全部导进去，加到CLASSPATH路径，发现，还是不行。两个...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/json-utils.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>struts2的action中获得request response session 对象</title>
		<link>http://www.mrzeng.com/post/struts2-action-request-response-session.html</link>
		<comments>http://www.mrzeng.com/post/struts2-action-request-response-session.html#comments</comments>
		<pubDate>Wed, 03 Mar 2010 01:17:54 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Struts2]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=153</guid>
		<description><![CDATA[在struts2中有两种方式可以得到这些对象,一般有两种方式，一种是利用Ioc实现拦截器接口，一种是使用静态类。分布如下 第一种方式，非IoC方式，使用ActionContext类和ServletActionContext类，例如 HttpServletResponse response(HttpServletResponse) = ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); HttpServletRequest request(HttpServletRequest) = } ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST); HttpServletResponse response = ServletActionContext.getResponse() response.getWriter().write("hello world"); 第二种就是使用Ioc的方式，实现ServletResponseAware、ServletRequestAware、SessionAware和CookiesAware等接口。例子如下 import com.opensymphony.xwork2.ActionSupport; import javax.servlet.http.*; import org.apache.struts2.interceptor.*; public class MyAction extends ActionSupport implements ServletResponseAware{ private javax.servlet.http.HttpServletResponse response; // 获得HttpServletResponse对象 public void setServletResponse(HttpServletResponse response){ this.response = response; } public String execute() throws Exception { response.getWriter().write("实现ServletResponseAware接口"); } import java.util.Map; import [...]]]></description>
			<content:encoded><![CDATA[<p>在struts2中有两种方式可以得到这些对象,一般有两种方式，一种是利用Ioc实现拦截器接口，一种是使用静态类。分布如下<br />
<span id="more-153"></span><br />
第一种方式，非IoC方式，使用ActionContext类和ServletActionContext类，例如</p>
<pre class=prettyprint>
HttpServletResponse response(HttpServletResponse) =
ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
HttpServletRequest request(HttpServletRequest) = }
ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
</pre>
<pre class=prettyprint>
 HttpServletResponse response = ServletActionContext.getResponse()
response.getWriter().write("hello world");
</pre>
<p>第二种就是使用Ioc的方式，实现ServletResponseAware、ServletRequestAware、SessionAware和CookiesAware等接口。例子如下</p>
<pre class=prettyprint>
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.*;
import org.apache.struts2.interceptor.*;

public class MyAction extends ActionSupport implements ServletResponseAware{
    private javax.servlet.http.HttpServletResponse response;
    // 获得HttpServletResponse对象
    public void setServletResponse(HttpServletResponse response){
    this.response = response;
}
    public String execute() throws Exception
        {
    response.getWriter().write("实现ServletResponseAware接口");
       }
</pre>
<pre class=prettyprint>
import java.util.Map;
import org.apache.struts2.*;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.*;
import com.opensymphony.xwork2.util.*;
import org.apache.struts2.interceptor.*;

public class FirstAction extends ActionSupport implements RequestAware{
private Map request;
private HttpServletResponse response;       

       public void setRequest(Map request){
                this.request = request;
       }
public String execute() throws Exception {
           java.util.Set&lt;string&gt; keys = request.keySet(); // 枚举所有的key值。实际上只有一个key:struts.valueStack
         for(String key: keys)
             System.out.println(key); // 获得OgnlValueStack 对象
            OgnlValueStack stack = (OgnlValueStack)myRequest.get("struts.valueStack");   // 获得HttpServletResponse对象
            response =(HttpServletResponse)stack.getContext().get(StrutsStatics.HTTP_RESPONSE);
           response.getWriter().write("实现RequestAware 接口");
        }
}
&lt;/string&gt;</pre>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/struts-2-annotations-example-1.html" title="Struts 2注解实例二">Struts 2注解实例二</a><br /><small>这个例子将继续前面讲的例子

Here we will see the same hello user example with the following changes.


	Our Action class ends with the world Action and does not implement com.opensymphony.xwork2.Action. 
	We...</small></li><li><a href="http://www.mrzeng.com/post/struts2-resources-study.html" title="Struts2的教程资源下载汇总">Struts2的教程资源下载汇总</a><br /><small>目前，国内的java培训貌似很热，这应该和国内的环境有关系。特别是随着电子商务的发展，越来越多的平台都转换到java的平台上来进行开发建设。
原来自己一直使用Struts1，虽然很早知道Struts2出来了，但是一直没时间去看。最近花了点时间看下，感觉确实比Struts1.x好得多。个人感觉有以下几点
   1、可以开始使用注解，使用注解的方式一直是我最喜欢的开发方式。虽然从软件开发的理念来讲...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/struts2-action-request-response-session.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jsp中文验证码</title>
		<link>http://www.mrzeng.com/post/jsp-chinese-verifycode.html</link>
		<comments>http://www.mrzeng.com/post/jsp-chinese-verifycode.html#comments</comments>
		<pubDate>Mon, 01 Mar 2010 02:52:34 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[验证码]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=196</guid>
		<description><![CDATA[网上找到一个不错的中文验证码，稍微改了改，解决了输出时的报错。还不错。代码如下： &#60; %@page contentType="image/jpeg" pageEncoding="GB2312" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*,java.io.*"%&#62; 　　 &#60; %! //生成随机颜色 Color getRandColor(Random random, int fc, int bc) { if (fc &#62; 255) fc = 255; if (bc &#62; 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - [...]]]></description>
			<content:encoded><![CDATA[<p>网上找到一个不错的中文验证码，稍微改了改，解决了输出时的报错。还不错。代码如下：<br />
<span id="more-196"></span></p>
<pre class=prettyprint>
&lt; %@page contentType="image/jpeg" pageEncoding="GB2312" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*,java.io.*"%&gt;
　　
&lt; %!

   //生成随机颜色
   Color getRandColor(Random random, int fc, int bc) {
     if (fc &gt; 255) fc = 255;
     if (bc &gt; 255) bc = 255;
     int r = fc + random.nextInt(bc - fc);
     int g = fc + random.nextInt(bc - fc);
     int b = fc + random.nextInt(bc - fc);
     return new Color(r, g, b);
   }
%&gt;
　　
&lt; %
   //设置页面不缓存
   response.setHeader("Pragma", "No-cache");
   response.setHeader("Cache-Control", "no-cache");
   response.setDateHeader("Expires", 0);
   // 设置图片的长宽
   int width = 50, height = 30;
   //设置备选汉字，剔除一些不雅的汉字
   String base = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48u8d77u4f60u90fdu628au597du8fd8u591au6ca1u4e3au53c8u53efu5bb6u5b66u53eau4ee5u4e3bu4f1au6837u5e74u60f3u751fu540cu8001u4e2du5341u4eceu81eau9762u524du5934u9053u5b83u540eu7136u8d70u5f88u50cfu89c1u4e24u7528u5979u56fdu52a8u8fdbu6210u56deu4ec0u8fb9u4f5cu5bf9u5f00u800cu5df1u4e9bu73b0u5c71u6c11u5019u7ecfu53d1u5de5u5411u4e8bu547du7ed9u957fu6c34u51e0u4e49u4e09u58f0u4e8eu9ad8u624bu77e5u7406u773cu5fd7u70b9u5fc3u6218u4e8cu95eeu4f46u8eabu65b9u5b9eu5403u505au53ebu5f53u4f4fu542cu9769u6253u5462u771fu5168u624du56dbu5df2u6240u654cu4e4bu6700u5149u4ea7u60c5u8defu5206u603bu6761u767du8bddu4e1cu5e2du6b21u4eb2u5982u88abu82b1u53e3u653eu513fu5e38u6c14u4e94u7b2cu4f7fu5199u519bu5427u6587u8fd0u518du679cu600eu5b9au8bb8u5febu660eu884cu56e0u522bu98deu5916u6811u7269u6d3bu90e8u95e8u65e0u5f80u8239u671bu65b0u5e26u961fu5148u529bu5b8cu5374u7ad9u4ee3u5458u673au66f4u4e5du60a8u6bcfu98ceu7ea7u8ddfu7b11u554au5b69u4e07u5c11u76f4u610fu591cu6bd4u9636u8fdeu8f66u91cdu4fbfu6597u9a6cu54eau5316u592au6307u53d8u793eu4f3cu58ebu8005u5e72u77f3u6ee1u65e5u51b3u767eu539fu62ffu7fa4u7a76u5404u516du672cu601du89e3u7acbu6cb3u6751u516bu96beu65e9u8bbau5417u6839u5171u8ba9u76f8u7814u4ecau5176u4e66u5750u63a5u5e94u5173u4fe1u89c9u6b65u53cdu5904u8bb0u5c06u5343u627eu4e89u9886u6216u5e08u7ed3u5757u8dd1u8c01u8349u8d8au5b57u52a0u811au7d27u7231u7b49u4e60u9635u6015u6708u9752u534au706bu6cd5u9898u5efau8d76u4f4du5531u6d77u4e03u5973u4efbu4ef6u611fu51c6u5f20u56e2u5c4bu79bbu8272u8138u7247u79d1u5012u775bu5229u4e16u521au4e14u7531u9001u5207u661fu5bfcu665au8868u591fu6574u8ba4u54cdu96eau6d41u672au573au8be5u5e76u5e95u6df1u523bu5e73u4f1fu5fd9u63d0u786eu8fd1u4eaeu8f7bu8bb2u519cu53e4u9ed1u544au754cu62c9u540du5440u571fu6e05u9633u7167u529eu53f2u6539u5386u8f6cu753bu9020u5634u6b64u6cbbu5317u5fc5u670du96e8u7a7fu5185u8bc6u9a8cu4f20u4e1au83dcu722cu7761u5174u5f62u91cfu54b1u89c2u82e6u4f53u4f17u901au51b2u5408u7834u53cbu5ea6u672fu996du516cu65c1u623fu6781u5357u67aau8bfbu6c99u5c81u7ebfu91ceu575au7a7au6536u7b97u81f3u653fu57ceu52b3u843du94b1u7279u56f4u5f1fu80dcu6559u70edu5c55u5305u6b4cu7c7bu6e10u5f3au6570u4e61u547cu6027u97f3u7b54u54e5u9645u65e7u795eu5ea7u7ae0u5e2eu5566u53d7u7cfbu4ee4u8df3u975eu4f55u725bu53d6u5165u5cb8u6562u6389u5ffdu79cdu88c5u9876u6025u6797u505cu606fu53e5u533au8863u822cu62a5u53f6u538bu6162u53d4u80ccu7ec6";
   //备选汉字的长度
   int length = base.length();
   //创建内存图像
   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   // 获取图形上下文
   Graphics g = image.getGraphics();
   //创建随机类的实例
   Random random = new Random();
   // 设定图像背景色(因为是做背景，所以偏淡)
   g.setColor(getRandColor(random, 200, 250));
   g.fillRect(0, 0, width, height);
   //备选字体
   String[] fontTypes = {
       "u5b8bu4f53", "u65b0u5b8bu4f53", "u9ed1u4f53", "u6977u4f53", "u96b6u4e66"};
   int fontTypesLength = fontTypes.length;
   //在图片背景上增加噪点
   g.setColor(getRandColor(random, 160, 200));
   g.setFont(new Font("Times New Roman", Font.PLAIN, 14));
   for (int i = 0; i &lt; 6; i++) {
     g.drawString("*********************************************", 0, 5 * (i + 2));
   }
   //取随机产生的认证码(6个汉字)
   //保存生成的汉字字符串
   String sRand = "";
   for (int i = 0; i &lt; 1; i++) {
     int start = random.nextInt(length);
     String rand = base.substring(start, start + 1);
     sRand += rand;
   //设置字体的颜色
     g.setColor(getRandColor(random, 10, 150));
   //设置字体
     g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)], Font.BOLD, 18 + random.nextInt(6)));
   //将此汉字画到图片上
     g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);
   }
   //将认证码存入session
   session.setAttribute("chkcode", sRand);
   g.dispose();
   //输出图象到页面
   OutputStream os = response.getOutputStream();
   ImageIO.write(image, "JPEG", os);
   os.flush();
   os.close();
   response.flushBuffer();
   //解决页面报错。
	out.clear();
	out = pageContext.pushBody();
%&gt;
</pre>
<h3  class="related_post_title">随机日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/flash-voice.html" title="系统、FLASH播放没有声音的处理方法">系统、FLASH播放没有声音的处理方法</a><br /><small>如果出现系统如QQ上线等没有声音、而且FLASH播放也没有声音。那么可以这么检查：1、检查声卡：在我的电脑点击右键，选择硬件中的设备管理器，点声音、视频和游戏控制器前面的+，如果子项目中有红色的叉叉，那么就说明没有安装好驱动。2、如果你是使用音箱，那么请调换音响的插孔，换下声道试试。...</small></li><li><a href="http://www.mrzeng.com/post/wps_office.html" title="推荐使用WPS的几个原因">推荐使用WPS的几个原因</a><br /><small>近，微软的“黑屏”事件一直闹得沸沸扬扬。
 
对我来说，原来用的是OFFICE2003，后面换了2007. 特别是到了2007，打开的时候经常要出现崩溃。 我一直不怎么用微软的OFFICE。自己一直用的是金山的WPS。倒不是因为“爱国”。WPS软件的体积比较小。还有几个优点。
 
1、最令我喜欢的WPS的 *（自由访问）的权限* ，对与自己重要的文件，我一般都用这个设置访问权限。但2007...</small></li><li><a href="http://www.mrzeng.com/post/guzhidejianchi.html" title="固执的坚持">固执的坚持</a><br /><small>刚刚从徐MM转载了一篇文章—蜘蛛的爱情。不禁想起刚看完的连续剧《白领公寓》。

1、白领公寓里讲的主要是珍惜眼前人。有时候，人固执的坚持自己心中的一个梦想，带着这个理由去做这些事情，可是事实上这些并不是真正适合他的。

2、另一个方向：两个长久相爱的人也不一定是真正的合适，是否也是一种固执的坚持，觉得说既然在一起就要一直的坚持，可事实上真正和他合适的，可以天长地久的在旁边的那一位。从这个角...</small></li><li><a href="http://www.mrzeng.com/post/json-utils.html" title="Json工具类">Json工具类</a><br /><small>jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。

代码如下：

@SuppressWarnings("unchecked")
public class JsonUtils {

	

	/**
	 * 从一个JSON 对象字符...</small></li><li><a href="http://www.mrzeng.com/post/chongshi.html" title="重拾">重拾</a><br /><small>重拾起博客，发现好久没写了，竟然孵化出了懒惰，还是像重新建起来，写写。

过去的几个月，自己做了好多决定，回想，一切都是不可思议，人生，就是这样，只有写在记忆里面的，才能明白，才能细细品味。享受人生要往前看，感悟人生只能往后看。
2011年9月7日于曾厝垵。...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/jsp-chinese-verifycode.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>改变Eclipse默认编码</title>
		<link>http://www.mrzeng.com/post/change-eclipse-encoding.html</link>
		<comments>http://www.mrzeng.com/post/change-eclipse-encoding.html#comments</comments>
		<pubDate>Mon, 01 Mar 2010 02:46:27 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Eclipse]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=194</guid>
		<description><![CDATA[windows &#8211;&#62; preferences &#8211;&#62; General &#8211;&#62; Content types &#8211;&#62; Text tree &#8211;&#62; Jsp 我们设置最下面的Default Encoding为UTF-8即可. 随机日志在windows上安装nginx+php环境目前，nginx以其独特的性能越来越博得喜爱，LNMP环境逐步代替了LAMP环境。Nginx从v0.7.52也开始支持windows环境。接下来简要介绍些安装方法。 1、准备好安装软件 Nginx ：我们选用最新的稳定版本0.7.65。http://nginx.org/download/nginx-0.7.65.zip PHP:http://www.php.net/g...Linux中修改ip的办法切换到root账户下 切换到/etc/sysconfig/network-scripts/目录下； 编辑网卡编码：vi ifcfg-ethX X为第X-1个网卡。 DEVICE=ethX 设备名称 ONBOOT=yes 计算...使用Properties文件来对Log4j进行配置Log4j will be usually configured using a properties file or xml file externally. So once the log statements are in place you can easily control them using the [...]]]></description>
			<content:encoded><![CDATA[<p><span style="COLOR: red"><strong>windows &#8211;&gt; preferences &#8211;&gt; General  &#8211;&gt;  Content types  &#8211;&gt; Text tree  &#8211;&gt; Jsp  我们设置最下面的Default Encoding为UTF-8即可.</strong></span><br />
<span id="more-194"></span></p>
<div id="attachment_316" class="wp-caption alignnone" style="width: 448px"><a href="http://www.mrzeng.com/wp-content/uploads/2010/03/2131213.jpg"><img class="size-medium wp-image-316" title="2131213" src="http://huashui.org/wp-content/uploads/2010/03/2131213-300x264.jpg" alt="2131213" width="438" height="334" /></a><p class="wp-caption-text">改变Eclipse默认编码</p></div>
<h3  class="related_post_title">随机日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/stormlive-exe.html" title="如何去掉暴风影音的stormlive.exe进程">如何去掉暴风影音的stormlive.exe进程</a><br /><small>如果安装了暴风影音，常常会在任务管理器的进程中发现stormlive.exe，这是暴风影音的升级程序。如下图



该进程一般来说没有什么太大的用处，而且耗费系统资源。可以设置将其取消掉。方法有两种。

第一种。

进入控制面板，找到管理工具，选择服务，进入下图界面



找到Contrl Center of Storm Media,双击，出现下述界面



点击停...</small></li><li><a href="http://www.mrzeng.com/post/jqgrid_base_study_1.html" title="jqGrid基础学习：1认识jqGrid">jqGrid基础学习：1认识jqGrid</a><br /><small>1、在项目中，使用一款合适的表格软件会让开发事半功倍，jqGrid提供搜索、分页功能，添加、编辑、删除和搜索表中记录等，是一款优秀的Grid的。

2、jqGrid是基于jQuery，作为jQuery的插件存在的，所以，使用前必须先导入jQuery包,同时，它支持Query的UI theme（from3.6）。

3、支持数组、json、xml、本地等格式作为数据源，一般情况下均使用jso...</small></li><li><a href="http://www.mrzeng.com/post/json-utils.html" title="Json工具类">Json工具类</a><br /><small>jqGrid在处理多字段查询的时候要使用json数据，于是，参考了网上的一些写法，写了一个json工具类。其中那个时间格式化，是为了解决json在处理java的java.util.Date出现的问题。

代码如下：

@SuppressWarnings("unchecked")
public class JsonUtils {

	

	/**
	 * 从一个JSON 对象字符...</small></li><li><a href="http://www.mrzeng.com/post/excel_id.html" title="身份证的编码安排规则">身份证的编码安排规则</a><br /><small>弄个Excel，可以自动生成，进行验证。

cardid

居民身份证编号识别

1、身份证编码规则如下：根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定，公民身份号码是特征组合码，由十七位数字本体码和一位数字校验码组成。排列顺序从左至右依次为：六位数字地址码，八位数字出生日期码，三位数字顺序码和一位数字校验码。

地址码（身份证前六位）表示编码对象第...</small></li><li><a href="http://www.mrzeng.com/post/chkdsk-f.html" title="磁盘碎片整理提示要运行Chkdsk /f的处理方法">磁盘碎片整理提示要运行Chkdsk /f的处理方法</a><br /><small>硬盘处理要进行碎片整理时候，如果出现一个写“磁盘碎片整理提示要运行Chkdsk /f”的对话框，那么处理方面如下：
 1、打开运行，输入Chkdsk /f ,在命令行中填写n，回车
 2、重启电脑。...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/change-eclipse-encoding.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2注解实例二</title>
		<link>http://www.mrzeng.com/post/struts-2-annotations-example-1.html</link>
		<comments>http://www.mrzeng.com/post/struts-2-annotations-example-1.html#comments</comments>
		<pubDate>Thu, 25 Feb 2010 07:53:34 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[Struts2]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=146</guid>
		<description><![CDATA[这个例子将继续前面讲的例子 Here we will see the same hello user example with the following changes. Our Action class ends with the world Action and does not implement com.opensymphony.xwork2.Action. We use /results directory for storing our result pages instead of WEB-INF/content. 和上个例子对比，我们做了如下变更， Action类以Action结尾，同时不实现com.opensymphony.xwork2.Action接口 我们使用/results目录为存放我们的result页面，而不再放在WEB-INF/content目录. The directory structure of the hello user example is shown below. 目录的结构如下 Our [...]]]></description>
			<content:encoded><![CDATA[<p>这个例子将继续<a href="http://huashui.org/post/struts-2-annotations-example.html">前面讲的例子</a><br />
<span id="more-146"></span><br />
Here we will see the same hello user example with the following changes.</p>
<ul>
<li>Our Action class ends with the world Action and does not implement com.opensymphony.xwork2.Action. </li>
<li>We use /results directory for storing our result pages instead of WEB-INF/content. </li>
</ul>
<p>和上个例子对比，我们做了如下变更，</p>
<ul>
<li>Action类以Action结尾，同时不实现com.opensymphony.xwork2.Action接口</li>
<li>我们使用/results目录为存放我们的result页面，而不再放在WEB-INF/content目录.</li>
</ul>
<p>The directory structure of the hello user example is shown below.<br />
目录的结构如下<br />
<div class="wp-caption alignnone" style="width: 305px"><a href="http://www.vaannila.com/images/struts2/Annotation2Pic1.gif"><img alt="Annotation2Pic1" src="http://www.vaannila.com/images/struts2/Annotation2Pic1.gif" title="Annotation2Pic1" width="295" height="545" /></a><p class="wp-caption-text">Annotation2Pic1</p></div></p>
<p>Our WelcomeUserAction class is a simple pojo class. The important thing to note here is that our Action classs name ends with the word Action.<br />
我们的WelcomeUserAction类是一个简单的pojo类。但重要的是我们的类名药以Action结尾。</p>
<pre class=prettyprint>
package com.vaannila.action; 

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result; 

public class WelcomeUserAction { 

	private String userName; 

	private String message; 

	@Action(value="/welcome",results={ @Result(name="success",location="/results/successPage.jsp")}) 

	public String execute() { 

		message = "Welcome " + userName + " !"; 

		return "success"; 

	} 

	public void setUserName(String userName) { 

		this.userName = userName; 

	} 

	public void setMessage(String message) { 

		this.message = message; 

	} 

	public String getUserName() { 

		return userName; 

	} 

	public String getMessage() { 

		return message; 

	}
}
</pre>
<p>Here we use Action and Result annotations just to show you how to use them, for simple example like this you can use the intelligent defaults provided by the Convention plug-in.<br />
这里，我们使用Action和Result注解主要是为了来介绍如何使用它们，我们也可以想前一个简单例子那样使用插件包默认的方式。</p>
<p>The Convention plug-in uses the Action class name to map the action URL. The Convention plug-in first removes the world Action at the end of the class name and then converts the camel case name to dashes. So by default our WelcomeUserAction will be invoked for the request URL welcome-user. But if you want the Action to be invoked for a different URL then you can do this by using the <strong>Action annotation</strong>.<br />
Convention 插件使用Actin类名来映射器URL。它首先去掉类后面的Action后缀，然后在使用驼峰的地方转换为破折号。所以，默认情况下WelcomeUserAction要通过请求welcome-user来访问。但如果你要让Action使用一个不同的URL来进行，你必须使用<strong>Action注解</strong>。</p>
<p>The value of the Action annotation is “/welcome”, this means that the action will be invoked for the request URL “/welcome”. You can change the default action and URL mapping using the Action annotation.<br />
Action注解的值为“/welcome”，这意味着这个action将通过/welcome进行访问。你能够通过使用Action注解来改变默认的action和URL映射。</p>
<p>Now based on the result code from action the Convention plug-in will look for the result name welcome-resultcode in the directory WEB-INF/content. You can change this to a different location by setting the property <em>struts.convention.result.path </em>to a new value in the Struts properties file. In this example we store the result pages in /results directory.<br />
现在，在Action的result code基础上，Convention将在WEB-INF/content查找welcome-resultcode的文件。有可以通过改变struts的properties文件中的<em>struts.convention.result.path </em>值来改变results的目录。</p>
<pre class=prettyprint>
struts.properties file
-----------------------
struts.convention.result.path=/results
</pre>
<p>Our result page name is successPage.jsp, the Convention plug-in will look for a page like welcome.jsp ( the file can even be a freemaker or velocity file ) since our URL is “/welcome”. In this case it will give an error, if we are not specifying which result it should invoke when the result is “success”. To do this we use the Result annotation.<br />
我们的result页面的名字是successPage.jsp。Convention插件会查找welcome.jsp文件，因为我们Action的URL为“/welcome”。在这个例子中，如我们没有指定他的的success的result，那么将会出错。为此，我们可以使用Result注解。</p>
<p>The <strong>Result annotation </strong>maps the result code with the result page. Here the result code “success” is mapped to the result “/results/successPage.jsp”.</p>
<p>在Result注解中，我们用一个result code来指定映射的页面。这里的result code为“success”，被映射到的“/results/successPage.jsp”页面。</p>
<p>The annotations needs to be specified only when you are not using the default naming conventions, if you use them you can keep writing action classes and result pages without any configuration and the framework know exactly when to invoke them.<br />
当你没有使用插件默认的名字规约的时候来需要使用注解。如果你使用了，你可以实现没有任何配置文件下些Action和result页面，而框架能够根据需要进行调用。</p>
<p>源码<br />
Source :<a href="http://www.vaannila.com/examples/struts2/src/Struts2Example2.zip">Download </a><br />
Source + Lib :<a href="http://www.vaannila.com/examples/struts2/example/Struts2Example2.war">Download</a> </p>
<p>原文地址：<a href="http://www.vaannila.com/struts-2/struts-2-example/struts-2-annotations-example-1.html">http://www.vaannila.com/struts-2/struts-2-example/struts-2-annotations-example-1.html</a></p>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/struts2-action-request-response-session.html" title="struts2的action中获得request response session 对象">struts2的action中获得request response session 对象</a><br /><small>在struts2中有两种方式可以得到这些对象,一般有两种方式，一种是利用Ioc实现拦截器接口，一种是使用静态类。分布如下

第一种方式，非IoC方式，使用ActionContext类和ServletActionContext类，例如

HttpServletResponse response(HttpServletResponse) =
ActionContext.getContext(...</small></li><li><a href="http://www.mrzeng.com/post/struts-2-annotations-example.html" title="Struts 2注解实例一">Struts 2注解实例一</a><br /><small>本文将通过一个前台通过表单输入user，来实现hello user的方式来讲述Struts2中使用注解。

首先要引入以下jar包

commons-fileupload-1.2.1 
commons-io-1.3.2 
commons-logging-1.1 
freemarker-2.3.13 
junit-3.8.1 
onl-2.6.11 
spring-test-2....</small></li><li><a href="http://www.mrzeng.com/post/struts2-resources-study.html" title="Struts2的教程资源下载汇总">Struts2的教程资源下载汇总</a><br /><small>目前，国内的java培训貌似很热，这应该和国内的环境有关系。特别是随着电子商务的发展，越来越多的平台都转换到java的平台上来进行开发建设。
原来自己一直使用Struts1，虽然很早知道Struts2出来了，但是一直没时间去看。最近花了点时间看下，感觉确实比Struts1.x好得多。个人感觉有以下几点
   1、可以开始使用注解，使用注解的方式一直是我最喜欢的开发方式。虽然从软件开发的理念来讲...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/struts-2-annotations-example-1.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2注解实例一</title>
		<link>http://www.mrzeng.com/post/struts-2-annotations-example.html</link>
		<comments>http://www.mrzeng.com/post/struts-2-annotations-example.html#comments</comments>
		<pubDate>Thu, 25 Feb 2010 07:23:53 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[Struts]]></category>
		<category><![CDATA[注解]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=142</guid>
		<description><![CDATA[本文将通过一个前台通过表单输入user，来实现hello user的方式来讲述Struts2中使用注解。 首先要引入以下jar包 commons-fileupload-1.2.1 commons-io-1.3.2 commons-logging-1.1 freemarker-2.3.13 junit-3.8.1 onl-2.6.11 spring-test-2.5.6 struts2-convention-plugin-2.1.6 struts2-core-2.1.6 xwork-2.1.2 首先要确定一下版本是否正确，此外struts2-convention-plugin-2.1.6 是必须加入的，这个包是用来注解的核心包。 目录的结构如下： 接下来书写表单输入页面 &#60; %@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&#62; &#60; !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&#62; &#60; %@taglib uri="/struts-tags" prefix="s" %&#62; &#60;html&#62; &#60;head&#62; &#60;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&#62; &#60;title&#62;Hello World&#60;/title&#62; &#60;/meta&#62;&#60;/head&#62; &#60;body&#62; &#60;s:form action="welcome-user" &#62; &#60;s:textfield name="userName" label="User Name" [...]]]></description>
			<content:encoded><![CDATA[<p>本文将通过一个前台通过表单输入user，来实现hello user的方式来讲述Struts2中使用注解。<br />
<span id="more-142"></span><br />
首先要引入以下jar包</p>
<pre class=prettyprint>
commons-fileupload-1.2.1
commons-io-1.3.2
commons-logging-1.1
freemarker-2.3.13
junit-3.8.1
onl-2.6.11
spring-test-2.5.6
struts2-convention-plugin-2.1.6
struts2-core-2.1.6
xwork-2.1.2
</pre>
<p>首先要确定一下版本是否正确，此外struts2-convention-plugin-2.1.6 是必须加入的，这个包是用来注解的核心包。<br />
目录的结构如下：<br />
<div class="wp-caption alignnone" style="width: 327px"><a href="http://www.vaannila.com/images/struts2/Annotation1Pic1.gif"><img alt="structure of the hello user example" src="http://www.vaannila.com/images/struts2/Annotation1Pic1.gif" title="structure of the hello user example" width="317" height="514" /></a><p class="wp-caption-text">structure of the hello user example</p></div><br />
接下来书写表单输入页面</p>
<pre class=prettyprint>
&lt; %@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt;
&lt; !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt; %@taglib uri="/struts-tags" prefix="s" %&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
		&lt;title&gt;Hello World&lt;/title&gt;
	&lt;/meta&gt;&lt;/head&gt;
	&lt;body&gt;
		&lt;s:form action="welcome-user" &gt;
		&lt;s:textfield name="userName" label="User Name" /&gt;
		&lt;s:submit /&gt;
		&lt;/s:form&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>需要注意的是表单中action为url的名字。<br />
我们在WelcomeUser 的类中布置好欢迎信息，返回“success”。</p>
<pre class=prettyprint>
package com.vaannila.action; 

import com.opensymphony.xwork2.ActionSupport; 

public class WelcomeUser extends ActionSupport{ 

	private String userName; 

	private String message; 

	public String execute() { 

		message = "Welcome " + userName; 

		return SUCCESS; 

	} 

	public void setUserName(String userName) { 

		this.userName = userName; 

	} 

	public void setMessage(String message) { 

		this.message = message; 

	} 

	public String getUserName() { 

		return userName; 

	} 

	public String getMessage() { 

		return message; 

	}
}
</pre>
<p>这里有没有发现我们action的url和名字有没有相似之处呢？<br />
我们再welcome-user.jsp 显示返回的欢迎信息。如下：</p>
<pre class=prettyprint>
&lt; %@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%&gt;
&lt; !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
		&lt;title&gt;Welcome User&lt;/title&gt;
	&lt;/meta&gt;&lt;/head&gt;
	&lt;body&gt; 

		&lt;h1&gt;${message}&lt;/h1&gt; 

	&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>配置web.xml</p>
<pre class=prettyprint>
&lt; ?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web -app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; 

&lt;display -name&gt;Struts2Example1&lt;/display&gt; 

&lt;filter&gt; 

	&lt;/filter&gt;&lt;filter -name&gt;struts2&lt;/filter&gt; 

	&lt;filter -class&gt; 

	org.apache.struts2.dispatcher.ng.filter. StrutsPrepareAndExecuteFilter 

	&lt;/filter&gt; 

&lt;filter -mapping&gt; 

	&lt;/filter&gt;&lt;filter -name&gt;struts2&lt;/filter&gt; 

	&lt;url -pattern&gt;/*&lt;/url&gt; 

&lt;welcome -file-list&gt; 

	&lt;/welcome&gt;&lt;welcome -file&gt;index.jsp&lt;/welcome&gt; 

&lt;/web&gt;
</pre>
<p>部署执行下http://localhost:8080/Struts2Example1，我们可以看到。<br />
<div id="attachment_297" class="wp-caption alignnone" style="width: 310px"><a href="http://huashui.org/wp-content/uploads/2010/02/Annotation1Pic2.gif"><img src="http://huashui.org/wp-content/uploads/2010/02/Annotation1Pic2-300x138.gif" alt="Annotation1Pic2" title="Annotation1Pic2" width="300" height="138" class="size-medium wp-image-297" /></a><p class="wp-caption-text">Annotation1Pic2</p></div><br />
随便输入一个名字，即可得到如下<br />
<div id="attachment_298" class="wp-caption alignnone" style="width: 310px"><a href="http://huashui.org/wp-content/uploads/2010/02/Annotation1Pic3.gif"><img src="http://huashui.org/wp-content/uploads/2010/02/Annotation1Pic3-300x138.gif" alt="Annotation1Pic3" title="Annotation1Pic3" width="300" height="138" class="size-medium wp-image-298" /></a><p class="wp-caption-text">Annotation1Pic3</p></div></p>
<p>接下来，我们看下它是如何进行的。<br />
<strong>Convention plug-in</strong>是在后台运行的。</p>
<ul>
<li>considered as the root package for the Convention plug-in.<br />
默认下，Convention plug-in 会在struts，struts2，action或者actions等包中进行查找。这里，我们的包名为com.vaannila.action。任何满足以上条件的的包都将被引入。</li>
<li>action类应该要继承com.opensymphony.xwork2.Action接口或者action类名以Action结尾。我们的例子中，WelcomeUser继承于com.opensymphony.xwork2.ActionSupport，从而也是实现了com.opensymphony.xwork2.Action。</li>
<li>Convention plug-in使用action的类名来映射成对应的URL。例子中的类名为WelcomeUser，它对应的URL为welcome-user.</li>
<li>接下里看看下results，他并不知道文件在哪个目录下面，但Convention plug-in将根据Action名来进行判断，例如，如何返回“success”，那么将自动查找文件名为welcome-user-success.jsp 或 welcome-user.jsp。</li>
</ul>
<p>Source :<a href="http://www.vaannila.com/examples/struts2/src/Struts2Example1.zip">Download </a><br />
Source + Lib :<a href="http://www.vaannila.com/examples/struts2/example/Struts2Example1.war">Download</a>  </p>
<p>原文地址：<br />
<a href="http://www.vaannila.com/struts-2/struts-2-example/struts-2-annotation-example-1.html">http://www.vaannila.com/struts-2/struts-2-example/struts-2-annotation-example-1.html</a></p>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/struts-2-annotations-example-1.html" title="Struts 2注解实例二">Struts 2注解实例二</a><br /><small>这个例子将继续前面讲的例子

Here we will see the same hello user example with the following changes.


	Our Action class ends with the world Action and does not implement com.opensymphony.xwork2.Action. 
	We...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/struts-2-annotations-example.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>使用Properties文件来对Log4j进行配置</title>
		<link>http://www.mrzeng.com/post/log4j-configuration-using-properties-file.html</link>
		<comments>http://www.mrzeng.com/post/log4j-configuration-using-properties-file.html#comments</comments>
		<pubDate>Tue, 09 Feb 2010 00:58:33 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Log4j]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=125</guid>
		<description><![CDATA[Log4j will be usually configured using a properties file or xml file externally. So once the log statements are in place you can easily control them using the external configuration file without modifying the source code. Now let&#8217;s see how you can obtain the same log output as the previous example using the properties file [...]]]></description>
			<content:encoded><![CDATA[<p>Log4j will be usually configured using a properties file or xml file externally. So once the log statements are in place you can easily control them using the external configuration file without modifying the source code. Now let&#8217;s see how you can obtain the same log output as the previous example using the properties file configuration.<br />
Log4j通常采用一个properties文件或者xml文件从外部进行配置。所以一旦你需要更改日志的声明，只需要修改外部文件而不必修改源代码。现在，让我们看看如何使用一个properties配置文件来实现前面的例子，得到一样的输出结果。</p>
<p><span id="more-125"></span><br />
Three main components you need to configure to obtain the same result are the logger, appender and layout. The logger object is the one that is used to log messages, appender is the one that specifies the output destination like console or a file and layout is the one that specify the format in which the log messages should be logged.<br />
要实现和前面例子一样，logger、appender和layout是你需要进行配置的三大核心要素。logger是用来记录信息，appender是用来指定输出方向，例如控制台或者文件，layout是来指定输出的日志的格式。</p>
<p>When you configure using the<em> BasicConfigurator.configure() </em>method by default it uses the <em>ConsoleAppender </em>and <em>PatternLayout </em>for all the loggers.<br />
The following configuration creates the same result as the <em>BasicConfigurator.configure() </em>method.<br />
当你使用<em>BasicConfigurator.configure()</em>方法时，模式将使用<em>ConsoleAppender </em>（控制台输出）和PatternLayout进行输出。<br />
一下的配置将使用<em>BasicConfigurator.configure()</em>时同样的效果。</p>
<pre class=prettyprint>
log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
</pre>
<p>The <em>rootLogger</em> is the one that resides on the top of the logger hierarchy. Here we set its level to <em>DEBUG</em> and added the console appender (CA) to it. The console appender can have arbitrary name, here its name is CA.<br />
rootLogger是日志的跟记录器，代表日志的最高层。我们设置他的级别为DEBUG，设定输出为控制台输出。控制台的输出器可以有一个专有的名字。这里的名字是CA。</p>
<p>You need to create an appender as shown and set its layout to PatternLayout. The PatternLayout uses the ConversionPattern to format the message. To know more about the various formating options you can refer the documentation. ( <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html">PatternLayout </a>)<br />
设置外设计器后，我们需要设置它的layout为PatternLayout。它的PatternLayout使用ConversionPattern来格式化信息。想了解更多的格式化选项可以去看下参考文档（<a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html">PatternLayout </a>) ）</p>
<p>Once the appender is created and its layout is set you need to specify which loggers can use this appender. If you set this appender to the rootLogger then all the loggers will log messge to this appender. Since the rootLogger is on top of the hierarchy all the loggers will inherit its logger level and its appenders. You will see this in more detail in the comming examples.<br />
Here is our example code. </p>
<p>当appender创建并且layout也设置好了之后要制定那个日志记录器可以使用这个apperder。如果你设置这个appender指定为rootLogger，那么所有的日志记录器将使用这个appender来进行记录信息。因为rootLogger处于所有日志记录器的最高层(即所有的日志记录器都将继承它),内置了所有的的日志级别。我们可以从接下里的例子看到更多的细节。<br />
以下是示例代码</p>
<pre class=prettyprint>
package com.vaannila.helloworld; 

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator; 

public class HelloWorld { 

static final Logger logger = Logger.getLogger(HelloWorld.class); 

public static void main(String[] args) {
		PropertyConfigurator.configure("log4j.properties");
		logger.debug("Sample debug message");
		logger.info("Sample info message");
		logger.warn("Sample warn message");
		logger.error("Sample error message");
		logger.fatal("Sample fatal message");
	}
}
</pre>
<p>You need to use the<em> PropertyConfigurator.configure() </em>method to configure log4j using a properties file. Log4j should be configured only once for the entire application.<br />
你需要使用PropertyConfigurator.configure() 方法配合properties文件来一起配置log4j。Log4j在整个应用中只需配置一次。</p>
<p>When you execute the example the following output will be displayed on the console.<br />
当你执行这个例子后，将在控制台上显示一下信息</p>
<pre class=prettyprint>
0    [main] DEBUG com.vaannila.helloworld.HelloWorld  - Sample debug message
0    [main] INFO  com.vaannila.helloworld.HelloWorld  - Sample info message
0    [main] WARN  com.vaannila.helloworld.HelloWorld  - Sample warn message
0    [main] ERROR com.vaannila.helloworld.HelloWorld  - Sample error message
0    [main] FATAL com.vaannila.helloworld.HelloWorld  - Sample fatal message
</pre>
<p>Since the <em>rootLogger</em> level is set to <em>DEBUG</em> all the messages are displayed.<br />
因为rootLogger的水平设置为DEBUG，所以所有的信息均输出。<br />
The log4j levels follow the following order. </p>
<ul>
<li>DEBUG</li>
<li>INFO</li>
<li>WARN</li>
<li>ERROR</li>
<li>FATAL</li>
</ul>
<p>If you set the rootLogger level to WARN then only the WARN, ERROR and FATAL level log messages will be displayed and the rest will be dropped.<br />
如果你设置rootLogger的水平为WARN，那么只有WARN，ERROR和FATAL水平的日志会输出。</p>
<pre class=prettyprint>
log4j.rootLogger=WARN, CA
</pre>
<pre class=prettyprint>
0    [main] WARN  com.vaannila.helloworld.HelloWorld  - Sample warn message
15   [main] ERROR com.vaannila.helloworld.HelloWorld  - Sample error message
15   [main] FATAL com.vaannila.helloworld.HelloWorld  - Sample fatal message
</pre>
<p>The directory structure of the project is shown below.<br />
整个项目的目录结构如下：<br />
<div class="wp-caption alignnone" style="width: 307px"><a href="http://www.vaannila.com/images/log4j/log4j-example2-pic1.gif"><img alt="Log4j Configuration Using Properties File" src="http://www.vaannila.com/images/log4j/log4j-example2-pic1.gif" title="Log4j Configuration Using Properties File" width="297" height="136" /></a><p class="wp-caption-text">Log4j Configuration Using Properties File</p></div></p>
<p>You can download the log4j configuration file here. </p>
<p>Source :<a href="http://www.vaannila.com/examples/log4j/src/Log4jExample2.zip">Download </a><br />
Source + Lib :<a href="http://www.vaannila.com/examples/log4j/example/Log4jExample2.zip">Download </a></p>
<p>本文的原文地址为：<a href="http://www.vaannila.com/log4j/sample-log4j-properties-file-configuration-1.html">http://www.vaannila.com/log4j/sample-log4j-properties-file-configuration-1.html</a></p>
<p>译者注：<br />
1、Log4j常用的优先级FATAL>ERROR>WARN>INFO>DEBUG<br />
2、layout，翻译成中文是布局，但本来感觉意思还是不够贴切，就不翻译了。log4j提供一下四种布局<br />
    org.apache.log4j.HTMLLayout（以HTML表格形式布局）<br />
    org.apache.log4j.PatternLayout（可以灵活地指定布局模式），<br />
    org.apache.log4j.SimpleLayout（包含日志信息的级别和信息字符串），<br />
    org.apache.log4j.TTCCLayout（包含日志产生的时间、线程、类别等等信息）<br />
3、appender也就是日志输出的目的地。</p>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/simple-log4j-configuration.html" title="简单的Log4j配置">简单的Log4j配置</a><br /><small>在struts2的网站上看到一个不错的网站：http://www.vaannila.com 看到里面的一些文章很不错。从今天开始陆续翻译一些文章。今天开始翻译Log4j。

Log4j is a simple and flexible logging framework. In this tutorial you will learn how to configure log4j for yo...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/log4j-configuration-using-properties-file.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>简单的Log4j配置</title>
		<link>http://www.mrzeng.com/post/simple-log4j-configuration.html</link>
		<comments>http://www.mrzeng.com/post/simple-log4j-configuration.html#comments</comments>
		<pubDate>Mon, 08 Feb 2010 06:24:04 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Log4j]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=121</guid>
		<description><![CDATA[在struts2的网站上看到一个不错的网站：http://www.vaannila.com 看到里面的一些文章很不错。从今天开始陆续翻译一些文章。今天开始翻译Log4j。 Log4j is a simple and flexible logging framework. In this tutorial you will learn how to configure log4j for your applications. Let’s get started first download the latest version of log4j ( Download ). I am using log4j version 1.2.15. Add the log4j-1.2.15.jar to the classpath. Log4j是一个简单而且灵活的日志记录框架，在这教程中，我们将学习到在你的应用中如何对log4j进行配置。首先下载最新的版本log4j（下载）。我使用的是1.2.15版本。将Jar包log4j-1.2.15.jar 加入类路径。 Next you need to create [...]]]></description>
			<content:encoded><![CDATA[<p>在struts2的网站上看到一个不错的网站：<a href="http://www.vaannila.com">http://www.vaannila.com</a> 看到里面的一些文章很不错。从今天开始陆续翻译一些文章。今天开始翻译Log4j。</p>
<p>Log4j is a simple and flexible logging framework. In this tutorial you will learn how to configure log4j for your applications. Let’s get started first download the latest version of log4j ( <a href="http://logging.apache.org/log4j/1.2/download.html">Download</a> ). I am using log4j version 1.2.15. Add the log4j-1.2.15.jar to the classpath.<br />
Log4j是一个简单而且灵活的日志记录框架，在这教程中，我们将学习到在你的应用中如何对log4j进行配置。首先下载最新的版本log4j（<a href="http://logging.apache.org/log4j/1.2/download.html">下载</a>）。我使用的是1.2.15版本。将Jar包log4j-1.2.15.jar 加入类路径。</p>
<p>Next you need to create an instance of Logger class. You can create one using the Logger.getLogger(HelloWorld.class) method. It takes one argument the fully qualified class name.<br />
接下来，我们需要创建一个Logger类实例。我们可以创建一个使用Logger.getLogger(Helloworld.class)的方法。该方法需要传递一个类的完整名字。</p>
<p>Now we need to configure log4j. The simple way to do that is using <em>BasicConfigurator. configure() </em>method. This will log all the messages on the console.<br />
现在，我们需要配置下log4j。简单的方法是使用<em>BasicConfigurator. configure() </em>方法。这将会在控制台输出记录的所有信息。</p>
<p>Now everything is ready you can log messages using any of the print statements of the<em> Logger </em>class. In the following code I use the <em>debug() </em>method to display the “HelloWorld!” message.<br />
现在，所有的都准备好了。我们可以使用Logger类中任何的输出方式来记录这些消息。在接下来的代码中，我使用debug的方法来显示“Helloworld!”的信息。</p>
<pre class="prettyprint">
package comvaannilahelloworld;
import orgapachelog4jBasicConfigurator;
import orgapachelog4jLogger;  

public class HelloWorld {     

	static final Logger logger = LoggergetLogger(HelloWorld.class);

	public static void main(String[] args) {
		BasicConfiguratorconfigure();
		loggerdebug("Hello World!");
	}
}</pre>
<p>The other methods available are info(), warn(), error() and fatal(). Each method represents a logger level namely DEBUG, INFO, WARN, ERROR and FATAL.<br />
The following example shows how to use these methods.<br />
此外，还可以使用 info(), warn(), error() and fatal()等方法。每个方法代表了一个日志记录级别分别为： DEBUG, INFO, WARN, ERROR and FATAL.<br />
接下里的一个例子将演示如何使用这些方法</p>
<pre class="prettyprint">
package comvaannilahelloworld;
import orgapachelog4jBasicConfigurator;
import orgapachelog4jLogger; 

public class HelloWorld {
	static final Logger logger = LoggergetLogger(HelloWorldclass);
	public static void main(String[] args) { 

		BasicConfiguratorconfigure(); 

		loggerdebug("Sample debug message"); 

		loggerinfo("Sample info message"); 

		loggerwarn("Sample warn message"); 

		loggererror("Sample error message"); 

		loggerfatal("Sample fatal message"); 

	}
}
</pre>
<p>Here is the output of the above code.<br />
 以上代码输出的结果如下：</p>
<pre class="prettyprint">0 [main] DEBUG comvaannilahelloworldHelloWorld  - Sample debug message
0 [main] INFO comvaannilahelloworldHelloWorld  - Sample info message
0 [main] WARN comvaannilahelloworldHelloWorld  - Sample warn message
0 [main] ERROR comvaannilahelloworldHelloWorld  - Sample error message
0 [main] FATAL comvaannilahelloworldHelloWorld  - Sample fatal message</pre>
<p>The output contains the time elapsed from the start of the program in milliseconds, the thread name, the logger level, the class name and the log message.<br />
输出的信息包含程序执行所使用的毫秒，线程名，日志级别，类名和日志信息。</p>
<p>You can download the log4j configuration file here.<br />
你可以下载这个例子<br />
Source :<a href="http://www.vaannila.com/examples/log4j/src/Log4jExample1.zip">Download </a><br />
Source + Lib :<a href="http://www.vaannila.com/examples/log4j/example/Log4jExample1.zip">Download</a></p>
<p>该文章翻译自：http://www.vaannila.com/log4j/log4j-configuration.html</p>
<h3  class="related_post_title">相关日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/log4j-configuration-using-properties-file.html" title="使用Properties文件来对Log4j进行配置">使用Properties文件来对Log4j进行配置</a><br /><small>Log4j will be usually configured using a properties file or xml file externally. So once the log statements are in place you can easily control them using the external configuration file without modif...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/simple-log4j-configuration.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate3错误:could not initialize proxy &#8211; no Session的解决办法</title>
		<link>http://www.mrzeng.com/post/hibernate3-could-not-initialize-proxy-no-session.html</link>
		<comments>http://www.mrzeng.com/post/hibernate3-could-not-initialize-proxy-no-session.html#comments</comments>
		<pubDate>Mon, 08 Feb 2010 05:47:21 +0000</pubDate>
		<dc:creator>zenghuashui</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Hibernate3]]></category>

		<guid isPermaLink="false">http://www.mrzeng.com/?p=188</guid>
		<description><![CDATA[前段时间在项目中出现以下错误： org.hibernate.LazyInitializationException: could not initialize proxy - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111) 网上查了很多文章，说是因为hibernate的延迟加载问题。解决方法是： &#60;many -to-one&#62; 和 &#60;set&#62; 中设置 lazy="false" &#60;/set&#62;&#60;/many&#62; 但操作中发现，这样会导致性能的大幅度下降，由于项目的关联的表格比较多，造成没刷新一次要执行非常多的SQL语句。 由于项目采用的ssh框架，因此使用spring的OpenSessionInViewFilter过滤器，重新测试下，性能提升很多。如果采用ssh，出现以上问题，可以加上这个过滤器。 &#60;filter&#62; &#60;/filter&#62;&#60;filter -name&#62;openSessionInViewFilter&#60;/filter&#62; &#60;filter -class&#62;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&#60;/filter&#62; &#60;filter -mapping&#62; &#60;/filter&#62;&#60;filter -name&#62;openSessionInViewFilter&#60;/filter&#62; &#60;url -pattern&#62;/*&#60;/url&#62; 随机日志jqGrid基础学习：5jqGrid中事件的使用jqGrid中提供了丰富的事件。主要如下，这些只要看看就好。部分用不到，部分要到再详解。 Event Parameters Description afterInsertRow rowid rowdata rowelem This event fires after every inserted row. rowid is the id of the [...]]]></description>
			<content:encoded><![CDATA[<p>前段时间在项目中出现以下错误：</p>
<pre class=prettyprint>
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111)
</pre>
<p><span id="more-188"></span><br />
网上查了很多文章，说是因为hibernate的延迟加载问题。解决方法是：</p>
<pre class=prettyprint>
&lt;many -to-one&gt;   和 &lt;set&gt; 中设置 lazy="false"
&lt;/set&gt;&lt;/many&gt;</pre>
<p>但操作中发现，这样会导致性能的大幅度下降，由于项目的关联的表格比较多，造成没刷新一次要执行非常多的SQL语句。</p>
<p>由于项目采用的ssh框架，因此使用spring的OpenSessionInViewFilter过滤器，重新测试下，性能提升很多。如果采用ssh，出现以上问题，可以加上这个过滤器。</p>
<pre class=prettyprint>
	&lt;filter&gt;
	&lt;/filter&gt;&lt;filter -name&gt;openSessionInViewFilter&lt;/filter&gt;
		&lt;filter -class&gt;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&lt;/filter&gt;	

	&lt;filter -mapping&gt;
		&lt;/filter&gt;&lt;filter -name&gt;openSessionInViewFilter&lt;/filter&gt;
		&lt;url -pattern&gt;/*&lt;/url&gt;
</pre>
<h3  class="related_post_title">随机日志</h3><ul class="related_post"><li><a href="http://www.mrzeng.com/post/java-zip-download.html" title="在java项目中使用Zip打包实现文件下载">在java项目中使用Zip打包实现文件下载</a><br /><small>zip压缩下载不仅可以减少网络传输，而且可以实现批量的文件下载。最近在项目中用到，写了个工具类，如下


/*
 * @{#} ZipUtils.java Create on Jan 18, 2010 2:45:47 PM
 * Copyright (c) 2009 by Huashui.
 */
package com.peaksport.export.zip;

import...</small></li><li><a href="http://www.mrzeng.com/post/jqgrid-base-study-3.html" title="jqGrid基础学习：3jqGrid与后台的交互（基于struts2）">jqGrid基础学习：3jqGrid与后台的交互（基于struts2）</a><br /><small>jqGrid与后台的交互方式如下：
载入时，jqGrid以POST或GET方式（用定义）向服务器发起数据载入请求，服务器根据请求传递给jqGrid；
传递的参数如下：
page ：指示需要查询第几页的数据。
rows ：指示每页显示的记录条数。
sidx ：指示查询排序的条件，这是一个字符串，可能是数据库表字段或者是POJO对象的属性名。这需要程序来处理。
sord ：指示查询排序的方...</small></li><li><a href="http://www.mrzeng.com/post/centos-vsftpd.html" title="Centos的vsftp搭建方法">Centos的vsftp搭建方法</a><br /><small>公司要架一台新的图片服务器，对比了centos下的几款ftp，最后还是继续选择vsftp。
搭建的方法如下：
一、下载安装
   1、安装Vsftpd

yum -y install vsftpd*
  
   2、安装PAM

yum -y install pam*
   
   3、安装db4
 
yum -y install db4*
 


二、配置vsf...</small></li><li><a href="http://www.mrzeng.com/post/phprpc-java-php.html" title="使用PHPRpc实现Java和PHP通信">使用PHPRpc实现Java和PHP通信</a><br /><small>PHPRPC是一款不错的是轻型的、安全的、跨网际的、跨语言的、跨平台的、跨环境的、跨域的、支持复杂对象传输的、支持引用参数传递的、支持内容输出重定向的、支持分级错误处理的、支持会话的、面向服务的高性能远程过程调用协议。官方网址为http://www.phprpc.org/zh_CN/

本文以Java作为服务器端，PHP作为客户端来作为演示。

1、先书写Java服务器端，书写一个接口。如...</small></li><li><a href="http://www.mrzeng.com/post/jqgrid_base_study_8-2.html" title="jqGrid基础学习：8jqGrid中在导航条使用按钮">jqGrid基础学习：8jqGrid中在导航条使用按钮</a><br /><small>jqGrid中可以再导航条上设置按钮，其中jqGrid已经默认设置了一些按钮，此外，用户也可以自定义自己的按钮。

使用默认的方法
系统中默认的按钮主要是对数据进行CRUD的操作的按钮。方法如下

jQuery("#list").jqGrid('navGrid','#pager',{edit:true,add:true,del:true,view:true},{
//这里可以指定edi...</small></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.mrzeng.com/post/hibernate3-could-not-initialize-proxy-no-session.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

