- 创建web项目
- 添加Struts2的jar包
- 在web.xml文件中配置Struts2的核心过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置核心过滤器-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- 定义处理用户请求的Action类
package cn.itcast.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
- 编写Struts2的配置文件
在src目录下创建一个名称为struts.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<!--struts2配置文件的根元素-->
<struts>
<!--struts2的Action必须放在指定的包空间下定义-->
<package name="hello" namespace="/" extends="struts-default">
<!--定义action,该action对应的类为cn.itcast.action.HelloWorldAction类-->
<action name="hello" class="cn.itcast.action.HelloWorldAction">
<!--定义处理结果和视图资源之间的映射关系-->
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
- 创建视图文件
在web目录下创建一个index.jsp和success.jsp文件
**index.xml文件**
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h2>Welcome To Struts 2!</h2>
<a href="${pageContext.request.contextPath}/hello.action">Hello Wrold</a>
</body>
</html>
**success.jsp文件**
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功页面</title>
</head>
<body>
</body>
欢迎学习第一个struts程序!
</html>
在浏览器地址栏中输入http://localhost:8080/SSHProgects/index.jsp成功访问结果如下图
单击Hellow World的超链接,发送地址为hello.action的请求,运行结果如下图