最近学习框架动手自己实现的一个防Structs的小Demo
希望对刚接触框架的新手有帮助,这可是花了好久整理的- -。由于本人较懒,只发个博客的链接:http://blog.csdn.net/chengyunyi123/article/details/54137798
前言:
MVC模式回顾:Model(模型) View(视图) Controller(控制器)
框架无非目的是为了简化代码,快捷开发,万变不离其宗。Structs就是对其中的Controller层进行优化,在JavaWeb中也就是Servlet。
现在回想下之前不用框架之前的麻烦点:
1. 跳转代码写死,不灵活;
2. 每次都去写Servlet,然后web.xml中配置Servlet。(配置目的: 请求, Servlet处理类)于是想到能不能进行优化呢,如果有几十个甚至上百个Servlet那web.xml是不是会非常臃肿呢?现在先自己动手实现优化,实现第一个自己的MyStruct。
需求:
一个简单的登录注册
- 设计User实体类、DAO与Service
ppackage entity; /** * 实体类 User * Created by Administrator on 2017/1/6. */ public class User { private String name; private String pwd; public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } } package dao; import entity.User; /** * Created by Administrator on 2017/1/6. */ public class UserDao { //模拟登陆 public User login(User user){ if("admin".equals(user.getName()) && "admin".equals(user.getPwd())){ return user; } return null; } //模拟注册 public void regist(User user){ System.out.println("注册成功,欢迎您 " + user.getName()); } } package service; import dao.UserDao; import entity.User; /** * Created by Administrator on 2017/1/6. */ public class UserService { private UserDao dao = new UserDao(); // 模拟登陆 public User login(User user){ return dao.login(user); } // 模拟注册 public void regist(User user) { dao.regist(user); } }
- 核心,模拟Structs中的设计,自己写一个ActionServlet,来管理项目中所有的Servlet,首先在src目录下新建一个mystructs.xml文件,配置项目中的Servlet。先设计配置文件:
<?xml version="1.0" encoding="UTF-8"?> <mystruts> <package> <!-- 配置请求路径,与处理action类的关系 --> <!-- 1. 请求路径与处理Action的关系 /login = LoginAction login success = /index.jsp 登陆成功(重定向) loginFaild = /login.jsp 登陆失败 --> <action name="login" class="framework.action.LoginAction" method="login"> <result name="loginSuccess" type="redirect">/index.jsp</result> <result name="loginFaild">/login.jsp</result> </action> <action name="register" class="framework.action.RegistAction" method="register"> <result name="registerSuccess">/login</result> </action> </package> </mystruts>
然后写两个Action类
package framework.action; import entity.User; import service.UserService; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Action表示动作类 * 1. 一个servlet对应一个action 2. action中负责处理具体的请求 * Created by Administrator on 2017/1/6. */ public class LoginAction { public Object execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return null; } /** * 处理登陆请求 */ public Object login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; //1.获取请求数据,封装 String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); User user = new User(); user.setName(name); user.setPwd(pwd); //2.调用Service UserService userService = new UserService(); User userInfo = userService.login(user); //3.跳转 if(userInfo == null){ //登陆失败 uri = "loginFailed"; }else { //登陆成功 request.getSession().setAttribute("userInfo",userInfo); uri = "loginSuccess"; } return uri; } } package framework.action; import entity.User; import service.UserService; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * RegistAction * Created by Administrator on 2017/1/6. */ public class RegistAction { public Object regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; //1.获取请求数据,封装 String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); User user = new User(); user.setName(name); user.setPwd(pwd); //2.调用Service UserService userService = new UserService(); userService.regist(user); //3.跳转 uri = "registSuccess"; return uri; } }
接着写一个ActionMapping来封装配置文件中的action节点
package framework.bean; import java.util.Map; /** * 封装action节点 * Created by Administrator on 2017/1/6. */ public class ActionMapping { //请求路径名称 private String name; //处理action类的全名 private String className; //处理方法 private String method; //结果视图集合 private Map<String,Result> results; 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 String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Map<String, Result> getResults() { return results; } public void setResults(Map<String, Result> results) { this.results = results; } }
还有一个封装结果视图的Result
package framework.bean; /** * 封装结果视图 * <result name="success" type="redirect">/index.jsp</result> * Created by Administrator on 2017/1/6. */ public class Result { // 跳转的结果标记 private String name; // 跳转类型,默认为转发; "redirect"为重定向 private String type; // 跳转的页面 private String page; 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 getPage() { return page; } public void setPage(String page) { this.page = page; } }
再写一个ActionMappingManager类:
package framework.bean; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 加载配置文件, 封装所有的整个 mystruts.xml * Created by Administrator on 2017/1/6. */ public class ActionMappingManager { //保存action的集合 private Map<String, ActionMapping> allActions; public ActionMappingManager() { allActions = new HashMap<String, ActionMapping>(); this.init(); } public ActionMapping getActionMapping(String actionName){ if (actionName == null) { throw new RuntimeException("传入参数有误,请查看struts.xml配置的路径。"); } ActionMapping actionMapping = allActions.get(actionName); if (actionMapping == null) { throw new RuntimeException("该路径在struts.xml中找不到,请检查"); } return actionMapping; } //初始化allCollection集合 private void init() { //DOM4J读取配置文件 try { //1.得到解析器 SAXReader reader = new SAXReader(); //得到mystruct.xml文件流 InputStream in = this.getClass().getResourceAsStream("/mystructs.xml"); //2.加载文件 Document doc = reader.read(in); //3,获取根节点 Element root = doc.getRootElement(); //4.得到packet节点 Element ele_package = root.element("package"); //5.得到根结点下所有的action节点 List<Element> listAction = ele_package.elements("action"); //6.遍历,封装 for (Element e : listAction) { // 6.1 封装一个ActionMapping对象 ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(e.attributeValue("name")); actionMapping.setClassName(e.attributeValue("class")); actionMapping.setMethod(e.attributeValue("method")); // 6.2 封装当前aciton节点下所有的结果视图 Map<String,Result> results = new HashMap<String,Result>(); //得到action节点下的所有result节点 Iterator<Element> it = e.elementIterator("result"); while(it.hasNext()){ Element ele_result = it.next(); //封装对象 Result res = new Result(); res.setName(ele_result.attributeValue("name")); res.setType(ele_result.attributeValue("type")); res.setPage(ele_result.getTextTrim()); //添加到集合 results.put(res.getName(),res); } // 设置到actionMapping中 actionMapping.setResults(results); //actionMapping添加到map集合 allActions.put(actionMapping.getName(),actionMapping); } } catch (Exception e) { throw new RuntimeException("启动初始化出错",e); } } }
然后记得在web.xml中配置ActionServlet
<servlet> <servlet-name>ActionServlet</servlet-name> <servlet-class>framework.ActionServlet</servlet-class> <!-- 启动时候执行servlet初始化方法 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ActionServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
最后完成三个jsp页面,login.jsp,regist.jsp,index.jsp
//index.jsp <body> 欢迎你,${sessionScope.userInfo.name} </body> //login.jsp <body> <form action="${pageContext.request.contextPath}/login.action" name="frmLogin" method="post"> 用户名:<input type="text" name="name"><br/> 密 码:<input type="text" name="pwd"><br/> <input type="submit" value="登陆"> <br/> </form> </body> //regist.jsp <body> <form action="${pageContext.request.contextPath }/regist.action" name="frmRegister" method="post"> 用户名: <input type="text" name="name"> <br/> 密码: <input type="text" name="pwd"> <br/> <input type="submit" value="注册"> <br/> </form> </body>
第一个自己动手的Structs框架项目完成!