Struts2 入门到精通 (一)

本文探讨了使用Struts2框架的原因,并列举了Servlet的一些不足之处。通过对比,突出了Struts2在解决多实例线程安全问题上的优势。同时,文章还提供了模拟Struts2工作原理的基本代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、为什么要使用 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 页面

转载于:https://www.cnblogs.com/julysun/p/8110590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值