struts入门----HelloWorld程序开发步骤
1.在MyEclipse中新建一个Web Project,命名为struts-helloworld,工程结构如下:
2.引入struts2支持,右键工程名,选中MyEclipse--ProjectFacets-Install Apache struts(2.x) Facet,
会发现在工程下面多了一个Struts2.1 Libraries,在src下面多了一个stuts.xml配置文件(MyEclipse工具提供的支持,使得struts开发比较方便,如果是使用eclipse工具,则不提供该支持,需要手动导入struts需要的jar包)
此处的URL pattern默认是*.action,意思是我们访问这个工程时默认使用xxx.action访问
此处加入struts2.1支持之后,工程结构图如下:(在框架开发过程中,配置文件和代码并重)
struts2.1加入的jar包如下:
代码都是从web.xml开始的,添加struts支持后,web.xml中自动加入struts需要的支持如下:
<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>
<!-- 当你访问以*.action结尾的路径时,会进入struts2的过滤器StrutsPrepareAndExecuteFilter,也就是会进入struts2的处理 -->
<url-pattern>*.action</url-pattern>
</filter-mapping>
3.写struts.xml配置文件
struts.xml刚开始的样子:xml格式的约束
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
</struts>
之后,进行编写struts.xml文件,进行相应的交易(页面输出:你好世界!)
<struts>
<package name="hello" namespace="/" extends="struts-default">
<action name="hello" class="com.etc.action.HelloAction">
<result name="success">/hello.jsp</result>
</action>
</package>
</struts>
4.写运行页面.java文件,在src下新建com.etc.action包,在包下新建 HelloAction.javapackage com.etc.action;--包名
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport{
--继承ActionSupport类,从而使得这个类跟struts2有关,可以使用其中的东西
//实现ActionSupport中的execute()方法
public String execute() throws Exception {
System.out.println("你好,世界!"); --在控制台输出的值
return "success"; --与result中的name一致。
//return Action.SUCCESS;--更加正规,方便。
}
}
5.在WebRoot下面新建一个页面:hello.jsp<html>
<body>
<h1 align="center">你好,世界!</h1>
</body>
</html>
运行:http://localhost:8080/struts-helloworld/hello.action,效果如下:
页面跳转到hello.jsp,输出:你好,世界!
其中
8080:端口号
struts_helloworld:工程名/项目名
/:命名空间,与package中的namespace一致,这样写更规范。
hello:文件名,与action中的name一致
.action:文件后缀名,与web.xml中的<url-pattern>*.action</url-pattern>一致 进入.action时,表示进入到struts的处理
struts_helloworld:工程名/项目名
/:命名空间,与package中的namespace一致,这样写更规范。
hello:文件名,与action中的name一致
.action:文件后缀名,与web.xml中的<url-pattern>*.action</url-pattern>一致 进入.action时,表示进入到struts的处理
struts2的工作原理:
在页面输入:http://localhost:8080/struts-helloworld/hello.action进入struts-helloworld项目,从web.xml开始分析(一个web工程首先是从web.xml开始的),web.xml中写明.action路径进入的是struts2框架,所以去查看路径,从路径中看到hello.action,表示这是一个strut请求,从而进入struts2框架,进入struts.xml(struts2框架开始的地方),找到名字叫做hello的action请求,通过配置文件,进入com.etc.action.HelloAction类,配置文件中action没有配置method属性时,默认调用execute()方法,代码打印“你好,世界!”,然后返回success,去询问struts.xml,最终展示hello.jsp页面。
(result中没有写name属性时,默认name="success",即成功时返回相应的页面)
技巧:更新.jsp页面或者.html页面时,服务器不需要重启,自动更新。
更新.java页面或者.xml配置文件时,服务器需要重启。
怎么设置不需要重启??
在struts.xml中设置常量:<constant name="struts.devMode" value="true"></constant>
怎么设置不需要重启??
在struts.xml中设置常量:<constant name="struts.devMode" value="true"></constant>