Java模仿Struts2模型驱动的实现

首先,我没有看过Struts2的源码,是自己写的。

我自己写的一个框架Dreamer,模仿Struts2的。看下Action配置

package com.pan.actions;

import org.dreamer.annotation.Action;
import org.dreamer.annotation.Result;
import org.dreamer.code.ModelDriven;
import org.dreamer.support.ActionSupport;

import com.deramer.vo.VUser;
import com.dreamer.action.test.ITest;

@Action(results = { @Result(path = "login", location = "/login.jsp"),@Result(path="user",location="/user.jsp") })
public class IndexAction extends ActionSupport implements ModelDriven<VUser>,ITest{

	private VUser vUser=new VUser();

	public String login() {
		actionContent.put("title", "用户登录");
		System.out.println(vUser.getUsername());
		return "login";
	}
	
	public String user(){

		return "user";
	}

	public VUser getModel() {
		// TODO Auto-generated method stub
		return vUser;
	}
}

这个类和使用Struts2的Action是差不多的。但是我没有使用Struts2的任何包。都是自己实现的

具体的实现:

这里用到了一个类,普通表单的处理:

package org.dreamer.action.dao.impl;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.management.ReflectionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dreamer.action.dao.IActionForm;
import org.dreamer.code.ModelDriven;
import org.dreamer.exception.AbnormalException;
import org.dreamer.exception.InitializeActionException;
import org.dreamer.exception.ModelDrivenException;
import org.dreamer.orm.convetor.FieldConvertor;
import org.dreamer.support.ServletActionContent;
import org.dreamer.util.InterfaceUtil;
import org.dreamer.util.MethodsUtil;
import org.dreamer.util.StringUtil;

/**
 * 普通表单处理
 * @author Pan
 *
 */
public class CommonForm implements IActionForm{

	private HttpServletRequest request;		//请求对象
	private HttpServletResponse response;	//响应对象
	private Map<String, Object> map=new HashMap<String, Object>();		//map对象
	private Object result;		//返回类型
	private String methodName;		//需要操作的方法
	private Object action;			//用户的Action
	
	public CommonForm(HttpServletRequest request,HttpServletResponse response,Object action,String methodName){
		this.request=request;
		this.response=response;
		this.action=action;
		this.methodName=methodName;
	}
	
	/**
	 * 模型驱动处理
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws ModelDrivenException 
	 */
	private void modelDriven() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ModelDrivenException{
		
		//获取Action,检测是否实现了ModelDriven接口
		Class<?> cls=this.action.getClass();
		Boolean exits=InterfaceUtil.checkInterface(cls.getInterfaces(), ModelDriven.class);
		if(exits){
			//调用方法
			Method method=cls.getMethod("getModel", null);
			if(method!=null){
				Object object=method.invoke(this.action, null);
				if(object==null){
					throw new ModelDrivenException();
				}else {
					initField(object);
				}
			}
			//initField(action);
		}
		
		
	}
	
	public Map getMap() {
		// TODO Auto-generated method stub
		return this.map;
	}
	public Object getResult() {
		// TODO Auto-generated method stub
		return result;
	}
	/**
	 * 将请求的值放入map
	 */
	private void invokeMap(){
		Iterator it=request.getParameterMap().entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry=(Map.Entry)it.next();
			String key=entry.getKey().toString();
			String value=StringUtil.getStringArray((String[])entry.getValue());
			map.put(key, value);
		}
	}
	
	/**
	 * 将相关对象设置到用户的Action中
	 * @throws AbnormalException 
	 * @throws Exception 
	 * @throws InitializeActionException 
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public void Initialization() throws NullPointerException,ReflectionException,RuntimeException, AbnormalException{
		
		

		
		//给对象设置字段参数
		initField(action);
		
		//调用Action的方法
		try{
			this.result=invokeMethod(this.action);
		}catch (NullPointerException e) {
			
			StringBuffer sb=new StringBuffer();
			sb.append(e.toString()+"\r\n");
			sb.append("Initialize the user Action in the process of abnormal happened, please check the Action method for error!\r\n");
			sb.append("Abnormal method:"+action.getClass().getName()+"."+this.methodName+"()");
			throw new AbnormalException(sb.toString());
		}
		catch (Exception e) {
		
			StringBuffer sb=new StringBuffer();
			sb.append(e.toString()+"\r\n");
			sb.append("Initialize the user Action in the process of abnormal happened, please check the Action method for error!\r\n");
			sb.append("Abnormal method:"+action.getClass().getName()+"."+this.methodName+"()");
			sb.append(e.getMessage());
			throw new AbnormalException(sb.toString());
			
		}

		
	}

	/**
	 * 初始化字段
	 */
	private void initField(Object object){
		
		//获取字段集合
		Field[] fields=object.getClass().getDeclaredFields();
		
		//获取方法集合
		Method [] methods=object.getClass().getDeclaredMethods();
		
		for (Field field : fields) {
				//给指定赋值
				String MethodName="set"+StringUtil.capitalize(field.getName());
				if(MethodsUtil.exist(methods,MethodName)){

					field.setAccessible(true);
					Object value=map.get(field.getName());
					if(value!=null){
						FieldConvertor.convertor(object, field, value.toString());
					}
	
				}
			}
		}
		
	/**
	 * 调用方法
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	private Object invokeMethod(Object object) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		
		//创建ServletActionContent实例对象
				ServletActionContent servlet=new ServletActionContent();
				servlet.setRequest(request);
				servlet.setResponse(response);
				servlet.setSession(request.getSession());
				
				//创建参数类型
				Class parameter[]=new Class[]{ServletActionContent.class};
				Method method=object.getClass().getMethod("setServletActionContent", parameter);
				
				//参数值
				Object obj[]=new Object[]{servlet};
				method.invoke(object, obj);	//操作方法
				//调用execute 方法
				//Method execute=class1.getMethod("execute", new Class[0]);
				Method execute=object.getClass().getMethod(this.methodName, new Class[0]);
				Object type= execute.invoke(object, new Class[0]);

				return type;	//设置返回类型
		
	}

	public Object getAction() {
		// TODO Auto-generated method stub
		return this.action;
	}

	public void handle() throws NullPointerException, ReflectionException, RuntimeException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, ModelDrivenException, AbnormalException {
		// TODO Auto-generated method stub
		invokeMap();
		modelDriven();
		
		Initialization();
		
	}
		
	

}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值