1 What is struts?
Struts2 是一个非常优秀的MVC框架,基于Model2设计模型
2、封装请求参数到JavaBean
3、有效数据校验
4、根据业务层处理结果生成响应页面
5、页面显示信息国际化
2 分析Struts2 运行原理
1、客户端发起请求 ${pageContext.request.contextPath }/hello.action
2、根据web.xml 配置 执行 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
3、Filter会调用框架配置 interceptor 拦截器 (效果相当于 过滤器) ------ 框架内部
4、拦截器执行后,请求才会调用相应Action 进行处理 ,执行execute方法 <action name="hello" class="cn.itcast.struts2.HelloAction">
5、Action返回String 对应struts.xml 相应结果集 <result name="success">/demo1/success.jsp</result>
6、跳转到 配置目标资源文件 /demo1/success.jsp
struts2 为每个Action 提供Package 进行管理,Package中可以定义结果集result, 拦截器interceptor
<package name="basicstruts2" extends="struts-default" > extends 继承 struts-default 包 在 struts2-core-2.3.7.jar struts-default.xml
* 继承 struts-default包,默认会执行 defaultStack 栈(拦截器集合)
struts2是一个按MVC模式设计的Web层框架,其实它就是一个大大的filter,我们可以在web.xml文件中将符合某种特征的所有请求交给这个filter处理,这个filter再参照一个配置文件(通常为/WEB-INF/classes/struts.xml)将各个请求分别分配给不同的action去处理。
一个扩展知识点:struts的配置文件可以有多个,可以按模块配置各自的配置文件,这样可以防止配置文件的过度膨胀;
3 第一个Struts实例
helloworld.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=ISO-8859-1">
<title>struts实例</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/hello.action">第一个Struts实例</a>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</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>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="tutorial" extends="struts-default">
<action name="hello" class="com.cug.struts.HelloAction">
<result>/demo01/success.jsp</result>
</action>
<!-- Add your actions here -->
</package>
</struts>
<%@ 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=ISO-8859-1">
<title>success页面</title>
</head>
<body>
<h1>struts成功页面</h1>
</body>
</html>