个性化阅读
专注于IT技术分析

Struts 2注解用法示例图解

点击下载

本文概述

  1. Struts 2注释
  2. 使用注释的Struts 2应用程序示例

Struts 2为你提供了使用注释创建Struts应用程序的便捷方法。因此, 不需要struts.xml文件。

如前所述, 有两种使用零配置文件(无struts.xml文件)的方法。

  1. 按照惯例
  2. 通过注释

Struts 2应用程序中使用的注释

对于struts 2的简单注释示例, 我们可以使用3个注释:

1)@Action批注用于标记动作类。

2)@Results批注用于为一个动作定义多个结果。

3)@Result批注用于显示单个结果。


使用注释的Struts 2应用程序示例

你需要为带注释的应用程序创建4个文件:

  1. index.jsp
  2. 动作课
  3. src目录中的struts.properties
  4. 结果页面
  5. web.xml文件

首先让我们看一下目录结构。

使用注解的Struts 2应用程序的目录结构

1)创建index.jsp作为输入

该jsp页面使用struts UI标记创建一个表单, 该表单从用户接收名称。

index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<s:form action="myAction" >
<s:textfield name="name" label="Name" />
<s:submit />
</s:form>

2)创建动作类

该动作类将标注用于动作和结果。

RegisterAction.java

package mypack;
import org.apache.struts2.convention.annotation.*;

@Action(value="myAction", results={@Result(name="ok", location="/myResults/result.jsp")})
public class MyAction {
private String name;
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public String execute()
{
return "ok";	
}
}

3)在src目录中创建struts.properties文件

struts.properties

struts.convention.package.locators=mypack
struts.convention.result.path=/myResults
struts.convention.action.mapAllMatches=true

4)创建result.jsp以显示消息

此jsp页面显示用户名。

result.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
Hello, <s:property value="name" /> It is annotated application.

下载这个在Eclipse IDE中开发的示例(无jar)


输出

struts注解示例1
struts 2注解示例2
赞(0)
未经允许不得转载:srcmini » Struts 2注解用法示例图解

评论 抢沙发

评论前必须登录!