第一步:选择创建Struts2项目

第二步:设置项目名称和项目路径。

第三步:配置tomcat





配置成功

现在一个基本的struts2项目创建成功了。
Struts2项目的核心JAR包如下:

现在就写一个简单的demo来测试。
项目结构如下:

StrutsAction.java
package action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
public class StrutsAction extends ActionSupport {
// 属性名必须和JSP页面的name一致
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String execute() {
if (!username.equals("张三")) {
Map request = (Map) ActionContext.getContext().get("request");
request.put("username", getUsername());
return "success";
} else {
return "error";
}
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="loginAction" class="action.StrutsAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
<result name="input">index.jsp</result>
</action>
</package>
</struts>
web.xml
<?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>
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误</title>
</head>
<body>
</body>
</html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Struts应用</title>
</head>
<body>
<form action="loginAction" method="post">
请输入姓名:<input type="text" name="username"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
效果展示


本文详细介绍了如何从零开始创建一个Struts2项目,包括项目创建步骤、核心JAR包配置、项目结构搭建及简单登录示例。通过整合struts.xml、web.xml配置文件,以及StrutsAction类、JSP页面的编写,实现了基本的用户输入验证流程。
——创建第一个Struts2项目&spm=1001.2101.3001.5002&articleId=102459122&d=1&t=3&u=02e54d0589934bf58c7a2cf3ef8ebdb8)
1062

被折叠的 条评论
为什么被折叠?



