Thursday, 10 October 2013



Compare Two Date of Util Type

A suite of utilities surrounding the use of the Calendar and Date object.
DateUtils contains a lot of common methods considering manipulations of Dates or Calendars. Some methods require some extra explanation. The truncate, ceiling and round methods could be considered the Math.floor(), Math.ceil() or Math.round versions for dates This way date-fields will be ignored in bottom-up order. As a complement to these methods we've introduced some fragment-methods. With these methods the Date-fields will be ignored in top-down order. Since a date without a year is not a valid date, you have to decide in what kind of date-field you want your result, for instance milliseconds or days.


If you really want to use the java.util.Date, you would do something like this:


Saturday, 31 August 2013

Struts2 Best Interview Question in java

Struts2 framework is a combined work of webwork and Struts community. Previously it was known as webwork2 which later on named as Struts2. It uses Inversion Of Control (IoC) and architectural pattern MVC(Model-View-Controller), It also enablesAspect-Oriented Programming (AOP)usingInterceptors. As Struts2 has built in support of AJAX, it is also ideally suitable for developing web 2.0 application.
Model:Action
View:JSP / Velocity Template / Freemaker
Controller:StrutsPrepareandExecuteFilter
Struts2 is a pull-MVC framework. i.e. the data that is to be displayed to user has to be pulled from the Action.
Struts2 Architectural:It leverages the standard JEE technologies such as Java Filters, JavaBeans, ResourceBundles, Locales, XML etc in its architecture.

1)What is Struts?
Ans:The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide the Model and the View.

The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

2) What is the advantage of having a POJO class as an action?
Ans: As mentioned in the first question, the POJO classis light weight and easy to test with frameworks like Junit. Moreover, there is no need to create separate Action Forms to hold the values from the source web page.

3) How can one integrate Spring IoC with Struts 2?
Ans: Struts 2 comes with support for Spring and Spring can be used to inject beans to various \classes. It can also be used to inject properties to the action class of struts 2..


4)What is Action Class?
Ans:The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

5)Mainclasses which are used instrutsapplication?
Ans:List of Main Classes
Action servlet: it’sa back-bone of web application it’s a controller class responsible for handling the entire request.
Action Class: using Action classes all the business logic is developed us call model of the application also.
Action Form: it’s a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is automatically populated onthe server side with data entered  from a form on the client side.
Action Mapping: using this class we do the mapping between object and Action.

ActionForward: this class in Struts is used to forward the result from controller to destination

6)What are Pull-MVC and push-MVC based architecture ?Which architecture does Struts2 follow ?
Ans:Pull-MVC and Push-MVC are better understood with how the view layer is getting data i.e.Model to render. In case of Push-MVC the data(Model) is constructed and given to the view layer by the Controllers by putting it in the scoped variables like request or session. Typical example is Spring MVC and Struts1. Pull-MVC on the other hand puts the model data typically constructed in Controllers are kept in a common place i.e. in actions, which then gets rendered by view layer.Struts2 is a Pull-MVC based architecture, in which all data is stored in Value Stack and retrieved by view layer for rendering

7)Are Interceptors in Struts2 thread safe ?
Ans:No, This is not Thread Safe, Interceptors are shared between requests, so thread issues will come if not taken care of.

8)What is the relation between ValueStack and OGNL ?
Ans: ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean through which the data in the ValueStack is manipulated.



9) How Will Run the Execute Method in Action Class?

Ans Action Servelet will run the execute method in Struts,as it is the Main controller of Strus



10) Why We Use Resource Bundle in Struts2?

Ans:To use resource bundle to retrieve the message from properties file,


Sunday, 12 May 2013

strus2 Hello World Example

Before we starts with our first Hello World Struts 2 Example, we will need few tools.
  1. JDK 1.5 above
  2. Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc)
  3. Eclipse 
  4. Apache Struts2 JAR files. Following are the list of JAR files required for this application.
    • commons-logging-1.0.4.jar
    • freemarker-2.3.8.jar
    • ognl-2.6.11.jar
    • struts2-core-2.0.12.jar
    • xwork-2.0.6.jar
    Note that depending on the current version of Struts2, the version number of above jar files may change.

Our Goal

Our goal is to create a basic Struts2 application with a Login page. User will enter login credential and if authenticated successfully she will be redirected to a Welcome page which will display message ” Howdy, <username>…!“. If user is not authenticated, she will be redirected back to the login page.
struts2-application-login-page

Getting Started

Let us start with our first Struts2 based application.
 Start Eclipse and goto Create the Dynamic Web Project in the  Project wizard screen.
Dynamic Web Project in Eclipse
After selecting Dynamic Web Project, press Next.
Eclipse Struts2 Project
Write the name of the project. For example StrutsHelloWorld. .
Eclipse Project Explorer: Struts2 Example
Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.
struts2-webinf-jars

Mapping Struts2 in WEB.xml

As discussed in the previous article (Introduction to Struts2), the entry point of Struts2 application will be the Filter define in deployment descriptor (web.xml). Hence we will define an entry of org.apache.struts2.dispatcher.FilterDispatcher class in web.xml.
Open web.xml file which is under WEB-INF folder and copy paste following code.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Struts2 Application</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>
</web-app>
The above code in web.xml will map Struts2 filter with url /*. The default url mapping for struts2 application will be /*.action. Also note that we have define Login.jsp as welcome file.
Note: The FilterDispatcher filter is deprecated since Struts version 2.1.3. If you are using latest version of Struts2 ( > 2.1.3) use StrutsPrepareAndExecuteFilter class instead.
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

The Action Class

We will need an Action class that will authenticate our user and holds the value for username and password. For this we will create a package net.deepak.struts2 in the source folder. This package will contain the action file.

Create a class called LoginAction in net.viralpatel.struts2 package with following content.
package net.deepak.struts2;
public class LoginAction {
    private String username;
    private String password;
    public String execute() {
        if (this.username.equals("admin")
                && this.password.equals("admin123")) {
            return "success";
        } else {
            return "error";
        }
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
Note that, above action class contains two fields, username and password which will hold the values from form and also contains an execute() method that will authenticate the user. In this simple example, we are checking if username is admin and password is admin123.
Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method.

The ResourceBundle

ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.
ResourceBundle comes handy when we want to add Internationalization (I18N) support to an application.
We will define an ApplicationResources.properties file for our application. This property file should be present in WEB-INF/classes folders when the source is compiled. Thus we will create a source folder called resources and put the ApplicationResources.properties file in it.
To create a source folder, right click on your project in Project Explorer and select New -> Source Folder.
struts2-resource-folder
Specify folder name resources and press Finish.
Create a file ApplicationResources.properties under resources folder.
struts-2-application-resources-properties
Copy following content in ApplicationResources.properties.
label.username= Username
label.password= Password
label.login= Login

The JSP

We will create two JSP files to render the output to user. Login.jsp will be the starting point of our application which will contain a simple login form with username and password. On successful authentication, user will be redirected to Welcome.jsp which will display a simple welcome message.
Create two JSP files Login.jsp and Welcome.jsp in WebContent folder of your project. Copy following content into it.

Login.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application | ViralPatel.net</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="login.action" method="post">
    <s:textfield name="username" key="label.username" size="20" />
    <s:password name="password" key="label.password" size="20" />
    <s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

Welcome.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>
<body>
    <h2>Howdy, <s:property value="username" />...!</h2>
</body>
</html>
Note that we have used struts2 <s:> tag to render the textboxes and labels. Struts2 comes with a powerful built-in tag library to render UI elements more efficiently.

The struts.xml file

Struts2 reads the configuration and class definition from an xml file called struts.xml. This file is loaded from the classpath of the project. We will define struts.xml file in the resources folder. Create file struts.xml in resources folder.
struts2-struts-xml
Copy following content into struts.xml.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <constant name="struts.enable.DynamicMethodInvocation"
        value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources"
        value="ApplicationResources" />
    <package name="default" extends="struts-default" namespace="/">
        <action name="login"
            class="net.deepak.struts2.LoginAction">
            <result name="success">Welcome.jsp</result>
            <result name="error">Login.jsp</result>
        </action>
    </package>
</struts>
Note that in above configuration file, we have defined Login action of our application. Two result paths are mapped with LoginAction depending on the outcome of execute() method. If execute() method returns success, user will be redirected to Welcome.jsp else to Login.jsp.
Also note that a constant is specified with name struts.custom.i18n.resources. This constant specify the resource bundle file that we created in above steps. We just have to specify name of resource bundle file without extension (ApplicationResources without .properties).
Our LoginAction contains the method execute() which is the default method getting called by Sturts2. If the name of method is different, e.g. authenticate(); then we should specify the method name in <action> tag.
<action name="login" method="authenticate"
    class="net.viralpatel.struts2.LoginAction">

Almost Done

We are almost done with the application. You may want to run the application now and see the result yourself. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows -> Show View -> Server. Right click in this view and select New -> Server and add your server details.
To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)
But there is one small problem. Our application runs perfectly fine at this point. But when user enters wrong credential, she is redirected to Login page. But no error message is displayed. User does not know what just happened. A good application always show proper error messages to user. So we must display an error message Invalid Username/Password. Please try again when user authentication is failed.

Final Touch

To add this functionality first we will add the error message in our ResourceBundle file.
Open ApplicationResources.properties and add an entry for error.login in it. The final ApplicationResources.properties will look like:
label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.
Also we need to add logic in LoginAction to add error message if user is not authenticated. But there is one problem. Our error message is specified in ApplicationResources.properties file. We must specify key error.login in LoginAction and the message should be displayed on JSP page.
For this we must implement com.opensymphony.xwork2.TextProvider interface which provides method getText(). This method returns String value from resource bundle file. We just have to pass the key value as argument to getText() method. The TextProvider interface defines several method that we must implement in order to get hold on getText() method. But we don’t want to spoil our code by adding all those methods which we do not intend to use. There is a good way of dealing with this problem.
Struts2 comes with a very useful class com.opensymphony.xwork2.ActionSupport. We just have to extend our LoginAction class with this class and directly use methods such as getText(), addActionErrors() etc. Thus we will extend the LoginAction class with ActionSupport class and add the logic for error reporting into it. The final code in LoginAction must look like:
package net.deepak.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
    private String username;
    private String password;
    public String execute() {
        if (this.username.equals("admin")
                && this.password.equals("admin123")) {
            return "success";
        } else {
            addActionError(getText("error.login"));
            return "error";
        }
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}
And that’s it. Our first Hello World Struts2 Application is now ready.

That’s All Folks

Execute the application in Eclipse and run it in your favorite browser.
Login page
struts2-application-login-page
Welcome page
struts2-welcome-page
Login page with error
struts2-login-page-error

Thursday, 11 April 2013

Struts2 and Hibernate with Spring Intergration

                               Integration of Struts2 with Spring and Hibernate

My this Post is regarding the integration of struts 2 with spring and  hibernate. Struts 2 is a pull-MVC framework. i.e. the data that is to be displayed to user has to be pulled from the Action.Struts2 supports annotation based configurations which are easy to create and more intuitive.Hibernate ORM (Hibernate in short) is an object-relational mapping library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.for Integration of Hibernate with Struts we have have used the spring .because Spring helps development teams everywhere build simple, portable,. fast and ... Keep it portable – Spring-based apps run anywhere the JVM Does

Struts 2 <--(ContextLoaderListener)--> Spring <--(LocalSessionFactoryBean) --> Hibernate

Our Goal

Our goal is to create a basic Struts2+spring+hibernate  application with a Add Student  page. User will enter Student data after the click on Save form will submitted the form data will be saved to student table

Getting Started

Let us start with our first Struts2 +Hibernate+Spring  based application.
Open Eclipse and goto File -> New -> Project and select Maven Project in the New Maven wizard screen

Choose the Default Work space Directory Location and Select Create a Simple Project. then Click on the Next Screen.
 
 

 The Next Option

Enter the Group Id. group Id is Your application Project Package Structure. and the Artifact Id is the 
Project  Name and Select Package as War. Fill the Name and Description for your Application. and remain other filled as Empty then Click on the Finish

 

Your Project Setup is ready for the Development 

below screen is related the final Structure of your  Application in the src/main/java/ is the package and all java file and src/main/web apps/ it will have all the .jsp pages, css, jquery  and image file . and src/main/resources/ it have all classpath file,like .xml file spring and struts configuration files,and database properties file and it has also hibernate configuration file

Root Dirctroy have the pom(Project Object Model).xml file

 

Firstly Create the com.java.tutions.model package create the pojo(plain old java object)  class of Student Entity.we used the Annotation configuration for the hibernate. Create DAO Interface and DAO Implementation class under the com.java.tutions.dao package. for Handling the database Operation using Hibernate. Final Service Interface and Service Interface's implementation class for the  handling the Hibernate Transaction.





Stereotype Action 
Stereotype annotations are markers for any class that fulfills a role within an application. This helps remove, or at least greatly reduce, the Spring XML configuration required for these components.
This Anotations is for the of Action Class

Action Class 

We will need an Action class that will  our Student Data and holds the value for student model For this we will create a package com.java.tutions.action. in the java Folder. This package will contain the action file.Action also Implement the ModelDriven Interface.

Create a class called StudentAction in com.java.tutions.action. package with following content.

Student Form

We will create one JSP files to render the output to user. webapp/student/addStudent.jsp. it will be the starting point of our application which will contain a simple add form with title and name surname,password,email.

webapp/student/addStudent.jsp



WEB-INF/web.xml file
Configure the Web Application Deployment Descriptor (web.xml) file to integrate Struts2 to your web project.

Create Stuts.xml File
Struts2 reads the configuration and class definition from an xml file called struts.xml. This file is loaded from the classpath of the project. We will define struts.xml file in the resources folder. Create file struts.xml in resources folder.
resources/struts.xml file



Create the Configuration File Like This



DataSource.xml

this file read the database.properties file for creating the datasoruce for the database operation


HibernateSessionFactory.xml

this file provide the sessionfacory object and the transaction object
Database.property File
This file contains all the database credential like dialect ,and username,password,database name

SpringBean.xml File


Pom.xml

POM stands for "Project Object Model". It is an XML representation of a Maven project held in a file named pom.xml. this file contains all dependency and repository of the project