最近想学struts2,上网看了许多struts2的例子,怎么捣腾都捣腾不出来。原来是struts2.3.8和之前的2.1.x不一样,于是继续捣腾,终于有成果,以下是一个HelloWorld的demo
创建webproject,结构目录如下
注:所需要的包缺一不可(本人无聊还故意一个个删除然后测试,哈哈),与网上的教程相比,多了个javassist这个jar包
修改WEB-INF/lib下的web.xml
加入
<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>
注:filter-class中与之前不同
编写action类
packagecom.action;
importcom.opensymphony.xwork2.ActionSupport;
publicclassIndexAction extendsActionSupport{
privatestaticfinallongserialVersionUID= 1L;
privatestaticfinalString MESSAGE= "struct is running";
privateString message= "";
@Override
publicString execute() throwsException {
setMessage(MESSAGE);
returnSUCCESS;
}
publicString getMessage(){
returnmessage;
}
publicvoidsetMessage(String message) {
this.message= message;
}
}
编写view的jsp
<%@page language="java"import="java.util.*"pageEncoding="utf8"%>
<%@taglib prefix="s"uri="/struts-tags"%>
<!DOCTYPEHTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MyJSP 'success.jsp' starting page</title>
</head>
<body>
<h2><s:propertyvalue="message"/></h2><br>
</body>
</html>
编写struts.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstruts PUBLIC
"-//ApacheSoftware Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<packagename="default"extends="struts-default">
<actionname="HelloWorld"class="com.action.IndexAction">
<resultname="success">/views/success.jsp</result>
</action>
</package>
</struts>
注:<actionname="HelloWorld"中的HelloWorld对应浏览器上输入的地址,class对应要调用的action类。<resultname="success">对应action类的execute方法返回的string。我的jsp页面放在项目根目录的views文件夹下。此struts.xml放在src目录下!
部署编译
在浏览器上输入http://localhost:8080/xxx/HelloWorld.action
Ok~~输出structis running 就成功啦。