1. 程式人生 > >Struts2 入門到精通 (一)

Struts2 入門到精通 (一)

多實例 @override eve 底層 text rri trac 入口 struts

一、為什麽要使用 struts2 以及 servlet 的優缺點

  Servlet 缺點

  1.寫一個 servlet 需要在 web.xml 文件裏面配置 8 行,如果 servlet 過多,則會導致 web.xml 文件裏面的內容很多。

  2.當項目分工合作,多人編輯一個 web.xml 文件的時候會出現版本沖突。

  3.在一個 Servlet 中方法的入口只有一個,諸多不便。

  4.Servlet 中的方法都有兩個參數 request、response,這兩個參數具有嚴重的容器依賴性,所以在 Servlet 中寫的代碼是不能單獨測試的。

  5.如果表單中元素很多,在 Servlet 裏面獲取表單數據的時候會出現很多 request.getParameter 代碼。

  6.在一個 Servlet 的屬性中聲明一個數據,會存在線程安全隱患。(struts2 中的 action 是多實例的,每請求一次將會創建一個對象,是不存在線程安全的。

  Servlet 優點

  1.因為是最底層的 mvc,所以效率比較高。

  

二、根據所學基礎知識模擬設計 struts2

  1.寫一個 ActionListener 監聽器

    public class ActionListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
   Map<String, String> map = new HashMap<String, String>();
   map.put("Action", "cn.july.Action");
   servletContextEvent.getServletContext().setAttribute("actions", map);
   }

   @Override
   public void contextDestroyed(ServletContextEvent servletContextEvent) {
   servletContextEvent.getServletContext().setAttribute("actions", null);
   }
   }

  2.寫一個 ActionServlet Servlet
    @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  String uri = req.getRequestURI();
  String actionName = uri.substring(1);
   System.out.println("actionName:" + actionName);
  Map<String, String> actions = (Map<String, String>)this.getServletContext().getAttribute("actions");
  System.out.println("actions:" + actions);
  String className = actions.get(actionName);
  System.out.println("className:" + className);
  try {
  Class clazz = Class.forName(className);
  Method method = clazz.getMethod("excute");
  String result = (String) method.invoke(clazz.newInstance());
  System.out.println("result:" + result);
  resp.sendRedirect("/"+ result +".jsp");
  } catch (Exception e){
  e.printStackTrace();
  }
  }
  
3.寫一個 Action 類
    public String excute(){
  return "login";
  }

  4.瀏覽器訪問 http://localhost:8080/Action 即到達 login.jsp 頁面

Struts2 入門到精通 (一)