• struts2框架学习笔记1:搭建测试


    Servlet是线程不安全的,Struts1是基于Servlet的框架

    而Struts2是基于Filter的框架,解决了线程安全问题

    因此Struts1和Struts2基本没有关系,只是创造者取名问题

    接下来搭建并测试

    下载Struts2:https://struts.apache.org/

    解压后目录如下:

    apps中的是示例、docs是文档、lib是类库、src是源码

    导包不需要导入lib中全部的包,导入这些即可

    简单写一个Action类:

    package hello;
    
    public class HelloAction {
        
        public String hello(){
            System.out.println("hello world!");
            return "success";
        }
        
    }

    导入dtd约束,这里可以省略,只是在编写配置文件的时候没有提示,全凭手打易出错

    配置文件:struts.xml(为什么这样写先不做说明,这里只是搭建测试)

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    <struts>
        <package name="hello" namespace="/hello" extends="struts-default" >
            <action name="HelloAction" class="hello.HelloAction" method="hello" >
                <result name="success">/hello.jsp</result>
            </action>
        </package>
    </struts>

    下一步至关重要,配置web.xml:

    由于Struts2是基于Filter的框架,所以必须配置web.xml:

      <!-- struts2核心过滤器 -->
      <filter>
          <filter-name>struts2</filter-name>
          <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>struts2</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>

    一个jsp文件hello.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>
    <h1>hello world!</h1>
    </body>
    </html>

    到这里框架搭建完成!

    部署到Tomcat服务器,本地测试:

    并且在控制台打印hello world!

    测试成功!!

    流程分析:

    1.浏览器中访问....../hello/HelloAction

    2.请求交到web.xml的Struts2过滤器,匹配hello和HelloAction

    3.过滤器去寻找核心配置文件,/hello匹配namespace属性成功,于是寻找HelloAction类

    4.找到HelloAction类,创建出Action对象,调用类的hello方法,打印hello world,返回"success"

    5.返回值找到result标签的name属性,匹配成功,转发到hello.jsp

    6.最终前端页面显示如图

  • 相关阅读:
    idea2020 安装
    739. 每日温度
    图像翻转
    257. 二叉树的所有路径
    1466. 重新规划路线
    面试题 04.05. 合法二叉搜索树
    671. 二叉树中第二小的节点
    965. 单值二叉树
    648. 单词替换
    137. 只出现一次的数字 II
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8455878.html
Copyright © 2020-2023  润新知