使用IDEA2021构建第一个struts2项目
1、file → new project 选择JavaEnterprise(也可以使用Maven等构建),项目结构如下:
2、打开pom.xml添加以下代码,加入位置如图:
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.22</version>
</dependency>
PS:若字体出现红色即报错,点击右侧Maven,点击刷新
再右击Denpendcies,选择Download Soures and Documentation
3、打开web.xml文件添加代码(注意Struts版本)
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<!--
struts2.5版本为以上路径
struts2.5版本为以下路径
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
-->
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3、在com.exmaple.demo3中添加类HelloWorldAction.java,并写入以下代码:
package com.example.demo3;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
@Override
public String execute() throws Exception {
return "success";
}
}
4、在resoureces新建名为struts的xml文件
5、打开文件,添加一下代码:
<?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">
<struts>
<!--package.name可以随意,extends不能修改-->
<package name="hello" extends="struts-default">
<!--action的name随意,但class必须是Action类的路径-->
<action name="helloWorld" class="com.example.demo3.HelloWorldAction">
<!--result的name为Action类返回的值-->
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
6、添加webapp文件夹下添加success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>成功</h3>
</body>
</html>
7、运行项目,在项目路径后添加struts.xml中action的name+“.action”,在此项目中url为:
http://localhost:8080/demo3_war_exploded/helloWorld.action,出现页面
8、创建成功