1.在Eclipse中创建一个动态网站项目。
File -> New -> Dynamic Web Project,然后一直next直到finish。
2.将Struts2的支持类型库文件添加到 Web-INF目录的lib文件夹中。
由于本例子较简单,只需添加Struts2的核心类库即可。
此处提供百度网盘:
链接:https://pan.baidu.com/s/1BKEuQZrmKTLmET8eiOTLtQ 密码:ygl8
3.在Web-INF目录下的web.xml文件中声明Struts2提供的过滤器。
如果没有web.xml文件,参考这里创建:https://www.cnblogs.com/whgk/p/9081565.html
web.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>8.1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- Struts2过滤器 -->
<filter>
<!-- 过滤器名称 -->
<filter-name>struts2</filter-name>
<!-- 过滤器类 -->
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- Struts2过滤器映射 -->
<filter-mapping>
<!-- 过滤器名称 -->
<filter-name>struts2</filter-name>
<!-- 过滤器映射 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
其中,注意点击左下角的Source视图,不然无法编辑。
4.在Java Rescourses -> src目录下创建配置文件struts.xml。
在此配置文件中定义Struts2的Action对象。
Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<!-- 声明包 -->
<package name="myPackage" extends="struts-default">
<!-- 定义action -->
<action name="first">
<!-- 定义处理成功后的映射页面 -->
<result>/first.jsp</result>
</action>
</package>
</struts>
5.在WebContent目录下新建index.jsp和first.jsp,进行验证。
index.jsp
<%@ 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>主页</title>
</head>
<body>
<a href="first.action">请求Struts2</a>
</body>
</html>
first.jsp
<%@ 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>第一个Struts2程序</title>
</head>
<body>
第一个Struts2程序!
<br>
</body>
</html>
运行如图所示:
-->