手写struts2框架

package struts2.config;


import java.util.List;
import java.util.Map;


/**
 * action的配置信息Manager
 * 
 * @author lenovo
 *
 */
public interface IConfigurationManager {
List getInterceptors();


String getConstant(String key);


Map getActions();

}





package struts2.config;


import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class ConfigurationManager implements IConfigurationManager {


private Element root;


public static void main(String[] args) {
}


public ConfigurationManager() {
SAXReader reader = new SAXReader();
try {
InputStream is = ConfigurationManager.class.getResourceAsStream("/struts.xml");
Document document = reader.read(is);
root = document.getRootElement();
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
}


@Override
public List getInterceptors() {
@SuppressWarnings("unchecked")
List list = root.elements("interceptor");
List interceptors = new ArrayList();
for (Element element : list)
interceptors.add(element.attributeValue("class"));
return interceptors;
}


@Override
public String getConstant(String key) {
@SuppressWarnings("unchecked")
List list = root.elements("constant");
for (Element element : list)
if (key.equals(element.attributeValue("name")))
return element.attributeValue("value");
return null;
}


@Override
public Map getActions() {
@SuppressWarnings("unchecked")
List elements = root.elements("action");
Map actions = new HashMap();
Map results = null;
for (Element actionElement : elements) {
@SuppressWarnings("unchecked")
List resultElement = actionElement.elements("result");
results = new HashMap();
ActionConfig action = new ActionConfig();
for (Element result : resultElement) {
results.put(result.attributeValue("name"), result.getText());
}
action.setName(actionElement.attributeValue("name"));
action.setClassName(actionElement.attributeValue("class"));
action.setMethod(actionElement.attributeValue("method"));
action.setResult(results);
actions.put(action.getName(), action);
}
return actions;


}
}




package struts2.config;


import java.util.Map;


/**
 * action的配置信息
 * 
 * @author lenovo
 *
 */
public class ActionConfig {
private String name;
private String className;
private String method;
private Map result;


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getClassName() {
return className;
}


public void setClassName(String className) {
this.className = className;
}


public String getMethod() {
return method;
}


public void setMethod(String method) {
this.method = method;
}


public Map getResult() {
return result;
}


public void setResult(Map result) {
this.result = result;
}
}





package struts2.context;


import java.util.Map;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import struts2.stack.IvalueStack;


/**
 * action上下文
 * 
 * @author lenovo
 *
 */
public interface IActionContext {


HttpServletRequest getRequest();


HttpServletResponse getResponse();


ServletContext getApplication();


Map getSession();


Map getParameters();


IvalueStack getValueStack();
}





package struts2.context;


import java.util.HashMap;
import java.util.Map;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import struts2.stack.ValueStack;
import struts2.utils.Constant;


public class ActionContext implements IActionContext {
private Map context;
private static ThreadLocal tl = new ThreadLocal();


private ActionContext() {
}


@SuppressWarnings("unused")
private static ActionContext actionContext = new ActionContext();


public ActionContext(Map context) {
this.context = context;
}


public static ActionContext getContext() {
return tl.get();
}


public static void releaseSrc() {
tl.remove();
}


public ActionContext(HttpServletRequest request, HttpServletResponse response, Object action) {
context = new HashMap();
context.put(Constant.REQUEST, request);
context.put(Constant.RESPONSE, response);
context.put(Constant.APPLICATION, request.getServletContext());
context.put(Constant.SESSION, request.getSession());
context.put(Constant.PARAMETER, request.getParameterMap());
ValueStack valueStack = new ValueStack();
valueStack.push(action);
request.setAttribute(Constant.VALUESTACK, valueStack);
context.put(Constant.VALUESTACK, valueStack);
tl.set(this);
}


@Override
public HttpServletRequest getRequest() {
return (HttpServletRequest) context.get(Constant.REQUEST);
}


@Override
public HttpServletResponse getResponse() {
return (HttpServletResponse) context.get(Constant.RESPONSE);
}


@Override
public ServletContext getApplication() {
return (ServletContext) context.get(Constant.APPLICATION);
}


@SuppressWarnings("unchecked")
@Override
public Map getSession() {
return (Map) context.get(Constant.SESSION);
}


@SuppressWarnings("unchecked")
@Override
public Map getParameters() {
return (Map) context.get(Constant.PARAMETER);
}


public ValueStack getValueStack() {
return (ValueStack) context.get(Constant.VALUESTACK);
}


}





package struts2.filter;


import java.io.IOException;
import java.util.List;
import java.util.Map;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import struts2.config.ActionConfig;
import struts2.config.ConfigurationManager;
import struts2.config.IConfigurationManager;
import struts2.context.ActionContext;
import struts2.invocation.ActionInvocation;
import struts2.invocation.IActionInvocation;


/**
 * 拦截http请求,并过滤掉struts.xml中定义的拦截后缀请求 Servlet Filter implementation class
 * StrutsPrepareAndExcuteFilter
 */
@WebFilter("/StrutsPrepareAndExcuteFilter")
public class StrutsPrepareAndExcuteFilter implements Filter {
private List intercepterList;
private String extension;
private Map actions;


/**
* Default constructor.
*/
public StrutsPrepareAndExcuteFilter() {
}


/**
* @see Filter#destroy()
*/
public void destroy() {
}


/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String path = req.getServletPath();
if (!path.endsWith(extension))
chain.doFilter(request, response);
else {
path = path.substring(1);
path = path.replace("." + extension, "");
ActionConfig config = actions.get(path);
if (config == null)
throw new RuntimeException();
IActionInvocation invocation = new ActionInvocation(intercepterList, config, req, res);
String result = invocation.invoke(invocation);
String dispatcherPaht = config.getResult().get(result);
if (dispatcherPaht == null || "".equals(dispatcherPaht))
throw new RuntimeException();
req.getRequestDispatcher(dispatcherPaht).forward(req, res);
ActionContext.releaseSrc();
}
}


/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
IConfigurationManager manager = new ConfigurationManager();
intercepterList = manager.getInterceptors();
extension = manager.getConstant("struts.extension");
actions = manager.getActions();
}


}





package struts2.interceptor;


import struts2.invocation.IActionInvocation;


/**
 * 定义拦截器
 * 
 * @author lenovo
 *
 */
public interface IInterceptor {
void init();


String interceptor(IActionInvocation invocation);


void destroy();
}




package struts2.interceptor;


import java.util.Map;


import struts2.context.ActionContext;
import struts2.invocation.IActionInvocation;
import struts2.utils.BeanUtils;


/**
 * 自动装配action的属性
 * 
 * @author lenovo
 *
 */
public class ParameterInterceptor implements IInterceptor {


@Override
public void init() {


}


@Override
public String interceptor(IActionInvocation invocation) {
ActionContext actionContext = invocation.getActionContext();
Object action = actionContext.getValueStack().seek();
Map map = actionContext.getParameters();
BeanUtils.populate(action, map);
return invocation.invoke(invocation);
}


@Override
public void destroy() {


}


}





package struts2.invocation;


import struts2.context.ActionContext;


/**
 * 定义invocation
 * 
 * @author lenovo
 *
 */
public interface IActionInvocation {
/*
* 1准备interceptor链 2准备action实例 3准备数据中心actionContext
*/
/*
* 返回action的result
*/
String invoke(IActionInvocation invocation);


ActionContext getActionContext();
}



package struts2.invocation;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


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


import struts2.config.ActionConfig;
import struts2.context.ActionContext;
import struts2.interceptor.IInterceptor;


public class ActionInvocation implements IActionInvocation {
private Iterator interceptors;
private ActionConfig config;
private Object action;
private ActionContext actionContext;


public ActionInvocation(List interceptorClassName, ActionConfig actionConfig, HttpServletRequest request,
HttpServletResponse response) {
// 准备interceptor链
if (interceptorClassName != null && interceptorClassName.size() > 0) {
List interceptorList = new ArrayList();
for (String className : interceptorClassName) {
try {
IInterceptor interceptor = (IInterceptor) Class.forName(className).newInstance();
interceptor.init();
interceptorList.add(interceptor);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
interceptors = interceptorList.iterator();
}
// 准备action实例
if (actionConfig != null) {
try {
this.config = actionConfig;
action = Class.forName(actionConfig.getClassName()).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (request != null && response != null)
actionContext = new ActionContext(request, response, action);
}
}


@Override
public ActionContext getActionContext() {
return this.actionContext;
}


private String result = null;


@Override
public String invoke(IActionInvocation invocation) {
// 递归调用
// 如果遍历所有的Interceptor去执行相应的操作
if (interceptors.hasNext() && result == null) {
result = interceptors.next().interceptor(invocation);
} else {
String methodName = config.getMethod();
try {
Method method = action.getClass().getMethod(methodName);
result = (String) method.invoke(action);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}




package struts2.stack;


/**
 * 定义action值栈
 * 
 * @author lenovo
 *
 */
public interface IvalueStack {
Object pop();


void push(Object obj);


Object seek();
}





package struts2.stack;


import java.util.ArrayList;
import java.util.List;


public class ValueStack implements IvalueStack {
private List values = new ArrayList();


@Override
public Object pop() {
return values.remove(0);
}


@Override
public void push(Object obj) {
values.add(0, obj);
}


@Override
public Object seek() {
return values.get(0);
}


}



package struts2.utils;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;


public class BeanUtils {
public static void populate(Object obj, Map map) {
Set keys = map.keySet();
Field field;
Method method;
for (String key : keys) {
try {
field = obj.getClass().getDeclaredField(key);
String methodName = "set" + key.substring(0, 1).toUpperCase() + key.substring(1);
method = obj.getClass().getMethod(methodName, field.getType());
String[] value = map.get(key);
method.invoke(obj, field.getType() == String.class ? value[0] : value);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}
}




package struts2.utils;


public class Constant {
public static final String REQUEST = "request";
public static final String RESPONSE = "response";
public static final String APPLICATION = "application";
public static final String SESSION = "SESSION";
public static final String PARAMETER = "parameter";
public static final String VALUESTACK = "valuestack";



}









/Succeed.jsp
2_1





package action;


public class TestAction {


private String name;
private String password;


public String test() {
System.out.println(name);
System.out.println(password);
return "right";
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getPassword() {
return password;
}


public void setPassword(String password) {
this.password = password;
}
}


你可能感兴趣的:(手写struts2框架)