欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java反射-在form提交的一些应用 JavaStrutsServletApacheJSP

程序员文章站 2024-03-16 00:01:07
...
 

 

说明:这个例子用在简化java的web开发之中,javaeye里面高手众多,我特地将这个例子贴出来,还希望各位朋友指导建议,互相学习学习。

实现:页面有一个form表单,提交到servlet或action后,表单的值与相应的javabean自动赋值。

 

假如,这里要对页面表单的数据进行插入数据库操作,

1、首先看javabean里面代码:

public class AccountBean {

	private int uid = -1;//用户编号-----hidden
	private String uname = "";//用户名称----text
	private String sex = "";//用户性别-----radio
	private String loves[];//用户爱好-------checkbox
     //省略get、set属性方法
}

 

2、BaseAction

package com.test;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.actions.DispatchAction;

public class BaseAction extends DispatchAction {

	private static final String TYPE_STRING = "java.lang.String";
	private static final String TYPE_INTEGER = "java.lang.Integer";
	private static final String TYPE_DOUBLE = "java.lang.Double";
	private static final String TYPE_FLOAT = "java.lang.Float";
	private static final String TYPE_BOOLEAN = "java.lang.Boolean";
	private static final String TYPE_CHARACTER = "java.lang.Character";
	private static final String TYPE_SHORT = "java.lang.Short";
	private static final String TYPE_LONG = "java.lang.Long";
	private static final String TYPE_BYTE = "java.lang.Byte";
	
	/**
	 * 将表单内所有的name属性与值封装
	 * 值的类型为基本类型、String、String[]类型,不可能为Collection或Map等集合类型
	 */
	public Map<String, Object> getFormValues(HttpServletRequest request){
		
		Map<String,Object> linkMap = null;
		Map map = request.getParameterMap();
		if(map!=null) {
			linkMap = new LinkedHashMap<String, Object>();
			Set set = map.entrySet();
			Iterator it = set.iterator();
			while(it.hasNext()) {
				Entry entry = (Entry) it.next();
				String key = entry.getKey().toString();
				String value = "";
				Object object = entry.getValue();
				if(object instanceof String[]) {
					String values[] = (String[]) entry.getValue();
					if(values.length == 1) {
						value += values[0];
					}
					if("".equals(value)){
						linkMap.put(key, values);
					}else
						linkMap.put(key, value);
				}
			}
		}
		return linkMap;
	}
	
	public void errors(String msg) {
		String temp = "操作出现异常,异常信息为:" + msg;
		try {
			throw new Exception(temp);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * 将form表单数据相应的javabean类与表单的数据封装,返回赋值后的javabean对象
	 */
	public Object getObjectByAttrs(String className,Map map) {
		
		try {
			Class clazz =Class.forName(className);
			Object obj = clazz.newInstance();
			Field fields[] = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				Class classType = field.getType();
				field.setAccessible(true);
				String key = field.getName();
				if(map.containsKey(key)) {
					Object object = setFieldType(classType,map.get(key));
					field.set(obj,object);
				}
			}
			return obj;
		} catch (ClassNotFoundException e) {
			errors("加载类出现异常");
		} catch (IllegalArgumentException e) {
			errors("向方法传递了一个不合法或不正确的参数");
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			errors("没有权限访问该成员变量");
		} catch (InstantiationException e) {
			errors("反射调用实例化类错误");
		}
		
		return null;
	}
	
	private Object setFieldType(Class classType,Object object) {
		
		String typeString = classType.getName();
		
		if(typeString.equals(TYPE_INTEGER) || classType.equals(Integer.TYPE)) {
			return Integer.parseInt(object.toString());
		}else if(typeString.equals(TYPE_STRING)) {
			return object.toString();
		}else if(typeString.equals(TYPE_LONG) || classType.equals(Long.TYPE)) {
			return Long.parseLong(object.toString());
		}else if(typeString.equals(TYPE_BOOLEAN) || classType.equals(Boolean.TYPE)) {
			return Boolean.parseBoolean(object.toString());
		}else if(typeString.equals(TYPE_BYTE) || classType.equals(Byte.TYPE)) {
			return Byte.parseByte(object.toString());
		}else if(typeString.equals(TYPE_CHARACTER) || classType.equals(Character.TYPE)) {
			return object.toString().charAt(0);
		}else if(typeString.equals(TYPE_DOUBLE) || classType.equals(Double.TYPE)) {
			return Double.parseDouble(object.toString());
		}else if(typeString.equals(TYPE_FLOAT) || classType.equals(Float.TYPE)) {
			return Float.parseFloat(object.toString());
		}else if(typeString.equals(TYPE_SHORT) || classType.equals(Short.TYPE)) {
			return Short.parseShort(object.toString());
		}else {
			if(classType.isArray()) {
				if(object instanceof String) {
					return new String[] {object.toString()};
				}
				return (String[])object;
			}
			return object;
		}
	}
	
}

 

3、调用的action类AccountAction.java

 

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AccountAction extends BaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm forms,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		request.setCharacterEncoding("UTF-8");

		Map<String, Object> maps = this.getFormValues(request);//将表单填写的数据按name和valu存储map集合中
		AccountBean account= (AccountBean) this.getObjectByAttrs(
				"com.test.AccountBean", maps);//将表单form的转换为一个javabean属性类
		
		System.out.println(account == null);//这里输出account对象的各个属性都是有值的
		return null;
	}

}

 

4、页面表单

 

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0"> 
	<style type="text/css">
		*{
			padding: 5px;
			font:small-caps 13px 微软雅黑; 
		}
	</style>
  </head>
  
  <body>
    	<form action="test.do" method="post">
    		<table border="1">
    			<tr>
    				<td>姓名:</td>
    				<td>
    					<input type="hidden" value="1001" name="uid" />
    					<input type="text" name="uname" />
    				</td>
    			</tr>
    			<tr>
    				<td>性别:</td>
    				<td>
    					<input type="radio" name="sex" value="男" checked="checked"/>男
    					<input type="radio" name="sex" value="女"/>女
    				</td>
    			</tr>
    			<tr>
    				<td>爱好:</td>
    				<td>
    					<input type="checkbox" name="loves" value="足球" />足球
    					<input type="checkbox" name="loves" value="篮球" />篮球
    					<input type="checkbox" name="loves" value="乒乓球" />乒乓球
    					<input type="checkbox" name="loves" value="垒球" />垒球
    					<input type="checkbox" name="loves" value="台球" />台球
    				</td>
    			</tr>
    			<tr>
    				<td>说明:</td>
    				<td>
    					<textarea rows="3" cols="35" name="info"></textarea>
    				</td>
    			</tr>
    			<tr>
    				<td colspan="2" align="center">
    					<input type="submit" value="提交" />
    					<input type="reset" value="重置" />
    				</td>
    			</tr>
    		</table>
    	</form>
		
  </body>
</html>

 

5、web.xml和 strut-config.xml环境的配置就不说了,需要导入strut1.2的所有的jar文件,附件内为源文件。

 

 

总结:这里重在简化页面提交和取值这里做简化,写的不怎么高明,高手指教。

  • T.rar (1.2 MB)
  • 下载次数: 24