👋 Hello World - 第一个 Struts2 应用
📝 本节要点: 创建最简单的 Struts2 应用,掌握 Action 编写和 struts.xml 配置
1. 项目结构
webapp/ ├── WEB-INF/ │ ├── web.xml │ └── lib/ │ └── struts2-core.jar ├── struts.xml ← Action 配置 ├── index.jsp └── hello.jsp ← 结果页面
2. web.xml 配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <!-- Struts2 核心过滤器 --> <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>
3. 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"> <struts> <!-- 开发模式 --> <constant name="struts.devMode" value="true"/> <!-- 定义包 --> <package name="default" namespace="/" extends="struts-default"> <!-- Action 配置 --> <action name="hello" class="com.demo.HelloAction"> <result>/hello.jsp</result> </action> </package> </struts>
4. HelloAction.java
package com.demo; import com.opensymphony.xwork2.ActionSupport; /** * 第一个 Struts2 Action * 继承 ActionSupport 可以获得验证、国际化的能力 */ public class HelloAction extends ActionSupport { // 接收参数 private String name; // 返回给页面的数据 private String message; /** * 执行方法,默认调用 */ @Override public String execute() throws Exception { if (name == null || name.trim().isEmpty()) { name = "Struts2 学习者"; } message = "你好, " + name + "! 欢迎学习 Struts2!"; return SUCCESS; // 返回 "success" } // Getter/Setter 必须提供,Struts2 通过反射注入参数 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
5. hello.jsp 结果页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html> <html> <body> <!-- 使用 Struts2 标签获取 Action 返回的值 --> <h1><s:property value="message"/></h1> </body> </html>
6. 访问方式
启动应用后,访问:
http://localhost:8080/hello - 默认执行http://localhost:8080/hello?name=张三 - 传递参数
执行流程图
浏览器请求 → Struts2 Filter → ActionProxy → HelloAction.execute()
→ 返回 "success" → 配置的 result → hello.jsp → 浏览器