自定义MVC
数据库:Oracle
表:User(id,uname,upwd)
自定义Struts框架
希望对你们有帮助
一、定义Action接口
1 import javax.servlet.http.*; 2 3 public interface Action { 4 /** 5 * 执行方法 6 * @return 7 */ 8 String execute(HttpServletRequest request,HttpServletResponse response); 9 }
二、根据特定功能实现Action接口(这里用User表添加用户)
1 import javax.servlet.http.HttpServletRequest; 2 import javax.servlet.http.HttpServletResponse; 3 4 import com.biz.UserBiz; 5 import com.biz.impl.UserBizImpl; 6 import com.entity.User; 7 import com.mystruts.Action; 8 /** 9 * 注册Action 完成注册功能 调用业务层 返回页面 10 * @author Administrator 11 * 12 */ 13 public class RegAction implements Action { 14 15 @Override 16 public String execute(HttpServletRequest request, 17 HttpServletResponse response) { 18 //获取请求内容 19 String uname = request.getParameter("uname"); 20 String upwd = request.getParameter("upwd"); 21 //创建User 对象 创建UserBizImpl对象 22 User user = new User(uname,upwd); 23 UserBiz userBiz = new UserBizImpl(); 24 if(userBiz.reg(user)){ 25 request.getSession().setAttribute("login", user); 26 return "success"; 27 }else{ 28 request.getSession().setAttribute("msg", "注册失败!"); 29 return "input"; 30 } 31 } 32 33 }
三、ActionFilter(负责请求的转发,将用户的请求交给相应的action进行处理)
1 import java.io.IOException; 2 3 import javax.servlet.Filter; 4 import javax.servlet.FilterChain; 5 import javax.servlet.FilterConfig; 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletRequest; 8 import javax.servlet.ServletResponse; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.action.RegAction; 13 /** 14 * ActionFilter 负责请求的转发 将用户的请求交给相应的Action进行处理 15 * @author Administrator 16 * 17 */ 18 public class ActionFilter implements Filter { 19 20 private FilterConfig config; 21 private ActionMappingManager mappingManager; 22 23 @Override 24 public void destroy() { 25 // TODO Auto-generated method stub 26 27 } 28 29 @Override 30 public void doFilter(ServletRequest arg0, ServletResponse arg1, 31 FilterChain chain) throws IOException, ServletException { 32 //强转对象 33 HttpServletRequest req = (HttpServletRequest)arg0; 34 HttpServletResponse resp = (HttpServletResponse)arg1; 35 //获取Action 去执行相应的功能 36 ActionMapping actionMapping = getActionMapping(req); 37 Action action = ActionManager.createAction(actionMapping.getClassName()); 38 //调用execute方法执行 39 String resultname = null; 40 try{ 41 resultname = action.execute(req, resp); 42 }catch(Exception ex){ 43 ex.printStackTrace(); 44 } 45 String result = actionMapping.getResultMap().get(resultname); 46 47 //正常得到处理后的返回值 进行页面跳转 48 if(null==result){ 49 return; 50 } 51 resp.sendRedirect(result); 52 } 53 54 @Override 55 public void init(FilterConfig conf) throws ServletException { 56 // TODO Auto-generated method stub 57 this.config = conf; 58 //获取配置文件 59 String[] configFiles = null; 60 String configStr = config.getInitParameter("config"); 61 if(null==configStr || configStr.isEmpty()){ 62 configFiles = new String[]{"mystruts.xml"}; 63 }else{ 64 configFiles = configStr.split(","); 65 } 66 this.mappingManager = new ActionMappingManager(configFiles); 67 } 68 69 //得到请求地址 通过请求地址得到对应action 通过request得到请求信息 70 public ActionMapping getActionMapping(HttpServletRequest request){ 71 //获取上URI 72 String uri = request.getRequestURI(); 73 //获取请求的路径 74 String contextPath = request.getContextPath(); 75 //截取获得action路径 76 String actionPath = uri.substring(contextPath.length()); 77 //获取action名称 78 String actionName = actionPath.substring(1,actionPath.lastIndexOf('.')).trim(); 79 80 //获取ActionMapping 81 ActionMapping actionMapping = null; 82 actionMapping = mappingManager.getActionMappingName(actionName); 83 84 return actionMapping; 85 } 86 87 88 }
四、配置xml文件,保存sction信息
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mystruts SYSTEM "mystruts.dtd"> 3 <mystruts> 4 <actions> 5 <action name="reg" class="com.action.RegAction"> 6 <result name="success">login.jsp</result> 7 <result name="input">index.jsp</result> 8 </action> 9 <action name="login" class="com.action.LoginAction"> 10 <result name="success">success.jsp</result> 11 <result name="input">login.jsp</result> 12 </action> 13 </actions> 14 </mystruts>
五、创建actionMapping对应xml中action的配置
1 import java.util.*; 2 3 public class ActionMapping { 4 //对应Action名称 5 private String name; 6 //对应Action类 7 private String className; 8 //对应result结果 result-name result-value 9 private Map<String,String> resultMap = new HashMap<String, String>(); 10 11 public String getName() { 12 return name; 13 } 14 public void setName(String name) { 15 this.name = name; 16 } 17 public String getClassName() { 18 return className; 19 } 20 public void setClassName(String className) { 21 this.className = className; 22 } 23 public Map<String, String> getResultMap() { 24 return resultMap; 25 } 26 public void setResultMap(Map<String, String> resultMap) { 27 this.resultMap = resultMap; 28 } 29 30 }
六、创建ActionMappingManager负责读取配置信息
1 import java.io.InputStream; 2 import java.util.*; 3 4 import org.dom4j.*; 5 import org.dom4j.io.SAXReader; 6 7 public class ActionMappingManager { 8 //创建保存所有action的集合 9 private static Map<String,ActionMapping> actionMappings = new HashMap<String, ActionMapping>(); 10 11 /** 12 * init方法加载Action配置文件 13 */ 14 public void init(String configFileName){ 15 try{ 16 if(null==configFileName || configFileName.isEmpty()){ 17 throw new Exception("configFileName为空!"); 18 } 19 //加载配置文件到输入流 20 InputStream is = this.getClass().getResourceAsStream("/"+configFileName); 21 Document doc = new SAXReader().read(is); 22 Element root = doc.getRootElement(); 23 //找到根节点下的actions节点 24 Iterator<Element> actionIt = root.elements("actions").iterator(); 25 //获取到actions 26 Element actions = actionIt.next(); 27 //获取action 28 Iterator<Element> iter = actions.elementIterator("action"); 29 while(iter.hasNext()){ 30 Element action =iter.next() ; 31 ActionMapping mapping = new ActionMapping(); 32 //将xml配置文件中读取的action 名称和类存入到actionMapping中 33 mapping.setName(action.attributeValue("name")); 34 mapping.setClassName(action.attributeValue("class")); 35 //将result存入到ActionMapping中 36 Iterator<Element> results = action.elementIterator("result"); 37 while(results.hasNext()){ 38 Element resultElement = results.next(); 39 String name = resultElement.attributeValue("name"); 40 String result = resultElement.getText(); 41 if(name==null||"".equals(name)){ 42 //设置默认结果 默认success 43 name="success"; 44 } 45 mapping.getResultMap().put(name, result); 46 } 47 actionMappings.put(mapping.getName(), mapping); 48 } 49 }catch(Exception ex){ 50 ex.printStackTrace(); 51 } 52 } 53 54 /** 55 * 加载配置文件 56 * @param configureFileNames 57 */ 58 public ActionMappingManager(String[] configureFileNames){ 59 for (String configureFileName : configureFileNames) { 60 init(configureFileName); 61 } 62 } 63 /** 64 * 根据action名称 获取对应的actionMapping对象 65 * @param actionName 66 * @return 67 */ 68 public ActionMapping getActionMappingName(String actionName){ 69 if(actionName==null || actionName.isEmpty()){ 70 return null; 71 } 72 ActionMapping mapping = this.actionMappings.get(actionName); 73 if(mapping==null){ 74 System.out.println("Mapping为空"); 75 } 76 return mapping; 77 } 78 79 }
1 七、创建ActionManager通过反射创建对应的Action 2 3 public class ActionManager { 4 5 public static Action createAction(String className){ 6 Class clazz = null; 7 try { 8 clazz = Class.forName(className); 9 return (Action)(clazz).newInstance(); 10 } catch (ClassNotFoundException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } catch (InstantiationException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } catch (IllegalAccessException e) { 17 // TODO Auto-generated catch block 18 e.printStackTrace(); 19 } 20 return null; 21 } 22 23 }
八、修改web.xml和ActionFilter完成自定义Controller
1 <filter> 2 <filter-name>openSessionInView</filter-name> 3 <filter-class>com.web.OpenSessionInViewFilter</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>openSessionInView</filter-name> 7 <url-pattern>/*</url-pattern> 8 </filter-mapping> 9 <!-- 配置ActionFilter过滤器 --> 10 <filter> 11 <filter-name>actionFilter</filter-name> 12 <filter-class>com.mystruts.ActionFilter</filter-class> 13 <init-param> 14 <param-name>config</param-name> 15 <param-value>mystruts.xml</param-value> 16 </init-param> 17 </filter> 18 <filter-mapping> 19 <filter-name>actionFilter</filter-name> 20 <url-pattern>*.action</url-pattern> 21 </filter-mapping>