Struts 2中自定义MVC框架

配置文件

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE  mystruts[
 <!ELEMENT mystruts (actions) >
 <!ELEMENT actions  (action*)>
 <!ELEMENT action   (result*)>
 <!ATTLIST action
     name CDATA #REQUIRED
     class CDATA #REQUIRED >
 <!ELEMENT result (#PCDATA)>
 
 <!ATTLIST result
     name  CDATA #IMPLIED
     redirect (true|false) "false">
 ]>
 <!-- 上面是对xml的定义DTD -->
<mystruts>
 <actions>
  <action name="login" class="org.mvc.servlet.LoginServlet">
   <result name="input">index.jsp</result>
   <result name="success">manager.jsp</result>
  </action>
  <action name="register" class="org.mvc.servlet.RegisterServlet">
   <result name="input">register.jsp</result>
   <result name="success" redirect="true">index.jsp</result>
  </action>
 </actions>
</mystruts>

 

==============================================================================================================================

package org.mvc.framework;

import java.io.IOException;

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

/**
 *
 * 定义Action接口
 *
 */
public interface Action {
 String execute(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException;
 String SUCCESS="success";
 String FAILURE="failure";
 String INPUT="input";
}

==============================================================================================================================

 

package org.mvc.framework;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 封装配置文件中的属性
 *
 */


public class ActionMapping implements Serializable {
  private String name;
  private String className;
  private Map<String, Result> resultMapping=new HashMap<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 Map<String, Result> getResultMapping() {
   return resultMapping;
  }
  public void setResultMapping(Map<String, Result> resultMapping) {
   this.resultMapping = resultMapping;
  }
  public ActionMapping() {
   // TODO Auto-generated constructor stub
  }
}

====================================================================================================================================

package org.mvc.framework;

import java.io.Serializable;
/*
 * 封装action节点下的result
 *
 */
public class Result implements Serializable {

 private String r_name;
 private String r_value;
 //是否重定向
 private boolean isredirect;
 public String getR_name() {
  return r_name;
 }
 public void setR_name(String rName) {
  r_name = rName;
 }
 public String getR_value() {
  return r_value;
 }
 public void setR_value(String rValue) {
  r_value = rValue;
 }
 public boolean isIsredirect() {
  return isredirect;
 }
 public void setIsredirect(boolean isredirect) {
  this.isredirect = isredirect;
 }
 
 public Result() {
  // TODO Auto-generated constructor stub
 }
}

 

============================================================================================================================

package org.mvc.framework;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;

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

import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;

/**
 *
 * 关键所在 《读取配置文件中的内容》
 *
 */
public class ActionMappingManager {

 private Map<String, ActionMapping> maps = new HashMap<String, ActionMapping>();

 public ActionMappingManager(String configureFile) throws DocumentException, FileNotFoundException {
  if (null == configureFile || "".equals(configureFile)) {
   throw new RuntimeException("配置文件不能为空");
  }
  init(configureFile);

 }

 /***
  * 读取mystruts.xml配置文件,封装成一个AcctionMapping
  *
  * @param configureFile
  * @throws DocumentException
  * @throws FileNotFoundException
  */
 public void init(String configureFile) throws DocumentException, FileNotFoundException {

  InputStream is = this.getClass().getResourceAsStream("/"+configureFile);
  
  SAXReader reader = new SAXReader();
  
  Document document  = reader.read(is);
  // 获得根节点mystruts
  Element root = document.getRootElement();
  // 获得子节点actions
  Element element = root.element("actions");
  // 获得actions节点下的集合
  Iterator<Element> actionIt = element.elementIterator();
  if (actionIt != null) {
   while (actionIt.hasNext()) {
    // 获得action节点
    Element actionElement = actionIt.next();
    ActionMapping actionMapping = new ActionMapping();
    actionMapping.setName(actionElement.attributeValue("name"));
    actionMapping.setClassName(actionElement.attributeValue("class"));
    // 获得action节点下的子节点 result的集合
    Iterator<Element> resultIt = actionElement.elementIterator();
    if (resultIt != null) {
     while (resultIt.hasNext()) {
      // 得到result节点
      Element ite = (Element) resultIt.next();
      Result result=new Result();
      result.setR_name(ite.attributeValue("name"));
      result.setR_value(ite.getTextTrim());
      
      //判断是否重定向
      String isredirect=ite.attributeValue("redirect");
      if(null==isredirect|| "".equals(isredirect)){
       isredirect="false";
      }
      result.setIsredirect(Boolean.parseBoolean(isredirect));
     
      actionMapping.getResultMapping().put(result.getR_name(), result);
     }
    }

    maps.put(actionElement.attributeValue("name"), actionMapping);
   }
  }
  //----------以下方法和上面方法一样
  // List list=document.selectNodes("/mystruts/actions/action");
  // for (Object elementItem : list) {
  // if (elementItem instanceof DefaultElement) {
  // Element actionElement = (Element) elementItem;
  // ActionMapping actionMapping = new ActionMapping();
  // actionMapping.setName(actionElement.attributeValue("name"));
  // actionMapping.setClassName(actionElement.attributeValue("class"));
  // Iterator it=actionElement.elementIterator("result");
  // if(it!=null){
  // while(it.hasNext()){
  // Element ite=(Element)it.next();
  // actionMapping.getResultMapping().put(ite.attributeValue("name"),
  // ite.getTextTrim());
  // }
  // }
  // maps.put(actionElement.attributeValue("name"), actionMapping);
  // }
  //
  // }

 }

 /**
  * 根据name得到一个actionMapping
  *
  * @param name
  * @return
  */
 public ActionMapping getActionMappingByName(String name) {
  return maps.get(name);
 }

 public static void main(String[] args) throws DocumentException, FileNotFoundException {
  ActionMappingManager amm = new ActionMappingManager("mystruts.xml");
  ActionMapping map = amm.getActionMappingByName("login");
  System.out.println("name:" + map.getName());
  System.out.println("class:" + map.getClassName());
  for (String s : map.getResultMapping().keySet()) {
   System.out.println(s + ":\t" + map.getResultMapping().get(s));
  }

  System.out.println(amm.getActionMappingByName("register").getName());
 
 }
 
}

=====================================================================================================================================

 

package org.mvc.framework;

/**
 * Action的管理者
 *
 * @author Administrator createAction 方法用来获取Action示例
 *
 */
public class ActionManager {

 public static Action createAction(String className) throws InstantiationException, IllegalAccessException {
 
  return (Action)loadClass(className).newInstance();
  
 
 }

 /**
  * loadClass动态加载类 (反射机制)
  *
  * @return
  */
 private static Class loadClass(String className) {
  Class classzz = null;

  // 获得当前类的类类型
  try {
   classzz = Thread.currentThread().getContextClassLoader().loadClass(className);
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  if (classzz == null) {
   try {
    classzz = Class.forName(className);
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  return classzz;
 }

}

 

=============================================================================================================================

 

package org.mvc.framework;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;

public class ActionServlet extends HttpServlet {

 private ActionMappingManager manager=null;
 private String configureFile="mystruts.xml";
 
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
   configureFile=this.getInitParameter("configureFile")!=null?
       this.getInitParameter("configureFile")
       :configureFile; 
  try {
   manager=new ActionMappingManager(configureFile);
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }     
 }
 //根据文件页面获得相应的ActionMapping
 public ActionMapping getActionMapping(HttpServletRequest request){
  //获取请求的uri
       String uri = request.getRequestURI();
       //获取上下文路径
       String contextPath = request.getContextPath();
       //截取上下文路径以后的部分
       String actionPath = uri.substring(contextPath.length());
       //获取Action 名称
       String actionName =                
       actionPath.substring(1,actionPath.lastIndexOf('.')).trim(); 
  
   
  return manager.getActionMappingByName(actionName);
 }

 /**根据请求URI确定要构造那个Action实例
  * @throws IllegalAccessException
  * @throws InstantiationException */
 private Action getAction(ActionMapping actionMapping) throws InstantiationException, IllegalAccessException{     
      
      return ActionManager.createAction(actionMapping.getClassName());
 }
 
 
 @Override
 protected void service(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  
  ActionMapping mapping=getActionMapping(request);
  try {
   //得到Action
   Action action=getAction(mapping);
   //得到要跳转的页面
   String result=action.execute(request, response);
   
   //得到结果
   Result forwordResult=mapping.getResultMapping().get(result);
   //得到配置文件中的页面
   String forwordPager=forwordResult.getR_value();
   
   //判断转发还是重定向
   if(forwordResult.isIsredirect()){
    response.sendRedirect(forwordPager);
 
   }else{
    request.getRequestDispatcher(forwordPager).forward(request, response);
    
   }
   
   
   
  } catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
  
 }
 
}

==================================================================================================================================

package org.mvc.servlet;

import java.io.IOException;

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

import org.mvc.framework.Action;
/**
 *
 * 登录实现Action 用户登录
 *
 */
public class LoginServlet implements Action {

 @Override
 public String execute(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  String name = request.getParameter("name");
  String password = request.getParameter("password");
  if ("admin".equals(name) && "admin".equals(password)) {
   return Action.SUCCESS;
  } else {
   request.setAttribute("message", "登录失败");
   return Action.INPUT;
  }

 }

}

 

============================================================================================================================

web.xml的配置

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>org.mvc.framework.ActionServlet</servlet-class>
   <init-param>
    <param-name>configureFile</param-name>
    <param-value>mystruts.xml</param-value>
   </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

 

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值