Struts 框架
Struts2 框架是 Apache 发行的 MVC 开源框架,是表现层 web 框架
Struts 文件包
apps
docs
lib
src
apps:官方提供的 Demo
docs:官方提供的文档
lib:官方提供的 jar 包,需要用到哪个才导入哪个
src:源码
使用 MyEclipse2017 配置 Struts2 项目
-
创建 Web Project(配置 tomcat 服务器)
-
将 Struts2 lib 目录下的 jar 包复制到项目中
-
创建 struts.xml 文件在项目中 src 目录下
-
配置 struts 过滤器(配置 web.xml)
-
运行
<?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 执行流程
- tomcat 启动服务,加载 web.xml
- web.xml 实例化并初始化过滤器
- 加载 struts.xml
- 客户端发送请求
- 请求到达过滤器
- 截取请求 Action 名称,在 struts.xml 中寻找 Action
- 找到 Action 后实例化对应的动作类
- 调用对应的方法,获取返回值
- 根据返回值,找到 name 取值对应的结果视图
- 找到 web 页面
- 响应浏览器,展示结果
Struts2 文件加载顺序
- default.properties //不可修改
- struts-default.xml //不可修改
- struts-plugin.xml //不可修改
- struts.xml //可以修改(推荐)
- struts.properties //可以修改
- web.xml //可以修改,可以给过滤器配置参数
注:如果不同的文件中对相同的属性给予不同的属性值,最终结果会以后加载的文件为准,因为后加载的文件会更新之前加载的属性配置