Sunday, February 12, 2017

Struts2

Database Access
==============
Struts is a MVC framework and not a database framework but it provides excellent support for JPA/Hibernate integration.

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
public String execute() {
      String ret = ERROR;
      Connection conn = null;

      try {
         String URL = "jdbc:mysql://localhost/struts_tutorial";
         Class.forName("com.mysql.jdbc.Driver");
         conn = DriverManager.getConnection(URL, "root", "root123");
         String sql = "SELECT name FROM login WHERE";
         sql+=" user = ? AND password = ?";
         PreparedStatement ps = conn.prepareStatement(sql);
         ps.setString(1, user);
         ps.setString(2, password);
         ResultSet rs = ps.executeQuery();

         while (rs.next()) {
            name = rs.getString(1);
            ret = SUCCESS;
         }
      } catch (Exception e) {
         ret = ERROR;
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (Exception e) {
            }
         }
      }
      return ret;
   }


Sending Email
============
  static Properties properties = new Properties();
   static
   {
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.socketFactory.port", "465");
      properties.put("mail.smtp.socketFactory.class",
                     "javax.net.ssl.SSLSocketFactory");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.port", "465");
   }

   public String execute()
   {
      String ret = SUCCESS;
      try
      {
         Session session = Session.getDefaultInstance(properties,
            new javax.mail.Authenticator() {
            protected PasswordAuthentication
            getPasswordAuthentication() {
            return new
            PasswordAuthentication(from, password);
            }});

         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));
         message.setSubject(subject);
         message.setText(body);
         Transport.send(message);
      }
      catch(Exception e)
      {
         ret = ERROR;
         e.printStackTrace();
      }
      return ret;
   }

mail.jar from JavaMail API

(%@ taglib prefix="s" uri="/struts-tags"%)

Localization, internationalization (i18n)
========================================
internationalization(i18n)
localization(i10n)

global.properties
#Global messages
global.username = Username
global.password = Password
global.submit = Submit
global_zh_CN.properties

global_zh_CN.properties
#Global messages
global.username = \u7528\u6237\u540d
global.password = \u5bc6\u7801
global.submit=\u63d0\u4ea4
global_fr.properties

global_fr.properties
#Global messages
global.username = Nom d'utilisateur
global.password = Mot de passe
global.submit = Soumettre
global_de.properties

global_de.properties
#Global messages
global.username = Benutzername
global.password = Kennwort
global.submit = Einreichen

To support Struts 2 localization, you HAVE TO declared the (%@ page contentType=”text/html;charset=UTF-8? %)


(%@ page contentType="text/html;charset=UTF-8" %)
(%@ taglib prefix="s" uri="/struts-tags" %)
(html)
(head)
(/head)

(body)
(h1)Struts 2 localization example(/h1)
(s:form action="validateUser" namespace="/user")
(s:textfield key="global.username" name="username" /)
(s:password key="global.password" name="password"/)
(s:submit key="global.submit" name="submit" /)
(/s:form)
(s:url id="localeEN" namespace="/" action="locale" )
   (s:param name="request_locale" )en(/s:param)
(/s:url)
(s:url id="localezhCN" namespace="/" action="locale" )
   (s:param name="request_locale" )zh_CN(/s:param)
(/s:url)
(s:url id="localeDE" namespace="/" action="locale" )
   (s:param name="request_locale" )de(/s:param)
(/s:url)
(s:url id="localeFR" namespace="/" action="locale" )
   (s:param name="request_locale" )fr(/s:param)
(/s:url)
(s:a href="%{localeEN}" )English(/s:a)
(s:a href="%{localezhCN}" )Chinese(/s:a)
(s:a href="%{localeDE}" )German(/s:a)
(s:a href="%{localeFR}" )France(/s:a)
(/body)
(/html)

To change the default locale, you just need to declared a “request_locale” parameter, set your prefer language code and pass to an Action class. In Struts 2 the com.opensymphony.xwork2.interceptor.I18nInterceptor interceptor, which declared in the struts-default.xml, will check your Action class and handle the locale stuff accordingly.

(struts)
(constant name="struts.custom.i18n.resources" value="global" /)
  (constant name="struts.devMode" value="true" /)
(package name="user" namespace="/user" extends="struts-default")
  (action name="login")
(result)pages/login.jsp(/result)
  (/action)
  (action name="validateUser" class="com.mkyong.user.action.LoginAction")
(result name="SUCCESS")pages/welcome.jsp(/result)
(result name="input")pages/login.jsp(/result)
  (/action)
(/package)
(package name="default" namespace="/" extends="struts-default")
  (action name="locale" class="com.mkyong.common.action.LocaleAction")
(result name="SUCCESS")user/pages/login.jsp(/result)
  (/action)
(/package)
(/struts)

Resource bundle search order
Resource bundle is searched in the following order:

ActionClass.properties
Interface.properties
BaseClass.properties
ModelDriven’s model
package.properties
Search up the i18n message key hierarchy itself
Global resource properties

if a com.mkyong.user.action.LoginAction want to get a message via resource bundle, it will search
com.mkyong.user.action.LoginAction.properties (found, exit, else next)
com.mkyong.user.action.package.properties (found,exit, else next)
com.mkyong.user.package.properties (found exit, else next)
…keep find package.properties in every parent directory all the way to the root directory
Find the global resource properties if you configure it in your application

This i18n tag can get the message from a specified resource bundle that declared in the “name” attribute. In this example, it ask to get the ‘username’ message from com/mkyong/user/package.properties file.

(s:i18n name="com.mkyong.user.package" )
     (s:text name="username" /)
(/s:i18n)


Parameters of i18n interceptor

There are 2 parameters defined for i18n interceptor. Both are optional.

Parameter Description
parameterName It specifies the name of the HTTP request parameter. It is set to request_locale bydefault.
attributeName specifies the name of the session key to store the locale. It is WW_TRANS_I18N_LOCALE bydefault.

Login.java
Login_en.properties and Login_hi.properties

(s:textfield name="request_locale" label="Language Code")(/s:textfield)


Struts2 provides localization ie. internationalization (i18n) support through resource bundles, interceptors and tag libraries in the following places:
The UI Tags
Messages and Errors.
Within action classes.

resource file format:
bundlename_language_country.properties
bundlename could be ActionClass, Interface, SuperClass, Model, Package, Global resource properties

language_country format:
Country Locale:
Spanish (Spain) locale = es_ES and
English (United States) locale = en_US

country part which is optional.

When you reference a message element by its key, Struts framework searches for a corresponding message bundle in the following order:
ActionClass.properties
Interface.properties
SuperClass.properties
model.properties
package.properties
struts.properties
global.properties

languages/(locale=country is optional)

global.properties: By default English (United States) will be applied
global_fr.properties: This will be used for Franch locale.
global_es.properties: This will be used for Spanish locale.

The text tag retrieves a message from the default resource bundle ie. struts.properties
(s:text name="some.key" /)

The i18n tag pushes an arbitrary resource bundle on to the value stack. Other tags within the scope of the i18n tag can display messages from that resource bundle:
(s:i18n name="some.package.bundle")
     (s:text name="some.key" /)
(/s:i18n)


Struts2 Themes
==============
Types:
simple
xhtml
css_xhtml

theme
templateDir
templateSuffix

struts.ui.theme property in struts.properties (defaults to xhtml)

File: struts.properties
struts.ui.theme = css_xhtml


(s:textfield key="global.username" name="username" /)
---
(tr)
(td class="tdLabel")
  (label for="validateUser_username" class="label")Username:(/label)
(/td)
(td)
  (input type="text" name="username" value="" id="validateUser_username"/)
(/td)
(/tr)

Struts 2 is using the “Theme & template” feature to generate the pre-designed table layout

Struts 2 see a “s:textfield” tag.

Search the declared theme (if no theme declared , the default xhtml theme will be select).

Search the corresponds theme’s template, e.g “s:textfield -) text.ftl” , “s:password -)password.ftl“. All the pre-defined HTML layout is defined in the ftl file.

Bind the value into the template file.

Display the final HTML markup.

Struts 2 tags + Theme’s template file (ftl) = Final HTML markup code.

All the theme and template files are inside the struts2-core.jar, template folder. Extract it to your local drive.

(struts)
    ...
  (constant name="struts.ui.theme" value="mkyong" /) // mykong folder .ftl files are there
(constant name="struts.ui.templateDir" value="template" /) //constant
...
(/struts)

tag A small piece of code executed from within JSP, FreeMarker, or Velocity.
template A bit of code, usually written in FreeMarker, that can be rendered by certain tags (HTML tags).
theme A collection of templates packaged together to provide common functionality.

simple theme A minimal theme with no "bells and whistles". For example, the textfield tag renders the HTML (input/) tag without a label, validation, error reporting, or any other formatting or functionality.

xhtml theme This is the default theme used by Struts 2 and provides all the basics that the simple theme provides and adds several features like standard two-column table layout for the HTML, Labels for each of the HTML, Validation and error reporting etc.

css_xhtml theme This theme provides all the basics that the simple theme provides and adds several features like standard two-column CSS-based layout, using (div) for the HTML Struts Tags, Labels for each of the HTML Struts Tags, placed according to the CSS stylesheet.

Selecting themes
The theme attribute on the specific tag
The theme attribute on a tag's surrounding form tag
The page-scoped attribute named "theme"
The request-scoped attribute named "theme"
The session-scoped attribute named "theme"
The application-scoped attribute named "theme"
The struts.ui.theme property in struts.properties (defaults to xhtml)

(s:textfield name="name" label="Name" theme="xhtml"/)


 struts.properties
# Standard UI theme
struts.ui.theme=xhtml
# Directory where theme template resides
struts.ui.templateDir=template
# Sets the default template type. Either ftl, vm, or jsp
struts.ui.templateSuffix=ftl

default theme with a setting struts.ui.theme=xhtml in struts-default.properties file which comes by default in struts2-core.xy.z.jar file.



Struts2 Tiles
=============
We can customize the layout of the struts 2 application by integrating with tiles framework.

A web page can contain many parts (known as tile) such as header, left pane, right pane, body part, footer etc. In tiles framework, we manage all the tile by our Layout Manager page.

Add tiles library in your application
Define Struts2TilesListener in web.xml file
Create the input page (index.jsp)
Create the Action class
Extend the tiles-default package in your package and define all the result type as tiles in struts.xml file
Create the tiles.xml file and define all the tiles definitions
Create the LayoutManager page
Create the View components

Web.xml
 (listener)
  (listener-class)org.apache.struts2.tiles.StrutsTilesListener(/listener-class)
  (/listener)

Struts.Xml
(struts)
(package name="abc" extends="tiles-default" )
(action name="login" class="com.javatpoint.Login")
(result name="success" type="tiles")login-success(/result)
(result name="error" type="tiles")login-error(/result)
(/action)
(/package)
(/struts)  

Tiles.XML
(tiles-definitions)
   (definition name="login-success" template="/layoutmanager.jsp")  
   (put-attribute name="title" value="Welcome Page"/)  
   (put-attribute name="body" value="/login-success.jsp"/)  
   (/definition)
   (definition name="login-error" template="/layoutmanager.jsp")  
   (put-attribute name="title" value="Login Error"/)  
   (put-attribute name="body" value="/login-error.jsp"/)  
   (/definition)  
(/tiles-definitions)

layoutmanager.jsp
(%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %)
(title)(tiles:getAsString name="title" /)(/title)
(body)
(%@  include file="header.jsp" %)
(tiles:insertAttribute name="body" /)
(%@ include file="footer.jsp" %)
(/body)
(/html)

getAsString
insertAttribute

(context-param id="struts_tiles")
 (param-name)org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG(/param-name)
 (param-value)/WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml(/param-value)
(/context-param)

api/compact/core/jsp/servlet
tiles-api.jar
tiles-compat.jar
tiles-core.jar
tiles-jsp.jar
tiles-servlet.jar

beanutils/digester/plugin
commons-beanutils.jar
commons-digester.jar
struts2-tiles-plugin.jar



(tiles-definitions)
   (definition name="baseLayout" template="/baseLayout.jsp") //name Template extends
      (put-attribute name="title"  value="Template"/)
      (put-attribute name="banner" value="/banner.jsp"/)
      (put-attribute name="menu"   value="/menu.jsp"/)
      (put-attribute name="body"   value="/body.jsp"/)
      (put-attribute name="footer"   value="/footer.jsp"/)
   (/definition)
   (definition name="tiger" extends="baseLayout")
      (put-attribute name="title"  value="Tiger"/)
      (put-attribute name="body"   value="/tiger.jsp"/)    
   (/definition)
   (definition name="lion" extends="baseLayout")
      (put-attribute name="title"  value="Lion"/)
      (put-attribute name="body"   value="/lion.jsp"/)    
   (/definition)
(/tiles-definitions)

(%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%)
(!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd")
(html)
(head)
(meta http-equiv="Content-Type" content="text/html; charset=UTF-8")
(title)(tiles:insertAttribute name="title" ignore="true" /)
(/title)
(/head)
(body)
   (tiles:insertAttribute name="banner" /)(br/)
   (hr/)
   (tiles:insertAttribute name="menu" /)(br/)
   (hr/)
   (tiles:insertAttribute name="body" /)(br/)
   (hr/)
   (tiles:insertAttribute name="footer" /)(br/)
(/body)
(/html)

(%@taglib uri="/struts-tags" prefix="s"%)
(a href="(s:url action="tigerMenu"/)" Tiger(/a)(br)
(a href="(s:url action="lionMenu"/)" Lion(/a)(br)





org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

6590 7360

Data Tags - manipulate the data displayed on a page
=========
Struts 2 Data tags, help to get the data from the ValueStack, or place the data into the ValusStack

(s:url value="http://www.dineshonjava.com" var="dojURL" /)
(s:a href="%{dojURL}")Dinesh On Java(/s:a)
(s:url action="atag" var="atagURL" /)
(s:a href="%{atagURL}")a Tag Action(/s:a)
(-- Example 1 --)
(s:url value="editGadget.action")
    (s:param name="id" value="%{selected}" /)
(/s:url)
(-- Example 2 --)
(s:url action="editGadget")
    (s:param name="id" value="%{selected}" /)
(/s:url)
(-- Example 3--)
(s:url includeParams="get")
    (s:param name="id" value="%{'22'}" /)
(/s:url)

action tag
include tag
bean tag
date tag
param tag
property tag
push tag
set tag
text tag
url tag


(s:bean name="org.apache.struts2.util.Counter" var="counter")
   (s:param name="first" value="20"/)
   (s:param name="last" value="25" /)
(/s:bean)
(s:bean name="com.journaldev.struts2.model.User" var="myUser")
    (s:param name="name")Lisa(/s:param)
    (s:param name="gender" value="#application.defaultGender")(/s:param)
    (s:param name="address")India(/s:param)
(/s:bean)


(s:action name="actionTagAction" executeResult="true" /)
(s:action name="actionTagAction!specialMethod" executeResult="true" /)
Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified.
 They can set the "executeResult" parameter to "true" to render the result directly in the view. Or, they can set this parameter to "false", but make use of the request attributes exposed by the action method.

These property tag is used to get the property of a value, which will default to the top of the stack if none is specified.

(-- First Syntax --)
(s:include value="myJsp.jsp" /)
(-- Second Syntax --)
(s:include value="myJsp.jsp")
   (s:param name="param1" value="value2" /)
   (s:param name="param2" value="value2" /)
(/s:include)
(-- Third Syntax --)
(s:include value="myJsp.jsp")
   (s:param name="param1")value1(/s:param)
   (s:param name="param2")value2(/s:param)
(/s:include)

(s:date name="person.birthday" format="dd/MM/yyyy" /)
(s:date name="person.birthday" format="%{getText('some.i18n.key')}" /)
(s:date name="person.birthday" nice="true" /)
(s:date name="person.birthday" /)
predefined format with key 'struts.date.format' in your properties file.

(pre)
(ui:component)
 (ui:param name="key"     value="[0]"/)
 (ui:param name="value"   value="[1]"/)
 (ui:param name="context" value="[2]"/)
(/ui:component)
(/pre)

(s:push value="myBean")
    (!-- Example 1: --)
    (s:property value="myBeanProperty" /)
    (!-- Example 2: --)TextUtils
    (s:property value="myBeanProperty" default="a default value" /)
(/s:push)
(s:push value="user")
    (s:propery value="firstName" /)
    (s:propery value="lastName" /)
(/s:push)
These push tag is used to push value on stack for simplified usage.

(s:set name="myenv" value="environment.name"/)
(s:property value="myenv"/)
(s:set name="technologyName" value="%{'Java'}"/)
(s:property value="#technologyName"/)
(s:set var="defaultGender" value="user.gender" scope="application")(/s:set)
Default Gender = (s:property value="#application.defaultGender"/)(br)
Default Gender = (s:property value="#application['defaultGender']"/)(br)

(!-- First Example --)
(s:i18n name="struts.action.test.i18n.Shop")
    (s:text name="main.title"/)
(/s:i18n)
(!-- Second Example --)
(s:text name="main.title" /)
(!-- Third Examlpe --)
(s:text name="i18n.label.greetings")
   (s:param )Mr Smith(/s:param)
(/s:text)

FileUpload
==========
org.apache.struts2.dispatcher.FilterDispatcher

org.apache.struts2.interceptor.FileUploadInterceptor class and included as part of the defaultStack.

(form action="upload" method="post" enctype="multipart/form-data")
(input type="file" name="myFile" /)

The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern:

[your file name parameter] - This is the actual file that the user has uploaded. In this example it will be "myFile"

[your file name parameter]ContentType - This is the content type of the file that was uploaded. In this example it will be "myFileContentType"

[your file name parameter]FileName - This is the name of the file that was uploaded. In this example it will be "myFileFileName"

automaically these variables are auto wired for us

Configuration files
(constant name="struts.multipart.maxSize" value="1000000" /)
struts.multipart.maxSize //define maximum file size
struts.multipart.parser //used to upload the multipart form. By default is jakarta
struts.multipart.saveDir //temproary server location

FileUpload interceptor is a part of the defaultStack of interceptors

it willbe declared automatically, if we need we can overwrite.

The fileUpload interceptor takes two parameters (a) maximumSize - default  2MB and (b) allowedTypes - comma seperated mime types.

(action name="upload" class="com.tutorialspoint.struts2.uploadFile")
       (interceptor-ref name="basicStack")
       (interceptor-ref name="fileUpload")
           (param name="allowedTypes")image/jpeg,image/gif(/param)
       (/interceptor-ref)
    (result name="success")/success.jsp(/result)
       (result name="error")/error.jsp(/result)
   (/action)

The fileUplaod interceptor uses several default error message keys: uploading , file.too.large ,content.type.not.allowed
struts.messages.error.uploading  = A general error that occurs when the file could not be uploaded.
struts.messages.error.file.too.large = occurs when the uploaded file is too large as specified by maximumSize.
struts.messages.error.content.type.not.allowed = Occurs when the uploaded file does not match the expected content types specified.

You can override the text of these messages in WebContent/WEB-INF/classes/messages.properties resource files.

==================================================================================================

(s:bean name="com.mkyong.common.Person" var="personBean" /) bean name/package var/object
(s:property value="#personBean.name" /)

(s:property value="name" /)
will look for a name property in the value stack i.e. is a value retrieved by calling getName().
If you wanted to force it to use literal value "name", you will need to use the %{} syntax -
(s:property value="%{'name'}" /)
#variable is used to refer to a variable that does not exist on the value stack, but rather exists somewhere else on the action context. This could be variables created by using the (set) tag, or values in session scope etc.

%{} is OGNL's expression evaluation operator.

notice this wont work
(s:hidden name="no" value="#st.index")(/s:hidden)
but if I change it to
(s:hidden name="no" value="%{#st.index}")(/s:hidden)


Form Tags - Struts UI Tags
==========================
Simple UI Tags
Group UI Tags radio/checkbox
Select UI Tags select/double select/combo box/opt group

(s:head/)

 (s:div)Email Form(/s:div)
   (s:text name="Please fill in the form below:" /)
   (s:form action="hello" method="post" enctype="multipart/form-data")
   (s:hidden name="secret" value="abracadabra"/)
   (s:textfield key="email.from" name="from" /)
   (s:password key="email.password" name="password" /)
   (s:textarea key="email.body" name="email.body" /)
   (s:label for="attachment" value="Attachment"/)
   (s:file name="attachment" accept="text/html,text/plain" /)
   (s:token /)
   (s:submit key="submit" /)
   (/s:form)

 (s:form action="hello.action")
   (s:radio label="Gender" name="gender" list="{'male','female'}" /)
   (s:checkboxlist label="Hobbies" name="hobbies"  list="{'sports','tv','shopping'}" /)
   (/s:form)

The name attribute is mandatory for the radiobutton tag

"key" attribute is used to fetch the label for these controls from the property file.

"accept" paramter of the s:file tag to specify which file mime types are allowed to be uploaded.

The token tag generates an unique token which is used to find out whether a form has been double submitted.


AJAX Tags - DOJO framework
==========================
Include the Dojo Plugin- /WEB-INF/lib folder.
Add (%@ taglib prefix="sx" uri="/struts-dojo-tags" %) to your page.
struts2-dojo-plugin-2.2.3.jar

(sx:head /)
ajax calls will not work without the sx:head being initialized.

=) autocompleter
=) datetimepicker
=) div
=) tabbedpanel

(sx:autocompleter label="Favourite Colour" list="{'red','green','blue'}" /)

(sx:autocompleter size="1" name="state" list="listOfStates" showDownArrow="false" label="Choose state")(/sx:autocompleter)

(sx:datetimepicker name="deliverydate" label="Delivery Date" displayFormat="dd/MM/yyyy" /)

(sx:div href="%{#url}" delay="2000")  Initial Content      (/sx:div)

(sx:tabbedpanel id="tabContainer")
(sx:div label="Tab 1")Tab 1(/sx:div)
(sx:div label="Tab 2")Tab 2(/sx:div)
(/sx:tabbedpanel)

annotations:
===========
Zero Configuration

struts2-convention-plugin.jar =)//annotation jar
asm.jar
antlr.jar
commons-fileupload.jar
commons-io.jar
commons-lang.jar
commons-logging.jar
commons-logging-api.jar
freemarker.jar
javassist.jar
ognl.jar
struts2-core.jar
xwork-core.jar

@Namespace (Action Annotation)
@Result - (Action Annotation)
@Results - (Action Annotation)
@After - (Interceptor Annotation)
@Before - (Interceptor Annotation)
@BeforeResult - (Interceptor Annotation)
@ConversionErrorFieldValidator - (Validation Annotation)
@DateRangeFieldValidator - (Validation Annotation)
@DoubleRangeFieldValidator - (Validation Annotation)
@EmailValidator - (Validation Annotation)
@ExpressionValidator - (Validation Annotation)
@IntRangeFieldValidator - (Validation Annotation)
@RegexFieldValidator - (Validation Annotation)
@RequiredFieldValidator - (Validation Annotation)
@RequiredStringValidator - (Validation Annotation)
@StringLengthFieldValidator - (Validation Annotation)
@UrlValidator - (Validation Annotation)
@Validations - (Validation Annotation)
@CustomValidator - (Validation Annotation)
@Conversion - (Type Conversion Annotation)
@CreateIfNull - (Type Conversion Annotation)
@Element - (Type Conversion Annotation)
@Key - (Type Conversion Annotation)
@KeyProperty - (Type Conversion Annotation)
@TypeConversion - (Type Conversion Annotation)


@Namespace("/User")
@ResultPath(value="/")
@Result(name="success",location="pages/login.jsp")
@Results({
   @Result(name="success", location="/success.jsp"),
   @Result(name="input", location="/index.jsp")
})
@Action(value="Welcome", results={
@Result(name="success",location="pages/welcome_user.jsp")
})
@RequiredFieldValidator( message = "The name is required" )
@IntRangeFieldValidator(message = "Age must be in between 28 and 65",
                                      min = "29", max = "65")

Here’s how the scanning work
Scan the annotated classes which located at the packaged named “struts, struts2, action or actions“.
Next, scan the file which match either of the following criteria :
Implemented the com.opensymphony.xwork2.Action interface.
Extends the com.opensymphony.xwork2.ActionSupport class.
File name ends with Action (e.g UserAction, LoginAction).

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;
   }
}


------------------------------------------------------------
package com.mkyong.user.action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/User")
@ResultPath(value="/")
@Result(name="success",location="pages/login.jsp")
public class LoginAction extends ActionSupport{
}
(package name="user" namespace="/User" extends="struts-default")
(action name="Login")
(result)pages/login.jsp(/result)
(/action)
(/package)

---------------------------------------------------------------
package com.mkyong.user.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/User")
@ResultPath(value="/")
public class WelcomeUserAction extends ActionSupport{
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Action(value="Welcome", results={
@Result(name="success",location="pages/welcome_user.jsp")
})
public String execute() {
return SUCCESS;
}
}

(package name="user" namespace="/User" extends="struts-default")
   (action name="Welcome" class="com.mkyong.user.action.WelcomeUserAction")
(result name="SUCCESS")pages/welcome_user.jsp(/result)
   (/action)
(/package)
--------------------------------------------------------------------------------------------
@Namespace("/content")
public class Employee extends ActionSupport{
  ...
}

@Result(name="success", value="/success.jsp")
public class Employee extends ActionSupport{
 ...
}

@Results({
   @Result(name="success", value="/success.jsp"),
   @Result(name="error", value="/error.jsp")
})
public class Employee extends ActionSupport{
 ...
}

public class Employee extends ActionSupport{
   @After
   public void isValid() throws ValidationException {
      // validate model object, throw exception if failed
   }
   public String execute() {
      // perform secure action
      return SUCCESS;
   }
}

public class Employee extends ActionSupport{
   @Before
   public void isAuthorized() throws AuthenticationException {
      // authorize request, throw exception if failed
   }
   public String execute() {
      // perform secure action
      return SUCCESS;
   }
}

public class Employee extends ActionSupport{
   @BeforeResult
   public void isValid() throws ValidationException {
    // validate model object, throw exception if failed
   }
   public String execute() {
      // perform action
      return SUCCESS;
   }
}

public class Employee extends ActionSupport{
   @ConversionErrorFieldValidator(message = "Default message",key = "i18n.key", shortCircuit = true)
   public String getName() {
       return name;
   }
}

public class Employee extends ActionSupport{
   @DateRangeFieldValidator(message = "Default message", key = "i18n.key", shortCircuit = true,
   min = "2005/01/01", max = "2005/12/31")
   public String getDOB() {
       return dob;
   }
}

public class Employee extends ActionSupport{
   @DoubleRangeFieldValidator(message = "Default message",key = "i18n.key", shortCircuit = true,minInclusive = "0.123", maxInclusive = "99.987")
   public String getIncome() {
       return income;
   }
}

public class Employee extends ActionSupport{
   @EmailValidator(message = "Default message",
   key = "i18n.key", shortCircuit = true)
   public String getEmail() {
       return email;
   }
}

@ExpressionValidator(message = "Default message", key = "i18n.key",
shortCircuit = true, expression = "an OGNL expression" )

public class Employee extends ActionSupport{
   @IntRangeFieldValidator(message = "Default message",
   key = "i18n.key", shortCircuit = true,
   min = "0", max = "42")
   public String getAge() {
       return age;
   }
}

@RegexFieldValidator( key = "regex.field", expression = "yourregexp")
public class Employee extends ActionSupport{
   @RequiredFieldValidator(message = "Default message",
   key = "i18n.key", shortCircuit = true)
   public String getAge() {
       return age;
   }
}

public class Employee extends ActionSupport{
   @RequiredStringValidator(message = "Default message",
   key = "i18n.key", shortCircuit = true, trim = true)
   public String getName() {
       return name;
   }
}

public class Employee extends ActionSupport{
   @StringLengthFieldValidator(message = "Default message",
   key = "i18n.key", shortCircuit = true,
   trim = true, minLength = "5",  maxLength = "12")
   public String getName() {
       return name;
   }
}

public class Employee extends ActionSupport{
   @UrlValidator(message = "Default message",
   key = "i18n.key", shortCircuit = true)
   public String getURL() {
       return url;
   }
}

public class Employee extends ActionSupport{
  @Validations(
   requiredFields =
      {@RequiredFieldValidator(type = ValidatorType.SIMPLE,
      fieldName = "customfield",
      message = "You must enter a value for field.")},
   requiredStrings =
      {@RequiredStringValidator(type = ValidatorType.SIMPLE,
      fieldName = "stringisrequired",
      message = "You must enter a value for string.")}
   )
   public String getName() {
       return name;
   }
}


@CustomValidator(type ="customValidatorName", fieldName = "myField")
@Conversion()
   public class ConversionAction implements Action {
}

@CreateIfNull( value = true )
private List(User) users;

@Element( value = com.acme.User )
private List(User) userList;

@Key( value = java.lang.Long.class )
private Map(Long, User) userMap;

@KeyProperty( value = "userName" )
protected List(User) users = null;

@TypeConversion(rule = ConversionRule.COLLECTION,
converter = "java.util.String")
public void setUsers( List users ) {
   this.users = users;
}

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...