感覺這自定義框架真的懵逼…跟著過了一遍,自己又過了1遍,一共看了5次,現在貼出來供參考 - - ,還有給自己以后來看看
下面是大概的流程,做的很簡陋包包、攔截器都沒有
filter —> 解析配置文件(映射用戶請求到action) —> 將用戶提交數據設置到action —> 處理結果集1、導入struts2core包+dom4j包(用來讀取xml配置文件的)
commons-fileupload-1.3.2.jarcommons-io-2.4.jarcommons-lang3-3.4.jardom4j-1.6.1.jarfreemarker-2.3.23.jarjavassist-3.20.0-GA.jarlog4j-api-2.7.jarognl-3.1.12.jarstruts2-core-2.5.8.jar2、創(chuàng)建framework(自定義).xml配置文件
<?xml version="1.0" encoding="UTF-8" ?><framework> <action name="hello" class="com.action.HelloAction"> <result>/index.jsp</result> </action> <action name="login" class="com.action.LoginAction"> <result>/success.jsp</result> <result name="login">/login.jsp</result> </action></framework>3、創(chuàng)建com.core包(Action、Result、ActionMapper類)
1、Action.java
public class Action { //屬性聲明 PRivate String name; private String classurl; private String method="execute";//默認屬性 //這里用map來裝result結果集 private Map<String, Result> resultMap=new HashMap<String,Result>(); //構造方法 public Action() { } public Action(String name, String classurl) { super(); this.name = name; this.classurl = classurl; } public Action(String name, String classurl, String method) { super(); this.name = name; this.classurl = classurl; this.method = method; } //get、set方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassurl() { return classurl; } public void setClassurl(String classurl) { this.classurl = classurl; } 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; }}2、Result.java
public class Result {//屬性聲明 private String name="success"; private String type="dispatcher";//默認屬性 private String location; //構造方法 public Result() { } public Result(String location) { super(); this.location = location; } public Result(String type, String location) { super(); this.type = type; this.location = location; } public Result(String name, String type, String location) { this.name = name; this.type = type; this.location = location; }//get、set方法 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; }}3、ActionMapper.java(這里用dom4j讀取文件)
public class ActionMapper { //Action容器 public static Map<String, Action> actionMap=new HashMap<String,Action>(); //解析配置文件 public static void Parser() throws DocumentException{ //讀取配置文件framework.xml InputStream inputStream=ActionMapper.class.getClassLoader().getResourceAsStream("framework.xml"); Document document=new SAXReader().read(inputStream); //獲取根元素對象 Element root=document.getRootElement(); //System.out.println(root.getName()); //獲取action對象 List<Element> listaction=root.elements(); for (Element itemaction : listaction) { Action action=new Action(); //獲取action屬性 action.setName(itemaction.attributeValue("name")); action.setClassurl(itemaction.attributeValue("class")); String method=itemaction.attributeValue("method"); if (method!=null) { action.setMethod(method); } //獲取result對象 List<Element> listresult=itemaction.elements(); for (Element itemresult : listresult) { Result result=new Result(); //獲取result屬性 String nameresult=itemresult.attributeValue("name"); if (nameresult!=null) { result.setName(nameresult); } String typeresult=itemresult.attributeValue("type"); if (typeresult!=null) { result.setType(typeresult); } result.setLocation(itemresult.getStringValue()); //將result對象添加到action對象 action.getResultMap().put(result.getName(), result); } //將action對象添加到actionMap對象 actionMap.put(action.getName(), action); } }}4、創(chuàng)建com.filter包(CoreFilter類) 1、CoreFilter.java(這里是重點核心,很難捉摸T.T)
public class CoreFilter implements Filter{ @Override public void destroy() { // TODO 自動生成的方法存根 } @Override public void init(FilterConfig arg0) throws ServletException { try { // 解析配置文件放到這里(該方法只執(zhí)行一次) ActionMapper.Parser(); } catch (DocumentException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } //處理事務都在doFilter里 @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httprequst=(HttpServletRequest) request; HttpServletResponse httpresponse=(HttpServletResponse) response; //我瞎設置的轉碼,目前只能傳遞常規(guī)字符串 httprequst.setCharacterEncoding("utf-8"); httpresponse.setCharacterEncoding("utf-8");//下面把大概的5個步驟分開為單獨的方法來吃 //1、將請求映射到action Action targetAction=reqToAction(httprequst); if (targetAction==null) { //如果不是action請求就跳過 filterChain.doFilter(request, response); return ; } //System.out.println(targetAction.getName()+"---"+targetAction.getClass()); try {//2、創(chuàng)建action Object proxyAction=createProxyAction(targetAction.getClassurl());//3、將用戶提交的屬性設置到action上 setProperty(httprequst, proxyAction);//4、執(zhí)行action String resultName=execute(proxyAction,targetAction.getMethod());//5、處理result Result result=targetAction.getResultMap().get(resultName); resultExecute(httprequst,httpresponse,result,proxyAction); } catch (Exception e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } //將請求映射到action public Action reqToAction(HttpServletRequest httprequest){ //獲取URL傳遞的請求名 String path=httprequest.getRequestURI(); if (!path.endsWith(".action")) {//測試此字符串是否以指定的后綴結尾。 return null; } //System.out.println(path.toString()); String reqName=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));//截取請求名 //System.out.println(reqName); return ActionMapper.actionMap.get(reqName); } //創(chuàng)建action public Object createProxyAction(String className) throws Exception { Class clzz=Class.forName(className); return clzz.newInstance(); } //將用戶提交的屬性設置到action上 public void setProperty(HttpServletRequest httprequst,Object action) throws Exception { //創(chuàng)建class Class clzz=action.getClass(); Map parameterMap=httprequst.getParameterMap(); for (Iterator iterator = parameterMap.keySet().iterator(); iterator.hasNext();) { Object key=iterator.next(); //根據提交參數去找field Field field=clzz.getDeclaredField(key.toString());//返回此類中指定字段的對象 if (field==null) { continue; } field.setaccessible(true); field.set(action, httprequst.getParameter(key.toString())); //System.out.println(key+"-----"+httprequst.getParameter(key.toString())); } } //執(zhí)行action private String execute(Object proxyAction, String methodName) throws Exception{ Class clzz=proxyAction.getClass(); Method method=clzz.getDeclaredMethod(methodName); return (String) method.invoke(proxyAction); } //處理result private void resultExecute(HttpServletRequest httprequst, HttpServletResponse httpresponse, Result result, Object proxyAction) throws Exception { if (result.getType().equals("redirect")) { httpresponse.sendRedirect(result.getLocation()); return; } //將action的屬性值設置到httprequst的attribute中 Class clzz=proxyAction.getClass(); Field[] fields=clzz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); httprequst.setAttribute(field.getName(), field.get(proxyAction)); field.setAccessible(false); } httprequst.getRequestDispatcher(result.getLocation()).forward(httprequst, httpresponse); }}JSP頁面 1、login.jsp
<form action="login.action" method="post"> 賬號<input type="text" name="name"><br> 密碼<input type="text" name="pwd"><br> <input type="submit" value="登錄"><br> </form>2、success.jsp
<h1>name:${name}</h1> age:${pwd}測試用例LoginAction.java
public class LoginAction extends ActionSupport { private String name; private String pwd; @Override public String execute() throws Exception { if (name.equals("admin")&&pwd.equals("000")) { return SUCCESS; } return LOGIN; } 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; }}效果圖
大概就這樣子 ,stuts2告一段落了~
新聞熱點
疑難解答