struts框架入门的第一小程序
专门提供给新入门者写第一struts程序:
- java代码
/**
* struts第一个程序hello world
* 1.选择发布方式G:\higher
* class\Struts\apache-tomcat8.0.36\conf\Catalina\localhost
* 2.右键项目properties在tomcat中配置生成xml文件
* 3.修改struts_hw/build/classes为struts_hw/WebContent/WEB-INF/classes
* 4.从struts给的例子中给定的例子导入struts.xml和log4j2.xml到src根目录下 5.从给定的例子中导入所有lib目录下的jar包
* 6.在web.xml中配置过滤器,程序的入口(有两种配置Servlet或者过滤器,但是struts支持过滤器) 7.写好程序后注意配置好struts文件
* 注意规范: package:name与namespace名称相同,extend="struts_default"
* action:name和method名称相同,class类的包名+类名 result:name和action中name相同,中间写服务器要跳转的jsp页面
* (规范,非强制要求)
*
* /struts_hw/WebContent/WEB-INF/lib/struts2-rest-plugin-2.5.2.jar注意这个jar包不删掉,会默认找index方法,这里把它删掉,可以执行自己自定义的方法
*
* @author Administrator
* */
public class HwAction
{
public String hwAction()
{
return "hwAction";
}
}
- struts.xml配置
<struts>
<package name="head" extends="struts-default" namespace="/head" strict-method-invocation="false">
<action name="hwAction" class="com.yzt.hw.HwAction" method="hwAction" >
<result name="hwAction">/hwAction.jsp</result>
</action>
</package>
</struts>
注意事项:尽量按照java代码中的规范来写
- web.xml中的过滤器配置
<!-- START SNIPPET: filter 程序的入口 -->
<filter>
<filter-name>action2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- END SNIPPET: filter -->
<filter-mapping>
<filter-name>action2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这个过滤器参考G:\higher class\Struts\10-8\struts-2.5.2-all\struts-2.5.2\apps对应目录下的例子参照来写,有可能struts更新后有所改动
- jsp页面body中的代码
<body>
<table border="1" width="60%" cellpadding="5" cellspacing="0" bgcolor="lightblue" bordercolor="white">
<tr>
<td>操作</td>
<td>连接</td>
</tr>
<tr>
<td>hwAction</td>
<td><a href="${pageContext.request.contextPath }/head/hwAction">hwAction</a></td>
</tr>
</table>
</body>
- 根据action中result使服务器跳转jsp页面
<body>
欢迎来到第一个struts程序,hello world
</body>
- 结果图