关闭

手写struts2框架

标签: struts框架
48人阅读 评论(0) 收藏 举报
package struts2.config;


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


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


String getConstant(String key);


Map<String, ActionConfig> 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<String> getInterceptors() {
@SuppressWarnings("unchecked")
List<Element> list = root.elements("interceptor");
List<String> interceptors = new ArrayList<String>();
for (Element element : list)
interceptors.add(element.attributeValue("class"));
return interceptors;
}


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


@Override
public Map<String, ActionConfig> getActions() {
@SuppressWarnings("unchecked")
List<Element> elements = root.elements("action");
Map<String, ActionConfig> actions = new HashMap<String, ActionConfig>();
Map<String, String> results = null;
for (Element actionElement : elements) {
@SuppressWarnings("unchecked")
List<Element> resultElement = actionElement.elements("result");
results = new HashMap<String, String>();
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<String, String> 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<String, String> getResult() {
return result;
}


public void setResult(Map<String, String> 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<String, Object> getSession();


Map<String, String[]> 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<String, Object> context;
private static ThreadLocal<ActionContext> tl = new ThreadLocal<ActionContext>();


private ActionContext() {
}


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


public ActionContext(Map<String, Object> 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<String, Object>();
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<String, Object> getSession() {
return (Map<String, Object>) context.get(Constant.SESSION);
}


@SuppressWarnings("unchecked")
@Override
public Map<String, String[]> getParameters() {
return (Map<String, String[]>) 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<String> intercepterList;
private String extension;
private Map<String, ActionConfig> 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<String, String[]> 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<IInterceptor> interceptors;
private ActionConfig config;
private Object action;
private ActionContext actionContext;


public ActionInvocation(List<String> interceptorClassName, ActionConfig actionConfig, HttpServletRequest request,
HttpServletResponse response) {
// 准备interceptor链
if (interceptorClassName != null && interceptorClassName.size() > 0) {
List<IInterceptor> interceptorList = new ArrayList<IInterceptor>();
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<Object> values = new ArrayList<Object>();


@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<String, String[]> map) {
Set<String> 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";



}



<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE struts SYSTEM "struts-2.0.dtd"> -->
<struts>
<interceptor class="struts2.interceptor.ParameterInterceptor"></interceptor>
<constant name="struts.extension" value="action" />
<action name="test" class="action.TestAction" method="test">
<result name="right">/Succeed.jsp</result>
<result name="2_1">2_1</result>
</action>
</struts>




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;
}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1618次
    • 积分:323
    • 等级:
    • 排名:千里之外
    • 原创:32篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类