您的位置:首页 > 编程语言 > Java开发

struts开发笔记--配置+简单实例

2012-10-24 18:55 447 查看
1. 开发环境:

myEclipse9 + tomcat 6.0.35 + jdk1.6 + struts2.1

2.
myEclipse不支持struts2,要引入一些jar包:




1、 编程步骤

1) 安装struts。由于struts的入口点是ActionServlet,所以得在web.xml文件中配置一下servlet;

2) 编写Action类,继承ActionSupport类;

3) 在web-inf/classes/struts.xml文件中进行配置action类

4) 如果数据是用户手工录入的,一般要编写若干jsp页面,通过jsp页面中的form将数据提交给Action。

2、 编程实例

1) 在web-inf/web.xml文件中配置struts2:



2) 编写Action类:

package com.action;
import com.opensymphony.xwork2.ActionSupport;
publicclass FirstActionextends ActionSupport{
privateintop1;
privateintop2;
publicvoid setOp1(int
op1){
this.op1 = op1;
}
publicvoid setOp2(int
op2){
this.op2 = op2;
}
publicint getSum(){
returnop1+op2;
}
@Override
public String execute()throws Exception {
String result =
"";
if(getSum()>=0){
result =
"positive";
}else{
result =
"negative";
}
return result;
}
}

动作类的一个特征就是必须覆盖execute方法,struts2中的execute方法没有参数,返回一个String值,用于表述一个执行结果(标志)。

3) 在web-inf/classes/struts.xml文件中配置上面的Action类,

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstruts
PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"struts-2.1.dtd">
<struts>
<packagename="default"extends="struts-default">
<actionname="sum"class="com.action.FirstAction">
<resultname="positive">/positive.jsp</result>
<resultname="negative">/negative.jsp</result>
</action>
</package>
</struts>

注意:

a) 使用<!DOCTYPEstruts
PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"struts-2.1.dtd">时,不用联网,<packageextends="struts-default">不会有异常,但需要将myEclipse安装目录中的struts-2.1.dtd即
myEclipse9\Common\plugins\com.genuitec.eclipse.j2eedt.core_9.0.0.me201009231754\catalog-dtd\struts-2.1.dtd复制到web-inf/classes/下。

b) 如果使用<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"   “http://struts.apache.org/dtds/struts-2.1.dtd”>时,就要在联网状态下使用,否则,<package extends="struts-default">会有异常(就是一些警告…);

c) <struts>标签下可有多个<package>,在<package>中可以有多个action标签,extends属性继承一个默认的配置文件“struts-default”,<action>标签的name属性表示动作名,class表示动作类名(路径完整);

d) <result>标签的name实际上就是execute方法返回的字符串,根据字符串的值选择跳转页面;

4)
Jsp页面:sum.jsp


<%@ taglib uri="/struts-tags" prefix="s"%>
……
<body>
求代数和
<br>
<s:formname="form1"action="Sum.action">
<s:textfieldname="op1"label="操作数1"></s:textfield>
<s:textfieldname="op2"label="操作数2"></s:textfield>
<s:submitvalue="代数和"></s:submit>
</s:form>
</body>

Positive.jsp:

<%@ taglib uri="/struts-tags" prefix="s"%>
……

<body>
代数和为非负整数<h1><s:propertyvalue="sum"/></h1>
</body> negative.jsp同样的页面
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐