自定义简易Struts框架
学习尚学堂的老师的课程整理的
需要导入的包,用来解析xml配置文件
- dom4j-1.6.1.jar
com.filter
CoreFilter.java 过滤器用来过滤请求,并处理
package com.filter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;
import com.core.Action;
import com.core.ActionMapper;
import com.core.Result;
/**
* 过滤器实现请求的映射
*
* @author YH
*
*/
public class CoreFilter implements Filter {
public void destroy() {
}
public void init(FilterConfig arg0) throws ServletException {
try {
// 程序启动后解析配置文件
ActionMapper.parser();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doFilter(ServletRequest rq, ServletResponse rp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) rq;
HttpServletResponse resp = (HttpServletResponse) rp;
// 将请求映射到action上
Action targetAction = reqToAction(req);
if (targetAction == null) {
chain.doFilter(rq, rp);
}
// 创建action对象
try {
Object proxyAction = createProxyAction(targetAction.getClasses());
// 将用户提交的数据设置到action的属性上
setProperty(req, proxyAction);
// 执行action的方法
String result = execute(proxyAction, targetAction.getMethod());
// 处理action产生的结果
// 获取结果对象
Result r = targetAction.getResultMap().get(result);
resultExecute(req, resp, r, proxyAction);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 映射请求到action
*
* @param req
* @return
*/
private Action reqToAction(HttpServletRequest req) {
// 获得请求
String path = req.getRequestURI();
// 只处理.action结尾的请求
if (!path.endsWith(".action")) {
return null;
}
// 获得请求的名称
String reqName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
return ActionMapper.actionMap.get(reqName);
}
/**
* 创建action对象
*
* @param className
* @return
* @throws Exception
*/
private Object createProxyAction(String className) throws Exception {
Class clzz = Class.forName(className);
return clzz.newInstance();
}
/**
* 将用户提交的数据设置到action的属性上,简化了很多
*
* @param req
* @param obj
* @param className
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
private void setProperty(HttpServletRequest req, Object obj)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// 创建Class
Class clzz = obj.getClass();
Map map = req.getParameterMap();
for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
Object key = iter.next();
// 根据提交的参数查找Field
Field field = clzz.getDeclaredField(key.toString());
if (field == null) {
continue;
}
field.setAccessible(true);
// 要进行相应的类型转换---这个地方省略
field.set(obj, req.getParameter(key.toString()));
field.setAccessible(false);
}
}
/**
* 执行action方法
*
* @param proxyAction
* @param method
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
private String execute(Object proxyAction, String method) throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class clzz = proxyAction.getClass();
// 获得方法对象
Method m = clzz.getDeclaredMethod(method);
// 执行方法
return (String) m.invoke(proxyAction);
}
/**
* 处理结果
*
* @param req
* @param resp
* @param r
* @param proxyAction
* @throws IOException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws ServletException
*/
private void resultExecute(HttpServletRequest req, HttpServletResponse resp, Result r, Object proxyAction)
throws IOException, IllegalArgumentException, IllegalAccessException, ServletException {
// 判断结果类型
if ("redirect".equals(r.getType())) {
resp.sendRedirect(r.getLocation());
return;
}
// 将action的属性值设置到request的attribute中
Class clzz = proxyAction.getClass();
// 取出属性
Field[] fds = clzz.getDeclaredFields();
for (Field fd : fds) {
fd.setAccessible(true);
req.setAttribute(fd.getName(), fd.get(proxyAction));
fd.setAccessible(false);
}
req.getRequestDispatcher(r.getLocation()).forward(req, resp);
}
}
com.core
Action.java Action对象
package com.core;
import java.util.HashMap;
import java.util.Map;
/**
* Action类
* @author YH
*
*/
public class Action {
private String name;
private String classes;
private String method="execute";
private Map<String,Result> resultMap=new HashMap<String,Result>();
public Action() {
super();
}
public Action(String name, String classes, String method) {
super();
this.name = name;
this.classes = classes;
this.method = method;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, Result> getResultMap() {
return resultMap;
}
public void setResultMap(Map<String, Result> resultMap) {
this.resultMap = resultMap;
}
}
ActionMapper.java 解析配置文件
package com.core;
import java.io.InputStream;
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;
/**
* 解析配置文件
* @author YH
*
*/
public class ActionMapper {
public static Map<String,Action> actionMap=new HashMap<String,Action>();
/**
* 解析配置文件
* 配置文件名不写,解析固定的配置文件
* @throws DocumentException
*/
public static void parser() throws DocumentException{
//输入流
InputStream is=ActionMapper.class.getClassLoader().getResourceAsStream("framework.xml");
//加载文件
Document document=new SAXReader().read(is);
//读取根节点
Element root=document.getRootElement();
//处理action节点
List<Element> actions=root.elements();
for(Element element:actions){
Action action=new Action();
//获取action的属性
action.setName(element.attributeValue("name"));
action.setClasses(element.attributeValue("class"));
String method=element.attributeValue("method");
//不为空的时候设置
if(method!=null){
action.setMethod(method);
}
//处理Action中的结果集
List<Element> results=element.elements();
for(Element e:results){
Result result=new Result();
String resultName=e.attributeValue("name");
String resultType=e.attributeValue("type");
if(resultName!=null){
result.setName(resultName);
}
if(resultType!=null){
result.setType(resultType);
}
result.setLocation(e.getStringValue());
//将result对象添加到action中
action.getResultMap().put(result.getName(), result);
}
//将Action当放入actionMap中
actionMap.put(action.getName(), action);
}
}
}
Result.java 结果集
package com.core;
/**
* 结果集
* @author YH
*
*/
public class Result {
private String name="success";
private String type="dispatcher";
private String location;
public Result(String location) {
super();
this.location = location;
}
public Result(String type, String location) {
super();
this.type = type;
this.location = location;
}
public Result() {
super();
}
public Result(String name, String type, String location) {
super();
this.name = name;
this.type = type;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
com.action
HelloAction.java
package com.action;
public class HelloAction {
private String name;
private String pwd;
public String execute(){
System.out.println(name+"---"+pwd);
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
UserAction.java
package com.action;
import java.util.ArrayList;
import java.util.List;
public class UserAction {
private String name;
private String tel;
private String email;
private List<String> list;
public String list(){
System.out.println(name+" "+tel+" "+email);
list=new ArrayList<String>();
list.add("sigyy");
list.add("hello world");
list.add("it is");
return "success";
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
配置文件 framework.xml
<?xml version="1.0" encoding="UTF-8"?>
<framework>
<action name="hello" class="com.action.HelloAction">
<result name="success" type="dispatcher">/index.jsp</result>
<result name="error" type="redirect">/index.jsp</result>
</action>
<action name="list" class="com.action.UserAction" method="list">
<result>/list.jsp</result>
</action>
</framework>