Struts Validation Framework tutorial with example.

@Author:M.Lakhmikar Reddy
Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.

Introduction to Struts Validation Framework

One of the important features of Struts framework is Struts Validation framework that performs validation on incoming form data. Validation framework was introduced by David Winterfeldt as an external plugin to Struts framework. It’s functionality has since been split so that validator can serve as the basis for a independant component and is now part of Jakarta Commons.

The Struts framework’s simple validation interface alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.

In order to do form validation without Validator framework, one has to use validate() method of the form bean (ActionForm class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).

Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.

Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.

The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

Using the Validator framework involves enabling the Validator plug-in, configuring Validator’s two configuration files, and creating Form Beans that extend the Validator’s ActionForm subclasses. The following sections explain in detail how to configure and use Validator.



Create a Struts project

Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: Creating Struts application using Eclipse and create a struts project.

Create Form Beans

struts validator form bean
Create a form bean in your project called CustomerForm and copy following code in it.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package net.viralpatel.struts.validation.form;
import org.apache.struts.validator.ValidatorForm;
public class CustomerForm extends ValidatorForm {
private String name;
private String telephone;
private String email;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

We will use this validator plugin to validate this form. Note that the form bean is extended from class ValidatorForm and not ActionForm as we generally do in Struts project.

Add Validator Plug-in in struts-config.xml

In order to use Validator in our project we need to configure it in struts-config.xml file. For this add following code in your struts-config.xml file.

1
2
3
4
5
6
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml" />
plug-in>

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file’s path should be specified by use of a Web application-relative path, as shown in the previous example.

Define validations for the form

validation.xml file struts validator framework

Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
xml version="1.0" encoding="UTF-8" ?>
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
<form-validation>
<global>
<constant>
<constant-name>telephoneFormatconstant-name>
<constant-value>^\d{5,10}$constant-value>
constant>
global>
<formset>
<form name="CustomerForm">
<field property="name" depends="required">
<arg key="label.name" />
field>
<field property="age" depends="required, integer, intRange">
<arg0 key="label.age" />
<arg1 key="${var:min}" resource="false"/>
<arg2 key="${var:max}" resource="false"/>
<var>
<var-name>minvar-name>
<var-value>1var-value>
var>
<var>
<var-name>maxvar-name>
<var-value>125var-value>
var>
field>
<field property="telephone" depends="required, mask">
<arg key="label.telephone" />
<arg1 key="label.telephone" />
<var>
<var-name>maskvar-name>
<var-value>${telephoneFormat}var-value>
var>
field>
<field property="email" depends="email">
<arg0 key="label.email" />
<arg1 key="label.email" />
field>
form>
formset>
form-validation>

In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..

Also you can define constants that can be reused in the validation xml using global constants tag.

Struts-config.xml entry for the action

Following is the entry in struts-config.xml file which maps the Action to our Validator form.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<form-beans>
<form-bean name="CustomerForm"
type="net.viralpatel.struts.validation.form.CustomerForm" />
form-beans>
...
...
...
<action-mappings>
...
<action path="/customer" name="CustomerForm" validate="true"
input="/index.jsp"
type="net.viralpatel.struts.validation.action.CustomerAction">
<forward name="success" path="/Customer.jsp" />
<forward name="failure" path="/index.jsp" />
action>
...
action-mappings>

Configuring ApplicationResources.properties

Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
label.name= Name
label.email= Email
label.telephone= Telephone
label.age= Age
# general error msgs
errors.header=<font size="2"><UL>
errors.prefix=<LI><span style="color: red">
errors.suffix=span>LI>
errors.footer=UL>font>
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.

Create JSP to display the form

Create a JSP file called index.jsp and copy following content in it.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
<title>Struts Validation Framework example.title>
head>
<body>
<html:errors />
<html:javascript formName="CustomerForm" />
<html:form action="/customer">
<bean:message key="label.name" />
<html:text property="name">html:text>
<br />
<bean:message key="label.age" />
<html:text property="age">html:text>
<br />
<bean:message key="label.email" />
<html:text property="email">html:text>
<br />
<bean:message key="label.telephone" />
<html:text property="telephone">html:text>
<br />
<html:submit value="Submit">html:submit>
html:form>
body>
html>

Running the application

We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.
struts validator form screen

Enter any invalid value in the form and press submit.

struts-validator-form-screen2

Load properties file in java

Class c =this.getClass();
ClassLoader cl = c.getClassLoader();
InputStream in = cl.getResourceAsStream("abc.properties");
Properties pop=new Properties();
pop.load(in);
in.close();
String driver = pop.getPropert("driver")

Diffrence between Struts1.x vs Struts 2.x

@Author:M.Lakshmikar Reddy

Struts 1x vs 2x


Feature

Struts 1

Struts 2

Action classes

Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.

An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.

Threading Model

Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.

Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

Servlet Dependency

Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked.

Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

Testability

A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1.

Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.

Harvesting Input

Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans.

Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects.

Expression Language

Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.

Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

Binding values into views

Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.

Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.

Type Conversion

Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance.

Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

Validation

Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects.

Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

Control Of Action Execution

Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle.

Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.


@

JDBC interview questions

JDBC Questions

@author:M.Lakshmikar Reddy

1.What is the JDBC?

Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers.


2.What are the new features added to JDBC 4.0?

The major features added in JDBC 4.0 include :

  • Auto-loading of JDBC driver class

  • Connection management enhancements

  • Support for RowId SQL type

  • DataSet implementation of SQL using Annotations

  • SQL exception handling enhancements

  • SQL XML support

Learn more about JDBC 4.0 features


3.Explain Basic Steps in writing a Java program using JDBC?

JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database :

  • Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded).

  • Open the connection to database which is then used to send SQL statements and get results back.

  • Create JDBC Statement object. This object contains SQL query.

  • Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.

  • Process the result set.

  • Close the connection.


4.Exaplain the JDBC Architecture.

The JDBC Architecture consists of two layers:

  • The JDBC API, which provides the application-to-JDBC Manager connection.

  • The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the Java application is shown in Figure 1.


Figure 1: JDBC Architecture


5.What are the main components of JDBC ?

The life cycle of a servlet consists of the following phases:

  • DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

  • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.

  • Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.

  • Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.

  • ResultSet: The ResultSet represents set of rows retrieved due to query execution.


6.How the JDBC application works?

A JDBC application can be logically divided into two layers:

1. Driver layer

2. Application layer

  • Driver layer consists of DriverManager class and the available JDBC drivers.

  • The application begins with requesting the DriverManager for the connection.

  • An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer.

  • The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.


Figure 2: JDBC Application


7


.How do I load a database driver with JDBC 4.0 / Java 6?

Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.


8.What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.


9.What does the connection object represents?

The connection object represents communication context, i.e., all communication with database is through connection object only.


10.What is Statement ?

Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects.
Through the connection object we create statement kind of objects.

Statement stmt = conn.createStatement();

This method returns object which implements statement interface.


People who read this, also read:-

11.What is PreparedStatement?

A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");

pstmt.setBigDecimal(1, 153833.00);

pstmt.setInt(2, 110592);

Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.




12.What is the difference between a Statement and a PreparedStatement?

Statement

PreparedStatement

A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database.

A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.

Statement has to verify its metadata against the database every time.

While a prepared statement has to verify its metadata against the database only once.

If you want to execute the SQL statement once go for STATEMENT

If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries


13.What are callable statements ?

Callable statements are used from JDBC application to invoke stored procedures and functions.


14.How to call a stored procedure from JDBC ?

PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class.

The following line of code illustrates this:

CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");

Here conn is an instance of the Connection class.


15.What are types of JDBC drivers?

There are four types of drivers defined by JDBC as follows:

  • Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.

  • Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.

  • Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.

  • Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.

Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.

16.Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.


17.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.


18.Which is the right type of driver to use and when?

  • Type I driver is handy for prototyping

  • Type III driver adds security, caching, and connection control

  • Type III and Type IV drivers need no pre-installation

Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more about JDBC drivers.


19.What are the standard isolation levels defined by JDBC?

The values are defined in the class java.sql.Connection and are:

  • TRANSACTION_NONE

  • TRANSACTION_READ_COMMITTED

  • TRANSACTION_READ_UNCOMMITTED

  • TRANSACTION_REPEATABLE_READ

  • TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels.


20.What is resultset ?

The ResultSet represents set of rows retrieved due to query execution.

ResultSet rs = stmt.executeQuery(sqlQuery);


2

People who read this, also read:-

1.What are the types of resultsets?

The values are defined in the class java.sql.Connection and are:

  • TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can be advanced only in the forward direction.

  • TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.

  • TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

Note: A TYPE_FORWARD_ONLY resultset is always insensitive.


22.What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?

TYPE_SCROLL_INSENSITIVE

TYPE_SCROLL_SENSITIVE

An insensitive resultset is like the snapshot of the data in the database when query was executed.

A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.

After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive.

After we obtain the resultset if the data is modified then such modifications are visible through resultset.

Performance not effected with insensitive.

Since a trip is made for every ‘get’ operation, the performance drastically get affected.


22.What is rowset?

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification mechanism.


2


4.What are the different types of RowSet ?

There are two types of RowSet are there. They are:

  • Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.

  • Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.


25.What is the need of BatchUpdates?

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip.


26.What is a DataSource?

A DataSource object is the representation of a data source in the Java programming language. In basic terms,

  • A DataSource is a facility for storing data.

  • DataSource can be referenced by JNDI.

  • Data Source may point to RDBMS, file System , any DBMS etc..


2


7.What are the advantages of DataSource?

The few advantages of data source are :

  • An application does not need to hardcode driver information, as it does with the DriverManager.

  • The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details.

  • The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.


28.What is connection pooling? what is the main advantage of using connection pooling?

A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested..