初识Struts2
一、struts2介绍
Apache Struts2 是流行和成熟的基于MVC设计模式的Web应用程序框架。它成功地结合了 WebWork和Struts1.x 两种 web 框架。使用OGNL表达式和Struts2标签来解决应用程序数据。通过Struts2可以减少使用MVC模式开发Web应用程序时间.
二、第一个struts2程序
1.下载struts2相关jar包.
地址:http://struts.apache.org/
2.struts2引入最少包,如下(若缺少会报错)
3.实现Action类
import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private Logger log = Logger.getLogger(UserAction.class); @Override public String execute() throws Exception { /* * 接收请求 * 执行业务处理 * 返回响应 */ log.debug("执行添加用户操作 >>>>>>"); return SUCCESS; } }
4.核心配置文件struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="student" namespace="/" extends="struts-default"> <action name="user" class="com.ittx.strutsproject.action.UserAction"> <result name="success">/sucess.jsp</result> </action> </package> </struts>
5.配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>strutsdemo</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
6. 执行请求
三、struts2工作原理
一个请求在Struts2框架中的处理大概分为以下几个步骤(可查看源码:https://github.com/apache/struts):
1 客户端初始化一个指向Servlet容器(例如Tomcat)的请求 2 这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框架的集成很有帮助,例如:SiteMesh Plugin) 3 接着StrutsPrepareAndExecuteFilter被调用,StrutsPrepareAndExecuteFilter询问ActionMapper来决定这个请是否需要调用某个Action 4 如果ActionMapper决定需要调用某个Action,StrutsPrepareAndExecuteFilter把请求的处理交给ActionProxy 5 ActionProxy通过Configuration Manager询问框架的配置文件struts.xml,找到需要调用的Action类 6 ActionProxy创建一个ActionInvocation的实例。 7 ActionInvocation实例使用命名模式来调用,在调用Action的过程前后,涉及到相关拦截器(Intercepter)的调用。 8 一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。返回结果通常是(但不总是,也可能是另外的一个Action链)一个需要被表示的JSP或者FreeMarker的模版。在表示的过程中可以使用Struts2 框架中继承的标签。在这个过程中需要涉及到ActionMapper
在上述过程中所有的对象(Action,Results,Interceptors,等)都是通过ObjectFactory来创建的。
转载请注明来源:初识Struts2