一、在Controller中获取
使用内置属性 多数框架提供直接访问Action名称的属性或方法。例如:
- ThinkPHP:
通过`Think.ACTION_NAME`常量或`$Think.ACTION_NAME`获取;
- Struts2:通过`ActionContext`对象,如`ActionContext.getActionName()`或`Request.RouteData.Values["action"]`获取。
通过请求对象 部分框架允许通过`Request`对象获取路径信息,再通过正则表达式提取Action名称。例如:
```php
$actionName = preg_match('/\.action$/', $_SERVER['REQUEST_URI'], $matches);
$actionName = $matches ? $matches : null;
```
二、在视图中获取
使用Model辅助工具
通过`Model`对象访问`ActionContext`,例如:
```php
$actionName = Model::getInstance()->getActionName();
```
直接访问Route数据
在JSP或Thymeleaf等模板中,可通过`@{...}`表达式获取:
- JSP: `@{action}` - Thymeleaf
三、其他通用方法
Struts2拦截器 在拦截器中可通过`InvocationContext`获取:
```java
public String getActionName() {
return invocation.getInvocationContext().getName();
}
```
ASP.NET MVC
通过`ControllerContext`获取:
```csharp
string actionName = ControllerContext.RouteData.Values["action"];
```
注意事项
框架差异: 不同框架的实现可能不同,建议查阅具体框架的官方文档(如ThinkPHP、Struts2); 性能优化
通过以上方法,可根据具体场景灵活选择获取Action名称的方式。