Struts2框架—— MyEclipse搭建项目以及运行流程

Struts 框架

​ Struts2 框架是 Apache 发行的 MVC 开源框架,是表现层 web 框架

Struts 文件包

apps

docs

lib

src

apps:官方提供的 Demo

docs:官方提供的文档

lib:官方提供的 jar 包,需要用到哪个才导入哪个

src:源码

使用 MyEclipse2017 配置 Struts2 项目

  1. 创建 Web Project(配置 tomcat 服务器)

  2. 将 Struts2 lib 目录下的 jar 包复制到项目中

  3. 创建 struts.xml 文件在项目中 src 目录下

  4. 配置 struts 过滤器(配置 web.xml)

  5. 运行

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>lmhStruts2</display-name>
  <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>
</web-app>

(web.xml 文件配置)

配置 struts.xml 文件及 Action

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 = "p1" extends = "struts-default">
		<action name = "hello" class = "com.web.action.HelloAction" method = "sayHello">
			<result name = "success">/success.jsp</result>
		</action>
	</package>
</struts>

​ package:表示包
​ name:包名,struts.xml 文件中不能有相同的包名,包名是唯一的
​ extends:继承,默认 struts-default
​ action:动作
​ name:相当于 Servlet 的映射路径
​ class:处理请求的类,相当于 Servlet
​ method:处理请求的方法
​ result:结果,返回的 jsp 页面

Action 编写

​ 在 src 中创建包并创建 Action 类,并创建准备使用的方法

package com.web.action;

public class HelloAction {
	
	public String sayHello() {
		System.out.println("Success");
		return "success";
	}

}

​ 根据类名和方法名在 struts.xml 中配好相应的名字,配置完成后启动 tomcat 服务即可访问

Struts2 执行流程

  1. tomcat 启动服务,加载 web.xml
  2. web.xml 实例化并初始化过滤器
  3. 加载 struts.xml
  4. 客户端发送请求
  5. 请求到达过滤器
  6. 截取请求 Action 名称,在 struts.xml 中寻找 Action
  7. 找到 Action 后实例化对应的动作类
  8. 调用对应的方法,获取返回值
  9. 根据返回值,找到 name 取值对应的结果视图
  10. 找到 web 页面
  11. 响应浏览器,展示结果

Struts2 文件加载顺序

  1. default.properties //不可修改
  2. struts-default.xml //不可修改
  3. struts-plugin.xml //不可修改
  4. struts.xml //可以修改(推荐)
  5. struts.properties //可以修改
  6. web.xml //可以修改,可以给过滤器配置参数

注:如果不同的文件中对相同的属性给予不同的属性值,最终结果会以后加载的文件为准,因为后加载的文件会更新之前加载的属性配置

发布了38 篇原创文章 · 获赞 44 · 访问量 3430

猜你喜欢

转载自blog.csdn.net/scfor333/article/details/103219088