自定义MVC
数据库:Oracle
表:User(id,uname,upwd)
自定义Struts框架
一、定义Action接口
import javax.servlet.http.*; public interface Action { /** * 执行方法 * @return */ String execute(HttpServletRequest request,HttpServletResponse response); }
二、根据特定功能实现Action接口(这里用User表添加用户)
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.biz.UserBiz; import com.biz.impl.UserBizImpl; import com.entity.User; import com.mystruts.Action; /** * 注册Action 完成注册功能 调用业务层 返回页面 * @author Administrator * */ public class RegAction implements Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { //获取请求内容 String uname = request.getParameter("uname"); String upwd = request.getParameter("upwd"); //创建User 对象 创建UserBizImpl对象 User user = new User(uname,upwd); UserBiz userBiz = new UserBizImpl(); if(userBiz.reg(user)){ request.getSession().setAttribute("login", user); return "success"; }else{ request.getSession().setAttribute("msg", "注册失败!"); return "input"; } } }
三、ActionFilter(负责请求的转发,将用户的请求交给相应的action进行处理)
import java.io.IOException; 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 com.action.RegAction; /** * ActionFilter 负责请求的转发 将用户的请求交给相应的Action进行处理 * @author Administrator * */ public class ActionFilter implements Filter { private FilterConfig config; private ActionMappingManager mappingManager; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { //强转对象 HttpServletRequest req = (HttpServletRequest)arg0; HttpServletResponse resp = (HttpServletResponse)arg1; //获取Action 去执行相应的功能 ActionMapping actionMapping = getActionMapping(req); Action action = ActionManager.createAction(actionMapping.getClassName()); //调用execute方法执行 String resultname = null; try{ resultname = action.execute(req, resp); }catch(Exception ex){ ex.printStackTrace(); } String result = actionMapping.getResultMap().get(resultname); //正常得到处理后的返回值 进行页面跳转 if(null==result){ return; } resp.sendRedirect(result); } @Override public void init(FilterConfig conf) throws ServletException { // TODO Auto-generated method stub this.config = conf; //获取配置文件 String[] configFiles = null; String configStr = config.getInitParameter("config"); if(null==configStr || configStr.isEmpty()){ configFiles = new String[]{"mystruts.xml"}; }else{ configFiles = configStr.split(","); } this.mappingManager = new ActionMappingManager(configFiles); } //得到请求地址 通过请求地址得到对应action 通过request得到请求信息 public ActionMapping getActionMapping(HttpServletRequest request){ //获取上URI String uri = request.getRequestURI(); //获取请求的路径 String contextPath = request.getContextPath(); //截取获得action路径 String actionPath = uri.substring(contextPath.length()); //获取action名称 String actionName = actionPath.substring(1,actionPath.lastIndexOf('.')).trim(); //获取ActionMapping ActionMapping actionMapping = null; actionMapping = mappingManager.getActionMappingName(actionName); return actionMapping; } }
四、配置xml文件,保存sction信息
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mystruts SYSTEM "mystruts.dtd"> <mystruts> <actions> <action name="reg" class="com.action.RegAction"> <result name="success">login.jsp</result> <result name="input">index.jsp</result> </action> <action name="login" class="com.action.LoginAction"> <result name="success">success.jsp</result> <result name="input">login.jsp</result> </action> </actions> </mystruts>
五、创建actionMapping对应xml中action的配置
import java.util.*; public class ActionMapping { //对应Action名称 private String name; //对应Action类 private String className; //对应result结果 result-name result-value private Map<String,String> resultMap = new HashMap<String, String>(); 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, String> getResultMap() { return resultMap; } public void setResultMap(Map<String, String> resultMap) { this.resultMap = resultMap; } }
六、创建ActionMappingManager负责读取配置信息
import java.io.InputStream; import java.util.*; import org.dom4j.*; import org.dom4j.io.SAXReader; public class ActionMappingManager { //创建保存所有action的集合 private static Map<String,ActionMapping> actionMappings = new HashMap<String, ActionMapping>(); /** * init方法加载Action配置文件 */ public void init(String configFileName){ try{ if(null==configFileName || configFileName.isEmpty()){ throw new Exception("configFileName为空!"); } //加载配置文件到输入流 InputStream is = this.getClass().getResourceAsStream("/"+configFileName); Document doc = new SAXReader().read(is); Element root = doc.getRootElement(); //找到根节点下的actions节点 Iterator<Element> actionIt = root.elements("actions").iterator(); //获取到actions Element actions = actionIt.next(); //获取action Iterator<Element> iter = actions.elementIterator("action"); while(iter.hasNext()){ Element action =iter.next() ; ActionMapping mapping = new ActionMapping(); //将xml配置文件中读取的action 名称和类存入到actionMapping中 mapping.setName(action.attributeValue("name")); mapping.setClassName(action.attributeValue("class")); //将result存入到ActionMapping中 Iterator<Element> results = action.elementIterator("result"); while(results.hasNext()){ Element resultElement = results.next(); String name = resultElement.attributeValue("name"); String result = resultElement.getText(); if(name==null||"".equals(name)){ //设置默认结果 默认success name="success"; } mapping.getResultMap().put(name, result); } actionMappings.put(mapping.getName(), mapping); } }catch(Exception ex){ ex.printStackTrace(); } } /** * 加载配置文件 * @param configureFileNames */ public ActionMappingManager(String[] configureFileNames){ for (String configureFileName : configureFileNames) { init(configureFileName); } } /** * 根据action名称 获取对应的actionMapping对象 * @param actionName * @return */ public ActionMapping getActionMappingName(String actionName){ if(actionName==null || actionName.isEmpty()){ return null; } ActionMapping mapping = this.actionMappings.get(actionName); if(mapping==null){ System.out.println("Mapping为空"); } return mapping; } }
七、创建ActionManager通过反射创建对应的Action public class ActionManager { public static Action createAction(String className){ Class clazz = null; try { clazz = Class.forName(className); return (Action)(clazz).newInstance(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
八、修改web.xml和ActionFilter完成自定义Controller
<filter> <filter-name>openSessionInView</filter-name> <filter-class>com.web.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置ActionFilter过滤器 --> <filter> <filter-name>actionFilter</filter-name> <filter-class>com.mystruts.ActionFilter</filter-class> <init-param> <param-name>config</param-name> <param-value>mystruts.xml</param-value> </init-param> </filter> <filter-mapping> <filter-name>actionFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping>