とても使いやすいAPI----BeanUtils

1387 ワード

大きな宿題をしているうちに、とても使いやすいAPI----BeanUtilを見つけました.そこで、自分で非常に実用的なツールを作って、requestオブジェクトをbeanオブジェクトに簡単に変換することができます.
package com.sdufe.util;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.sun.org.apache.commons.beanutils.BeanUtils;

/**
 *  formbean 
 * 
 * @author zhangbowen
 * 
 */
public class WebUtils {

	//  , T 
	public static  T request2Bean(HttpServletRequest request, Class clas) {
		try {
			T bean = clas.newInstance();
			Enumeration en = request.getParameterNames();
			while (en.hasMoreElements()) {
				String name = en.nextElement();
				String value = new String(request.getParameter(name).getBytes(
						"ISO-8859-1"), "UTF-8");
				BeanUtils.setProperty(bean, name, value);
			}
			return bean;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

私がJSPとサーブレットで設定した符号化復号フォーマットはUTF-8なので、beanオブジェクトのvalue値をコードでUTF-8に変換すると中国語になってカプセル化されます.
注記はっきり言って、Tは汎用型を採用して、1つのT型のオブジェクトを返します
後でします.classは理解してまとめた
ハイライトをまとめる
汎用的な柔軟な応用、列挙タイプを取得して遍歴する
BeanUtils.setProperty(bean, name, value);まるでプログラマーの福音O(∩∩)O
この使いやすいAPIを覚えておいてください
====================================================================================
com.sun.org.apache.commons.beanutils.BeanUtils;
====================================================================================