AJ (MCA 2nd) 2
AJ (MCA 2nd) 2
Foundation, it is used to create a web application based on servlet and JSP. It depends on the MVC
(Model View Controller) framework. Struts are thoroughly useful in building J2EE (Java 2 Platform,
Enterprise Edition) applications because struts take advantage of J2EE design patterns. Struts follows
these J2EE design patterns including MVC and JSP custom tag libraries. In struts, the composite view
manages the layout of its sub-views and can implement a template, making persistent look and feel
easier to achieve and customize across the entire application. A composite view is made up by using
other reusable sub-views such that a small change that happens in a sub-view is automatically
updated in every composite view. Struts consist of a set of custom tag libraries. Struts also support
utility classes.
The main purpose of the struts framework is to provision separation of concerns between the business
logic and the presentation logic (view), making it easier to manage and develop large-scale web
applications.
Features of Struts
Struts have the following features:
Struts encourages good design practices and modeling because the framework is designed
with “time-proven” design patterns.
Struts is almost simple, so easy to learn and use.
It supports many convenient features such as input validation and internationalization.
It takes much of the complexity out as instead of building your own MVC framework, you
can use struts.
Struts is very well integrated with J2EE.
Struts has large user community.
It is flexible and extensible; it is easy for the existing web applications to adapt the struts
framework.
Struts provide good tag libraries.
It allows capturing input form data into JavaBean objects called Action forms.
It also hands over standard error handling both programmatically and declaratively.
Working of Struts:
Basic Architecture of MVC: Model View Controller or MVC as it is popularly called, is a software
design pattern for developing web applications. A Model View Controller pattern is made up of the
following three parts −
Model − The lowest level of the pattern which is responsible for maintaining data.
View − This is responsible for displaying all or a portion of the data to the user.
Controller − Software Code that controls the interactions between the Model and View.
MVC is popular as it isolates the application logic from the user interface layer and supports
separation of concerns. Here the Controller receives all requests for the application and then works
with the Model to prepare any data needed by the View. The View then uses the data prepared by the
Controller to generate a final presentable response. The MVC abstraction can be graphically
represented as follows.
The Model
The model is responsible for managing the data of the application. It responds to the request from the
view and it also responds to instructions from the controller to update itself.
The View
It means presentation of data in a particular format, triggered by a controller's decision to present the
data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with
AJAX technology.
The Controller
The controller is responsible for responding to the user input and perform interactions on the data
model objects. The controller receives the input, it validates the input and then performs the business
operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC
methodology within Struts2.
After selecting Dynamic Web Project, press Next, in next screen provide the name of the project.
Enter the name of the project as StrutsDBExample and click on Finish as shown below.
Step 3 : Add jar files to the classpath of Project
Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder.Following jar files
should be added to the project build path for successful deployment of struts project :
Copy all the tld files to WEB-INF folder and make the entry of these tld files in web.xml file.
Now we have to configure ActionServlet of struts with web.xml.The first page that will be called in
the login application is the login.jsp page. This configuration should be done
in web.xml as <welcome-file-list> .
Following xml shows how to configure struts in web.xml.
web.xml
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
</web-app>
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
}
if (lastName == null || lastName.length() < 1) {
errors.add("lastName", new ActionMessage("error.lastName.required"));
}
if (userName == null || userName.length() < 1) {
errors.add("userName", new ActionMessage("error.userName.required"));
}
if (password == null || password.length() < 1) {
errors.add("password", new ActionMessage("error.password.required"));
}
if (email == null || email.length() < 1) {
errors.add("email", new ActionMessage("error.email.required"));
}
if (phone == null || phone.length() < 1) {
errors.add("phone", new ActionMessage("error.phone.required"));
}
return errors;
}
}
Inside the validate method, we will check whether all field is entered, If not the corresponding error
message is displayed to the user. The error messages are configured in
the ApplicationResource.properties file.
The validate method in the LoginForm class is called when the Form is submitted. If any errors are
found then the control is returned back to the input page where the errors are displayed to the user.
The input page is configured in the action tag of struts-configuration file. <html:errors/> tag is used to
display the errors in the jsp page.
package com.jwt.struts.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
try {
try {
Statement st = con.createStatement();
int value = st
.executeUpdate("INSERT INTO
USER_DETAILS(FIRST_NAME,LAST_NAME,USER_NAME,PASSWORD,EMAIL,PHONE) "
+ "VALUES('"
+ firstName
+ "','"
+ lastName
+ "','"
+ userName
+ "','"
+ password
+ "','"
+ email + "','" + phone + "')");
System.out.println("1 row affected" + value);
} catch (SQLException ex) {
System.out.println("SQL statement is not executed!" + ex);
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.jwt.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.jwt.struts.dao.UserRegisterDAO;
import com.jwt.struts.form.UserRegisterForm;
}
}
The execute() method contains the business logic of the application. Here first we typecast
the ActionForm object to UserRegisterForm, so that we can access the form variables using the getter
and setter methods. If all fields are saved to database then we forward the user to the success.jsp page.
These configuration has been done in struts-config.xml file which is given below.
Step 8 : Create struts-config.xml file :
Create struts-config.xml file inside WEB-INF folder of the project.
struts-config.xml
<struts-config>
<form-beans>
<form-bean name="registerForm" type="com.jwt.struts.form.UserRegisterForm" />
</form-beans>
<action-mappings>
<action input="/login.jsp" name="registerForm" path="/register"
type="com.jwt.struts.action.UserRegisterAction">
<forward name="success" path="/success.jsp" />
</action>
</action-mappings>
</struts-config>
Hibernate: Hibernate is the most used Object/Relational persistence and query service and It is
licensed under the open-source GNU Lesser General Public License (LGPL). Hibernate not only see
the mapping from Java classes to database tables but also provides data query and recovery facilities.
Hibernate is free to download.
This Hibernate Tutorial is tailored for both beginners and experienced professionals, It helps you to
use Hibernate to create database-based web applications in simple and easy steps and learn
fundamental and advanced concepts of Hibernate including setting up Hibernate, mapping Java
classes to database tables, performing basic and advanced database operations, utilizing Hibernate
Query Language (HQL), and more.
Hibernate Framework: Hibernate is a Java framework, licensed under the open-source GNU Lesser
General Public License (LGPL), and is available for free download. Developed in 2001 by Gavin
King, Hibernate was introduced as a groundbreaking alternative to the EJB2-style entity bean
approach. By mapping Java objects to database tables, it streamlines data persistence and retrieval
without the need for complex SQL queries. With features like automatic transaction management and
caching, Hibernate simplifies and optimizes database interactions, making it an indispensable
framework for efficient data management in Java applications.
JDBC
JDBC (Java Database Connectivity) provides a set of Java APIs to access the relational databases
from the Java program. Java APIs enable programs to execute SQL statements and interact with any
SQL database.
JDBC gives a flexible architecture to write a database-independent web application that can execute
on different platforms and interact with different DBMS without any change.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access and It is a programming
technique that maps the object to the data stored in the database.
ORM Tool
The ORM tool internally uses the JDBC API to interact with the database.
JPA
Java Persistence API (JPA) is a Java specification that provides specific functionality and is a
standard for ORM tools.
javax.persistence package contains the JPA classes and interfaces.
CREATING POJO FILES: POJO, short for Plain Old Java Object, is a standard Java object
with minimal restrictions imposed by the Java Language Specification. It operates without
requiring any specific classpath. These objects serve as intermediaries for communication
between different layers or components within distributed systems, encapsulating data and
related behavior. Typically, POJOs feature private member variables alongside public getter
and setter methods, with additional methods for data manipulation if needed.
Example
// Student POJO class to represent entity Student
public class Student
{
// default field
String name;
// public field
public String id;
// private field
private double score;
In the above example, the database entity represents the POJO, i.e. the POJO class has the
same members as the database entity.
Using POJO Class in Java Program
To use a POJO class in a Java program, you need to follow the below steps:
Create a POJO class: Define a POJO class with private fields, public getters, and setters.
Instantiate the POJO class: Create an object of the POJO class using the new operator.
Set values: Set the values of the POJO class fields using the setter methods.
Get values: Retrieve the values of the POJO class fields using the getter methods.
Here is an example of how to use a POJO class in a Java program:
// Define a POJO class named "Person"
public class Person {
private String name;
private int age;
public Person() {
// Default constructor
}
Hibernate Lifecycle
As depicted from the above media one can co-relate how they are plotted in order to plot
better in our mind. Now we will be discussing the states to better interpret hibernate lifecycle.
It is as follows:
State 1: Transient State
The transient state is the first state of an entity object. When we instantiate an object of
a POJO class using the new operator then the object is in the transient state. This object is not
connected with any hibernate session. As it is not connected to any Hibernate Session, So this
state is not connected to any database table. So, if we make any changes in the data of the
POJO Class then the database table is not altered. Transient objects are independent of
Hibernate, and they exist in the heap memory.
//Persistent State
session.save(e);
State 3: Detached State
For converting an object from Persistent State to Detached State, we either have to close the
session or we have to clear its cache. As the session is closed here or the cache is cleared, then
any changes made to the data will not affect the database table. Whenever needed, the
detached object can be reconnected to a new hibernate session. To reconnect the detached
object to a new hibernate session, we will use the following methods as follows:
merge()
update()
load()
refresh()
save()
update()
Following are the methods used for the detached state :
session.detach(e);
session.evict(e);
session.clear();
session.close();
// Persistent State
session.save(e);
// Detached State
session.close();
State 4: Removed State
In the hibernate lifecycle it is the last state. In the removed state, when the entity object is
deleted from the database then the entity object is known to be in the removed state. It is done
by calling the delete() operation. As the entity object is in the removed state, if any change
will be done in the data will not affect the database table.
Note: To make a removed entity object we will call session.delete().
// Transient State
Employee e = new Employee();
Session s = sessionfactory.openSession();
e.setId(01);
// Persistent State
session.save(e)
// Removed State
session.delete(e);
For this example we’ve created table books with fields book_name and book_author inside
the jelasticDb database.
3. Modify the following configuration files of your web-application:
hibernate.cfg.xml
2
<hibernate-configuration>
3 <session-factory>
<property
4 name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property
5 name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
6 name="hibernate.connection.url">jdbc:mysql://mysql{node_id}.{your_env_name}.
{hoster_domain}:3306/jelasticDb</property>
7 <property name="hibernate.connection.username">jelastic</property>
<property name="hibernate.connection.password">jelastic</property>
8 <property name="hibernate.current_session_context_class">thread</property>
<mapping resource="com/Testdata.hbm.xml"/>
9 </session-factory>
1 </hibernate-configuration>
0
1
1
hibernate.revenge.xml
1 <hibernate-reverse-engineering>
2 <schema-selection match-catalog="jelasticDb"/>
3 <table-filter match-name="books"/>
4 </hibernate-reverse-engineering>
For the next step we’ve used reverse engineering mechanism and got 2 files in our web-
project:
Books.java
Books.hbm.xml
Also you need to create the HibernateUtil.java file but do not need to change it.
4. Create a simple Java method, which will add a new row to the books table in our database:
1
public void addBook(){
2
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
3
s.beginTransaction();
4
Books book = new Books("romeo and juliet","william shakespeare ");
5
s.save(book);
6
s.getTransaction().commit();
7
}