创建项目

选择命名空间

1.1入门案例
1.添加struts2相关依赖
2.修改web.xml,加载struts2配置
3.编写Action控制器
4.编写index.jsp页面
5.编写struts2.xml文件
1.1.1添加struts2相关依赖
在pom.xml文件中加入struts2的依赖代码:
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.22</version> </dependency>
1.1.2修改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>
<!--过滤器名称,自定义,命名为struts2 -->
<filter-name>struts2</filter-name>
<!-- 过滤器核心类-->
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<!--过滤器名称,自定义,命名为struts2 -->
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
1.1.3 .编写Action控制器
package com.xyz.web;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
private String userName;
@Override
public String execute() throws Exception {
System.out.println("useaName:"+userName);
return "ok";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
1.1.4 编写index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<form action="hello.action"method="post">
<div>
<label>用户名</label>
<input type="text" name="userName">
</div>
<div>
<input type="submit" value="提交">
</div>
</form>
</body>
</html>
1.1.5编写struts2.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">
<struts>
<package name="default" extends="struts-default" >
<action name="hello" class="com.xyz.web.HelloAction">
<result name="ok">/show.jsp</result>
</action>
</package>
</struts>
本文详细介绍了如何在Java项目中集成Struts2,包括添加依赖、配置web.xml、创建HelloAction并编写对应页面及struts2.xml。从添加依赖到实际运行,逐步引导读者掌握Struts2的基础应用。
1836

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



