转载请注明 http://blog.sina.com.cn/programbus
今天开始学习struts2.0
结果一开始连续配置出的错误给我迎头痛击,调了一下午好歹调出来了,分享下
开发环境:myeclipse7.0+tomcat6.0
struts下载: http://struts.apache.org 下完全的
struts版本: 2.1.6
以下以一个登陆页面为例
1.导入jar文件
首先是5个基本jar【必须导入】
commons-logging-1.0.4
freemarker-2.3.13
ognl-2.6.11
struts2-core-2.1.6
xwork-2.1.2
其次下面那个jar如果不导入可能报错【因为这个我检查了N遍配置文件,试过各种方法 ORZ】
commons-fileupload-1.2.1
错误信息
type Status report
message
description The requested resource () is not available.
2.配置web.xml【在其中加入filter】
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.登陆页面,注意action="login.action"
login为接下要配置struts.xml中要用到 username,password在相应的action要用到
给出body,注意页面编码gb2312/gbk
<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 align="center">
<input type="submit" value="登录"/>
<input type="reset" value="重填"/>
</td>
</tr>
</table>
</form>
</body>
4.对应action 注意路径com.test.action.LoginAction
package com.test.action;
public class LoginAction {
//客户端直接调用set而非通过strut1.x的form
private String username;
private String password;
//表单提交自动查询set方法
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public String execute() throws Exception{
return "success";
}
}
5.src目录下建立 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="struts2" extends="struts-default">
<action name="login" class="com.test.action.LoginAction">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
6.结果显示result.jsp
<body>
userName:${requestScope.username }<br>
password:${requestScope.password}
</body>
发布工程,测试登陆
基本流程
jsp页面提交-根据struts找到对应的action-实例化action调用表单属性对应的set方法-执行execute方法
根据返回String判断转发路径