对于struts2现在用的是相当的多啊,,不学看来就得落伍了,记下一系列的学习笔记,供以后复习使用。
首先还是从所有程序员都认识的HelloWorld开始。
1、加入必要的开发包,这里所列的包是从struts2自带的demo中拷贝出来的。有如下的一些。

2、配置web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
3、编写进行逻辑处理的Action
Action可以是普通的POJO、还可以是继承ActionSupport的类、或是实现Action的类,对于继承或实现的方式,里面会有一些常量,方便作为返回值使用
Action.ERROR ;
Action.INPUT ;
Action.LOGIN ;
Action.NONE ;
Action.SUCCESS ;
编写一个简单的类实现ActionSupport
package com.akwolf.helloworld.action; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private static final long serialVersionUID = 1L; private String username; private String password; @Override public String execute() throws Exception { if ("akwolf".equals(username) && "123456".equals(password)) { return "success"; } return "error"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
<?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>
<!-- 包机制防止重名,action也必须放在package下 ,可以继承自一个包-->
<package name="helloworld" extends="struts-default" namespace="/">
<!-- 具体的用来请求处理逻辑的action,并指定使用哪一个action进行处理 -->
<action name="login" class="com.akwolf.helloworld.action.LoginAction">
<!-- action处理后的返回结果,根据结果进行相应的视图跳转 -->
<result name="success">/welcom.html</result>
<result name="error">/error.html</result>
</action>
</package>
</struts>
5、编写三个简单页面,进行视图层的显示。
index.jsp
<body>
<form action="login.action" method="post">
<table align="center">
<caption><h3>用户登录</h3></caption>
<tr>
<td>
用户名:<input type="text" name="username" />
</td>
</tr>
<tr>
<td>
密码:<input type="text" name="password"/>
</td>
</tr>
<tr align="center">
<td>
<input type="submit" value="登录"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</body>
welocm.html
<body> <h3>欢迎方位<a href="index.jsp">返回</a></h3> </body>
<body>
<h3>信息错误!!<a href="index.jsp">返回</a></h3>
</body>
ok,部署运行,第一个struts程序搞到!!!!
本文详细介绍了使用Struts2框架创建第一个程序的过程,包括开发包的加入、web.xml的配置、Action类的编写、struts.xml的配置以及视图层的实现。通过实践操作,深入理解Struts2的基本应用。
946

被折叠的 条评论
为什么被折叠?



