今天写篇关于struts2入门的文章吧,struts2现在逐渐开始流行起来了,已有不少公司都采用struts2。
我的开发环境是MyEclipse5.5GA Enterprise Workbench+JDK1.5+tomcat6.0。首先到官方网站下载struts2,http://struts.apache.org/download.cgi#struts20111,选择Full Distribution:
- struts-2.0.11.2-all.zip (91mb) 下载后解压即可。
1、新建一个Web Project,将以下5个jar文件,放到WebRoot\WEB-INF\lib下:
struts2-core.jar | Struts2的核心api,也是我们以后打交道最多的 |
xwork-2.0.4.jar | Struts2(同Webwork一样)建立在XWork 2库的基础上 |
ognl-2.6.11.jar | Object Graph Navigation Language (OGNL), 类似于jsp2.0中EL表达式的一门用于访问对象的表达式语言 |
freemarker-2.3.8.jar | Struts2所有的ui标记的模板均使用freemarker编写,freemarker根据struts2 ui标记的模板渲染,可通过修改或重写模板使struts2的ui标记按你的要求渲染 |
commons-logging-1.0.4.jar | 封装了通用的日志接口(在Log4J or JDK 1.4+日志api的基础上 ) |
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"> <filter> <filter-name>action2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>action2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
FilterDispatcher是一个servlet过滤器,它是整个Web应用的配置项.
3、新建一个action,struts2的action不需要继承其它类,也不需要实现其他接口。这样的类就是一个简单的POJO。
package com.yx.action;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class HelloAction extends ActionSupport {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute() {
name = "你好, " + name + "!";
return SUCCESS;
}
}
4、在struts.xml中添加action映射
在struts2\src下新建一个struts.xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <include file="struts-default.xml" /> <!-- struts2的action必须放在一个指定的包空间下定义 --> <package name="struts2" extends="struts-default"> <!-- 定义处理请求URL为Hello.action的Action --> <action name="Hello" class="com.yx.action.HelloAction"> <!-- 定义处理结果字符串和资源之间的映射关系,, 如果开发人员没有显式指定它的值,那么它的默认值就是“success” --> <result>hello.jsp</result> </action> </package> </struts>
5、index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Struts2</title>
</head>
<body>
<s:form action="Hello.action"> 姓名: <s:textfield name="name" />
<s:submit />
</s:form>
</body>
</html>
hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Struts2</title>
</head>
<body>
<h3>
<s:property value="name" />
</h3>
</body>
</html>
一个最基本的struts2,就配合好了。