Struts2框架实现helloworld程序,IDEA版
项目目录:
1.创建项目
2.导入Struts2 框架依赖的基础 jar包
官网下载或者点击博主主页免费下载,我用的是struts-2.3.37-all
3.配置 Struts2 的核心过滤器
打开项目的 web.xml 文件,在文件中添加 Struts2 的核心过滤org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
<?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.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<!--配置核心过滤器的映射-->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.创建Action类
在项目的 src 目录下,新建一个名称为 com.zh.action 的包,在包中创建一个名为 Hello的类
package com.zh.action;
import com.opensymphony.xwork2.ActionSupport;
public class Hello extends ActionSupport {
public String execute() {
System.out.println("hello world!");
return "SUCCESS";
}
}
5.编写Struts2的配置文件struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="com.zh.action.Hello">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>
6.创建视图首页文件
在web目录下创建 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/hello.action">第一个Struts2程序</a>
</body>
</html>
创建返回页面 success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>执行成功界面</title>
</head>
<body>
您的第一个Struts2程序执行成功!
</body>
</html>
运行结果: