Struts 2 Annotations

本文介绍了如何通过Struts2注解替代传统的struts.xml配置文件,实现验证与操作的零配置。通过示例展示了如何在项目中引入必要的jar文件,创建JSP页面和Action类,并利用注解进行字段验证。

As mentioned previously, Struts provides two forms of configuration. The traditional way is to use the struts.xml file for all the configurations. We have seen so many examples of that in the tutorail so far. The other way of configuring Struts is by using the Java 5 Annotations feature. Using the struts annotations, we can achieve Zero Configuration.

To start using annotations in your project, make sure you have included following jar files in your WebContent/WEB-INF/lib folder:

  • struts2-convention-plugin-x.y.z.jar

  • asm-x.y.jar

  • antlr-x.y.z.jar

  • commons-fileupload-x.y.z.jar

  • commons-io-x.y.z.jar

  • commons-lang-x.y.jar

  • commons-logging-x.y.z.jar

  • commons-logging-api-x.y.jar

  • freemarker-x.y.z.jar

  • javassist-.xy.z.GA

  • ognl-x.y.z.jar

  • struts2-core-x.y.z.jar

  • xwork-core.x.y.z.jar

Now let us see how you can do away with the configuration available in the struts.xml file and replace it with annotaions.

To explain the concept of Annotation in Struts2, we would have to reconsider our validation example explained in Struts2 Validations chapter.

Here we will take an example of Employee whose name and age would be captured using a simple page and we will put two validation to make sure that use always enters a name and age should be in between 28 and 65. So let us start with the main JSP page of the example.

Create main page:

Let us write main page JSP file index.jsp, which will be used to collect Employee related information mentioned above.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Employee Form</title>
</head>

<body>

   <s:form action="empinfo" method="post">
      <s:textfield name="name" label="Name" size="20" />
      <s:textfield name="age" label="Age" size="20" />
      <s:submit name="submit" label="Submit" align="center" />
   </s:form>

</body>
</html>

The index.jsp makes use of Struts tag, which we have not covered yet but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag.

Create Views:

We will use JSP file success.jsp which will be invoked in case defined action returns SUCCESS.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success</title>
</head>
<body>
   Employee Information is captured successfully.
</body>
</html>

Create Action:

This is the place where annotation will be used. Let us re-define action class Employee with annotation, and then add a method called validate() as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed.

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.validator.annotations.*;

@Results({
   @Result(name="success", location="/success.jsp"),
   @Result(name="input", location="/index.jsp")
})
public class Employee extends ActionSupport{
   private String name;
   private int age;

   @Action(value="/empinfo")
   public String execute() 
   {
       return SUCCESS;
   }

   @RequiredFieldValidator( message = "The name is required" )
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }

   @IntRangeFieldValidator(message = "Age must be in between 28 and 65",
                                      min = "29", max = "65")
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
}

We have used few annotations in this example. Let me go through them one by one:

  • First, we have included the Results annotation. A Results annotation is a collection of results. Under the results annotation, we have two result annotations. The result annotations have the name that correspond to the outcome of the execute method. They also contain a location as to which view should be served corresponding to return value from execute().

  • The next annotation is the Action annotation. This is used to decorate the execute() method. The Action method also takes in a value which is the URL on which the action is invoked.

  • Finally, I have used two validation annotations. I have configured the required field validator on name field and the integer range validator on the age field. I have also specified a custom message for the validations.

Configuration Files:

We really do not need struts.xml configuration file, so let us remove this file and let us check the content of web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">

   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
      <init-param>
         <param-name>struts.devMode</param-name>
         <param-value>true</param-value>
      </init-param>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you following screen:

Email User Input

Now do not enter any required information, just click on Submit button. You will see following result:

Error

Enter the required information but enter a wrong From field, let us say name as "test" and age as 30, and finally click on Submit button. You will see following result:

Success

Struts 2 Annotations Types:

Struts 2 applications can use Java 5 annotations as an alternative to XML and Java properties configuration. You can check the list of most important annotations related to different categories:

Struts 2 Annotations Types.


内容概要:本文提出了一种针对大规模电动汽车接入电网的双层优化调度策略,并基于IEEE33节点系统进行了建模与仿真分析,配套提供了完整的Matlab代码实现。该策略构建了上层电网运行优化与下层电动汽车充电调度的双层协同模型,综合考虑电网负荷削峰填谷、电压稳定性维持以及电动汽车用户充电需求满足等多重目标,采用先进的优化算法实现对电动汽车集群的智能有序调度。研究详细阐述了双层模型的构建逻辑、目标函数设计、约束条件设定及迭代求解流程,有效降低了电网峰谷差,提升了配电系统对可再生能源的消纳能力,兼具扎实的理论深度与明确的工程应用前景。; 适合人群:电气工程、电力系统及其自动化、能源系统优化等相关专业的研究生、科研人员以及从事智能电网、电动汽车调度、分布式能源管理等领域工作的工程师和技术人员。; 使用场景及目标:①深入研究高比例电动汽车接入对配电网运行特性的影响机制;②掌握电力系统双层优化建模方法及其在实际系统中的求解技巧;③实现电动汽车集群的协同调度与车网互动(V2G)优化控制;④作为撰写学术论文、开展课题研究或复现高水平期刊成果的技术参考与代码基础。; 阅读建议:建议读者结合所提供的Matlab代码逐行理解双层优化模型的数学表达与程序实现细节,重点剖析上下层模型之间的信息交互机制与收敛判据,可通过调整电动汽车渗透率、充电行为参数或引入分布式电源等场景进行拓展性仿真,以深化对智能调度策略适应性的认识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值