无法使用struts2注释

This is the second article in the series of Struts 2 Tutorials. If you have directly come here, I would recommend to check out earlier post too.

这是《 Struts 2教程》系列的第二篇文章。 如果您直接来过这里,我也建议您查看之前的帖子。

Struts 2 Beginners Tutorial

Struts 2初学者教程

In last tutorial, we looked into the Struts 2 architecture, it’s components and build a simple Struts 2 web application with XML based configuration (struts.xml). In this tutorial we will see how we can avoid struts configuration file completely using annotations or naming conventions.

在上一教程中,我们研究了Struts 2体系结构及其组件,并使用基于XML的配置(struts.xml)构建了一个简单的Struts 2 Web应用程序。 在本教程中,我们将看到如何使用注释或命名约定完全避免struts配置文件。

Struts 2公约概念 (Struts 2 Convention Concept)

Struts 2 uses two methodologies to find out the action classes and result classes. We need to use struts2-convention-plugin API to use any of these methodologies. If you have a normal web application, you can download it’s jar file and put it in the web application lib directory. For maven projects, you can simply add it’s dependency like below.

Struts 2使用两种方法来找出动作类和结果类。 我们需要使用struts2-convention-plugin API来使用任何这些方法。 如果您有普通的Web应用程序,则可以下载它的jar文件并将其放在Web应用程序的lib目录中。 对于Maven项目,您可以像下面这样简单地添加它的依赖项。

<dependency><groupId>org.apache.struts</groupId><artifactId>struts2-convention-plugin</artifactId><version>2.3.15.1</version>
</dependency>
  1. Scanning: In this method, we specify package which needs to be scanned for action classes. The configuration needs to be done in web.xml for Struts 2 filter, like below.

    <filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class><init-param><param-name>actionPackages</param-name><param-value>com.journaldev.struts2.actions</param-value></init-param>
    </filter>

    Struts 2 will find action classes by following methods.

    • Any class annotated with @Action or @Actions annotations.
    • Any class implementing Action interface or extending ActionSupport class.
    • Any class whose name ends with Action and contains execute() method. For these classes, naming convention is used to determine action and results.

    扫描 :在此方法中,我们指定需要扫描以获取操作类的程序包。 需要在web.xml中为Struts 2过滤器完成配置,如下所示。

    Struts 2将通过以下方法找到动作类。

    • 任何带有@Action@Actions批注的类。
    • 任何实现Action接口或扩展ActionSupport类的类。
    • 名称以Action结尾且包含execute()方法的任何类。 对于这些类,使用命名约定来确定操作和结果。
  2. Naming Convention: Struts 2 will automatically create action for classes name ending with Action. The action name is determined by removing the Action suffix and converting first letter to lowercase. So if class name is HomeAction, then action will be “home”.

    If these classes are not annotated with @Result to provide the result, then result pages are looked into WEB-INF/content directory and name should be {action}-{return_string}.jsp. So if HomeAction action class is returning “success”, the request will be forwarded to WEB-INF/content/home-success.jsp page.

    Using naming convention alone can be very confusing and we can’t use same JSP page for other action classes. So we should try to avoid this and use annotation based configuration.

    命名约定 :Struts 2将自动为以Action结尾的类名称创建action。 通过删除动作后缀并将首字母转换为小写来确定动作名称。 因此,如果类名称为HomeAction,则操作将为“ home”。

    如果未使用@Result注释这些类以提供结果,则将结果页查找到WEB-INF / content目录中,名称应为{action}-{return_string} .jsp。 因此,如果HomeAction操作类返回“成功”,则该请求将转发到WEB-INF / content / home-success.jsp页面。

    单独使用命名约定可能会造成很大的混乱,我们不能将相同的JSP页面用于其他操作类。 因此,我们应该尝试避免这种情况,并使用基于注释的配置。

Now we are ready to create our Hello World struts 2 application using annotations and we won’t have struts 2 configuration file.

现在,我们准备使用批注创建Hello World struts 2应用程序,并且没有struts 2配置文件。

Create a dynamic web project in Eclipse Struts2AnnotationHelloWorld and convert it to maven project. The final project looks like below image.

在Eclipse Struts2AnnotationHelloWorld中创建一个动态Web项目,并将其转换为Maven项目。 最终项目如下图所示。

Maven配置 (Maven Configuration)

We have added struts2-core and struts2-convention-plugin dependencies in the pom.xml, final pom.xml code is:

我们在pom.xml中添加了struts2-core和struts2-convention-plugin依赖项,最终的pom.xml代码为:

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>Struts2AnnotationHelloWorld</groupId><artifactId>Struts2AnnotationHelloWorld</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><dependencies><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-core</artifactId><version>2.3.15.1</version></dependency><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-convention-plugin</artifactId><version>2.3.15.1</version></dependency></dependencies><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>2.3</version><configuration><warSourceDirectory>WebContent</warSourceDirectory><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins><finalName>${project.artifactId}</finalName></build>
</project>

部署描述符配置 (Deployment Descriptor Configuration)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xmlns="https://java.sun.com/xml/ns/javaee"xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><display-name>Struts2AnnotationHelloWorld</display-name><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class><init-param><param-name>actionPackages</param-name><param-value>com.journaldev.struts2.actions</param-value></init-param></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>

Notice the init-param element where we are providing action classes package that will be scanned by struts 2.

请注意init-param元素,我们在其中提供将由struts 2扫描的动作类包。

结果页 (Result Pages)

We have three result pages in our application.

我们的应用程序中有三个结果页面。

login.jsp

login.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login"><s:textfield name="name" label="User Name"></s:textfield><s:textfield name="pwd" label="Password" type="password"></s:textfield><s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

error.jsp

error.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Error Page</title>
</head>
<body>
<h4>User Name or Password is wrong</h4>
<s:include value="login.jsp"></s:include>
</body>
</html>

welcome.jsp

welcome.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Welcome Page</title>
</head>
<body>
<h3>Welcome <s:property value="name"></s:property></h3>
</body>
</html>

Now let’s create our Action classes that we will annotate to configure action and result pages.

现在,让我们创建Action类,我们将对其进行注释以配置操作和结果页面。

带注释的动作类 (Action Classes with Annotations)

package com.journaldev.struts2.actions;import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;import com.opensymphony.xwork2.ActionSupport;/*** An empty class for default Action implementation for:* *  <action name="home">*       <result>/login.jsp</result>*    </action>* HomeAction class will be automatically mapped for home.action* Default page is login.jsp which will be served to client* @author pankaj**/@Namespaces(value={@Namespace("/User"),@Namespace("/")})
@Result(location="/login.jsp")
@Actions(value={@Action(""),@Action("home")})
public class HomeAction extends ActionSupport {
}

Notice that HomeAction is an empty class with only purpose to forward the request to login.jsp page.

注意,HomeAction是一个空类,仅用于将请求转发到login.jsp页面。

package com.journaldev.struts2.actions;import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;/*** Notice the @Action annotation where action and result pages are declared* Also notice that we don't need to implement Action interface or extend ActionSupport* class, only we need is an execute() method with same signature* @author pankaj**/
@Action(value = "login", results = {@Result(name = "SUCCESS", location = "/welcome.jsp"),@Result(name = "ERROR", location = "/error.jsp") })
@Namespaces(value={@Namespace("/User"),@Namespace("/")})
public class LoginAction {public String execute() throws Exception {if("pankaj".equals(getName()) && "admin".equals(getPwd()))return "SUCCESS";else return "ERROR";}//Java Bean to hold the form parametersprivate String name;private String pwd;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}
}

Notice the use of @Action, @Actions, @Result, @Namespace and @Namespaces annotations, the usage is self explanatory.

注意使用@ Action,@ Actions,@ Result,@ Namespace和@Namespaces批注,其用法不言自明。

Now when we run our application, we get following response pages.

现在,当我们运行应用程序时,我们将获得以下响应页面。

If you have read the last post where we have developed the same application with struts.xml configuration, you will notice that it’s almost same. The only change is the way we wire our application action classes and result pages.

如果您阅读了上一篇文章,其中我们使用struts.xml配置开发了相同的应用程序,那么您会发现它几乎是相同的。 唯一的变化是我们连接应用程序操作类和结果页面的方式。

Download Struts2 Annotations Example Project下载Struts2注释示例项目

翻译自: https://www.journaldev.com/2146/struts-2-hello-world-example-with-annotations-and-without-struts-xml-file

无法使用struts2注释

无法使用struts2注释_带有注释且没有struts.xml文件的Struts 2 Hello World示例相关推荐

  1. Struts2配置struts.xml文件

    Struts2配置struts.xml文件 Struts2框架的核心配置文件是struts.xml文件 该文件,主要用来配置Action和请求的对应关系,以及配置逻辑视图和物理视图资源的对应关系 st ...

  2. Struts2的2.5.10版本找不到StrutsPrepareAndExecuteFilter过滤器 与 struts.xml文件通配符异常问题

    一.异常描述: 今天在整合ssh的时候,在配置Struts2框架之后,启动之后,项目报错抛异常:主要异常信息如下: java.lang.ClassNotFoundException: org.apac ...

  3. 解决Struts2的配置文件struts.xml文件无提示问题

    1.在上一篇文章Struts2搭建开发环境并编写第一个Struts2应用 中,详细的图解介绍了如何搭建Struts2开发环境和编写第一个Struts2应用,其中struts2的配置文件struts.x ...

  4. java 自定义注释_带有自定义注释的Java注释教程

    java 自定义注释 Java批注提供有关代码的信息,并且它们对其批注的代码没有直接影响. 在本教程中,我们将学习Java注释,如何编写自定义注释 ,注释用法以及如何使用反射来解析注释 . 注释是在J ...

  5. jsp界面自动生成文件注释_实施注释界面

    jsp界面自动生成文件注释 对于Java开发人员而言,每天都需要使用注释. 如果没有其他简单的@Override注释,那该响了. 创建注释要复杂一些. 在运行时通过反射使用"自制" ...

  6. matlab分析xml文件_如何在Java中读取XML文件(DOM分析器)

    matlab分析xml文件 Today we will learn how to read the XML file in Java. We will also learn how to parse ...

  7. 为什么开源的代码没有注释_代码注释那些事儿

    程序源代码中的注释经常是一个卧虎藏龙的地方, 来看看这一辑国外某公司产品中的注释. 注意:看的时候严禁喝水或进食. 亲爱的代码维护人员:当您尝试优化这段代码但发现这是一个极端错误的决定的时候,请修改下 ...

  8. spring 定时器注释_带注释的控制器– Spring Web / Webflux和测试

    spring 定时器注释 Spring Webflux和Spring Web是两个完全不同的Web堆栈. 但是, Spring Webflux继续支持基于注释的编程模型 使用这两个堆栈定义的端点可能看 ...

  9. python_程序格式_缩进_行注释_段注释---python工作笔记012

    然后我们再去看python程序的基本格式,以及注释 我们通过上面这个简单的程序去看 我们打开idel的ide 然后用file  new file 去创建一个文件,保存到一个,本地,没有中文,没有空格的 ...

最新文章

  1. 图像去畸变矫正及双线性内插法
  2. nmap命令_白帽子黑客教你:如何用Nmap探测目标主机操作系统类型?
  3. 4.1 配置Flask-WTF
  4. 计算机绘图实训,计算机绘图实训-杜兰萍主编.pdf
  5. 从0开始学习GitHub系列之「向GitHub 提交代码」
  6. 3. 什么是icmp?icmp与ip的关系_「2020.12.3」黄俊捷热搜被爆料?郭俊辰交往女朋友?为什么三只跨年不合体?郝富申和王俊凯关系?Naomi和alracco?...
  7. asp.net treeView 节点 点击 变色
  8. 上验证cudnn是否安装成功_windows和linux上的tensorflow安装(极简安装方法)
  9. mysql explain insert_MySQL之EXPLAIN 执行计划详解
  10. linux事务隔离级别,事务的隔离级别(Transaction isolation levels)2
  11. 大项目之网上书城(十二)——完成啦
  12. 如何关闭kafka的控制台日志
  13. 谁是面向对象设计中的霸主?(中)
  14. mysql备份恢复出错_MySQL:MySQL备份失败,原因和解决方式
  15. R语言模拟:Cross Validation
  16. 快速计算代码行小工具
  17. Skype国际版最新版及老版本下载
  18. NB-IOT(BC95模组)对接华为中国电信物联网平台上行数据与下行数据总流程
  19. 构建面向未来的前端架构
  20. 课堂笔记_ 光线跟踪加速

热门文章

  1. .NET设计模式(10):装饰模式(Decorator Pattern)
  2. [转载] Python: ljust()|rjust()|center()字符串对齐
  3. [转载] numpy.inf
  4. [转载] Python: fnmatch模块 (Unix B-Shell通配符的文件名匹配)
  5. zabbix4.0LTS安装配置
  6. cobbler的搭建
  7. 20165223 week2测试补交与总结
  8. 阿里云API网关(6)用户指南(开放 API )
  9. 为什么模板函数的声明和实现都放在.h文件中
  10. 为什么一个实例只有一个LGWR