1.获取struts的jar包
1.1首先在http://struts.apache.org/download.cgi#struts23163这里下载 struts的文件包(选择struts-2.3.16.3-all)
1.2解压得到如下的文件夹
apps文件夹下是struts的一些官方例子
docs已久是官方api说明文档
lib包是struts所有的jar包
src则是一些例子的资源文件
注意:接下来我们需要取得我们需要的jar包,而不是lib目录下所有的jar文件,如果全部导入有可能会发生冲突
那么哪些才是我们需要的jar包呢?
1.3打开apps文件夹,解压struts2-blank.war得到示例的文件
1.4打开WEB-INF/lib 里面的jar包就是我们基本struts操作需要的jar包。把他们取出来待用。
2.在项目中取得struts的支持
2.1 打开eclipse 新建动态web
2.2将第一步取得jar包复制到项目WEB-INF/lib目录下
2.3在项目中添加web.xml并配置
在WEB-INF根目录下添加web.xml文件并配置struts的过滤器
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
</span>
3.建立struts并实现
3.1在scr中新建action继承ActionSupport
<span style="font-size:18px;">package fzl.struts.demo;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("--------UserAction-------");
return "success";
}
}
</span>
3.2在配置struts.xml文件
在src根目录下建立struts.xml文件并进行一下配置
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="fzl.struts.demo.UserAction">
<result>/hello.jsp</result>
</action>
</package>
</struts>
</span>
4建立显示层文件
在WEB-INF文件夹下建立hello.jsp
<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>hello struts</h2>
<h2>这是我的第一个struts程序</h2>
</body>
</html></span>
启动Tomcat、在地址栏输入http://localhost:端口号/StrutsDemo/hello 即可得到如下页面
到这里我们的struts的配置已经完成并实现了。
最后总结一下
基本步骤:
1、拷贝struts的jar到项目中(apps中的blank项目中可以找到这些jar包) 2、将struts2的过滤器添加到web.xml中 3、配置struts2的配置文件(在src目录中创建struts.xml文件) 4、创建action(action就是一个POJO类) 4.1、为action编写execute方法 4.2、在struts.xml文件中配置action和返回结果集 |