美文网首页
struts原理

struts原理

作者: chad_it | 来源:发表于2017-01-13 15:40 被阅读57次
    struts原理

    配置文件:strust.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <strust>
      //name:访问这个资源使用的url
      //class:资源的位置
      //method:资源中的方法名
      <action name="login" class="com.javawu.action.LoginAction" method="login">
        //结果集
        //name:方法的返回值
        //对应的资源名
        <result name="success">/index.jsp</result>
        <result name="error">/error.jsp</result>
      </action>
    </strust>
    

    实体类:ActionMapping.java

    package com.javawu.action;
    import java.util.Map;
    public class ActionMapping {
        private String name;
        private String cls;
        private String method;
        private Map<String, String> result;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getCls() {
            return cls;
        }
        public void setCls(String cls) {
            this.cls = cls;
        }
        public String getMethod() {
            return method;
        }
        public void setMethod(String method) {
            this.method = method;
        }
        public Map<String, String> getResult() {
            return result;
        }
        public void setResult(Map<String, String> result) {
            this.result = result;
        }   
    }
    

    解析xml类:ActionManager.java

    package com.javawu.action;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    //解析xml文件
    public class ActionManager {
        private List<ActionMapping> list = null;
        public List<ActionMapping> getList() {
            return list;
      }
        public ActionManager() {
            list = new ArrayList<>();
            try {
              parseXML();
            } catch (Exception e) {
            // TODO Auto-generated catch block
              e.printStackTrace();
            }
        }
        private void parseXML() throws Exception {
            SAXReader saxReader = new SAXReader();
            InputStream inputStream = ActionManager.class.getResourceAsStream("/struts.xml");
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            List<Element> aEles = rootElement.elements("action");
            if(aEles != null) {
                for (Element element : aEles) {
                    ActionMapping actionMapping = new ActionMapping();
                    actionMapping.setName(element.attributeValue("name"));
                    actionMapping.setCls(element.attributeValue("class"));
                    actionMapping.setMethod(element.attributeValue("method"));
                    List<Element> rEles = element.elements("result");
                    if(rEles != null) {
                        Map<String, String> map = new HashMap<>();
                        for(Element res : rEles) {
                            map.put(res.attributeValue("name"), res.getText());
                        }
                        actionMapping.setResult(map);
                    }
                    list.add(actionMapping);
                }
            }
        }   
    }
    

    页面资源:login.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        //访问资源时使用在配置文件中配置的url
        <form action="/X01_Struts/login.action" method="post">
            user<input type="text" name="user_name" /><br/>
            password<input type="password" name="user_password" /><br/>
            <input type="submit" value="登录">
        </form>
    </body>
    </html>
    

    在web.xml中增加配置

        <servlet>
            <description></description>
            <display-name>ActionServlet</display-name>
            <servlet-name>ActionServlet</servlet-name>
            <servlet-class>com.javawu.action.ActionServlet</servlet-class>
        </servlet>
            <servlet-mapping>
            <servlet-name>ActionServlet</servlet-name>
            //访问所有以.action为结尾的资源时都会被ActionServlet.java拦截
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
    

    ActionServlet.java

    package com.javawu.action;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.sun.swing.internal.plaf.metal.resources.metal;
    /**
     * Servlet implementation class ActionServlet
     */
    public class ActionServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        /**
         * @see HttpServlet#HttpServlet()
         */
        public ActionServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
        /**
        * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            ActionManager actionManager = new ActionManager();
            List<ActionMapping> list = actionManager.getList();
            //获取请求的uri
            String uri = request.getRequestURI();
            //根据uri获取请求的资源
            uri = uri.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf(".action"));
            for(ActionMapping actionMapping : list) {
                if(actionMapping.getName().equals(uri)) {
                    try {
                        Class cls = Class.forName(actionMapping.getCls());
                        Object newInstance = cls.newInstance();
                        Method method = cls.getDeclaredMethod(actionMapping.getMethod(), HttpServletRequest.class, HttpServletResponse.class);
                        String ret = (String)method.invoke(newInstance, request, response);
                        for(String result : actionMapping.getResult().keySet()) {
                            if (result.equals(ret)) {
                                response.sendRedirect(request.getContextPath() + actionMapping.getResult().get(result));
                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
                }
            }   
        }
        /**
        * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
        */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            doGet(request, response);
        }
    }
    

    LoginAction.java

    package com.javawu.action;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class LoginAction {
        public String login(HttpServletRequest request, HttpServletResponse response) {
            if(request.getParameter("user_name").equals("admin") && request.getParameter("user_password").equals("123")) {
                return "success";
            }else {
                return "error";
            }   
        }   
    }
    

    相关文章

      网友评论

          本文标题:struts原理

          本文链接:https://www.haomeiwen.com/subject/kcdsbttx.html