Search

Struts 2 CRUD example

       In this example you will see how to perform Create, Read, Update and Delete (CRUD) operations. I will be explaining only the points that is not covered in the previous examples.
Let's get started, the screen shot of the example is shown below. The directory structure of the example.
Let's see the flow from the back-end.
The UserDAOImpl has four methods to perform the various CRUD operation
package com.vaannila.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.googlecode.s2hibernate.strutsplugin.annotations.SessionTarget;
importcom.googlecode.s2hibernate.strutsplugin.annotations.TransactionTarget;
import com.vaannila.domain.User;

public class UserDAOImpl implements UserDAO {

@SessionTarget
Session session;

@TransactionTarget
Transaction transaction;

/**
* Used to save or update a user.
*/
@Override
public void saveOrUpdateUser(User user) {
try {
session.saveOrUpdate(user);
catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}

/**
* Used to delete a user.
*/
@Override
public void deleteUser(Long userId) {
try {
User user = (User) session.get(User.class, userId);
session.delete(user);
catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}

/**
* Used to list all the users.
*/
@SuppressWarnings("unchecked")
@Override
public List<User> listUser() {
List<User> courses = null;
try {
courses = session.createQuery("from User").list();
catch (Exception e) {
e.printStackTrace();
}
return courses;
}

/**
* Used to list a single user by Id.
*/
@Override
public User listUserById(Long userId) {
User user = null;
try {
user = (User) session.get(User.class, userId);
catch (Exception e) {
7e.printStackTrace();
7}
7return user;
7}
7 
7}
The org.hibernate.Session and org.hibernate.Transaction objects are injected using the Full Hibernate Plug-in 4 GA.
The User domain object with the JPA annotations to create the USER table.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USER")
public class User {

private Long id;
private String name;
private String gender;
private String country;
private String aboutYou;
private Boolean mailingList;

@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}

@Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

@Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}

@Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}

}
Our UserAction implements ModelDriven interface, so the domain object User will be exposed as a model object. Use ActionContext.getContext().get(ServletActionContext. HTTP_REQUEST) method to access the HttpServeletRequest object in action.
package com.vaannila.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.strutsServletActionContext;

import com.opensymphony.xworkActionContext;
import com.opensymphony.xworkActionSupport;
import com.opensymphony.xworkModelDriven;
import com.vaannila.dao.UserDAO;
import com.vaannila.dao.UserDAOImpl;
import com.vaannila.domain.User;

public class UserAction extends ActionSupport implements ModelDriven<User> {

private static final long serialVersionUID = -6659925652584240539L;

private User user = new User();
private List<User> userList = new ArrayList<User>();
private UserDAO userDAO = new UserDAOImpl();

@Override
public User getModel() {
return user;
}

/**
* To save or update user.
* @return String
*/
public String saveOrUpdate()
{  
userDAO.saveOrUpdateUser(user);
return SUCCESS;
}

/**
* To list all users.
* @return String
*/
public String list()
{
userList = userDAO.listUser();
return SUCCESS;
}

/**
* To delete a user.
* @return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
userDAO.deleteUser(Long.parseLong( request.getParameter("id")));
return SUCCESS;
}

/**
* To list a single user by Id.
* @return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
user = userDAO.listUserById(Long.parseLong( request.getParameter("id")));
return SUCCESS;
}
7 
7public User getUser() {
7return user;
7}
7 
7public void setUser(User user) {
7this.user = user;
7}
7 
8public List<User> getUserList() {
8return userList;
8}
8 
8public void setUserList(List<User> userList) {
8this.userList = userList;
8}
8 
8}
In the struts configuration file we have four different actions corresponding to the different CRUD operations. During the save, update and delete operations, we need to update the list of users displayed below so we redirect the result to the listUser acion.
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 0//EN"

<struts>
<package name="default" extends="hibernate-default">
<action name="saveOrUpdateUser" method="saveOrUpdate"class="com.vaannila.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list"class="com.vaannila.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="editUser" method="edit"class="com.vaannila.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="deleteUser" method="delete"class="com.vaannila.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
</package>
</struts>
The hibernate.cfg.xml file contains the following configuration.
<?xml version="0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 0//EN"
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver </property>
<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost </property>
<property name="hibernate.connection.username">sa</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.vaannila.domain.User" />
</session-factory>
</hibernate-configuration>
In the register.jsp page we use the Struts 2 tags to display the form elements.
The push tag is used to move the object to the top of the ValueStack. During add operation we will refer to the model object User exposed by the ModelDriven inteface, in this case the push tag is not necessary. But during update operation we refer to the JavaBean property user that is returned by thelistUserById() method, now the push tag will be useful, it pushes the User object to the top of theValueStack so we need not use the second-level OGNL expression language like user.name to access the domain object properties.
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get( ServletActionContext.HTTP_REQUEST);
user = userDAO.listUserById(Long.parseLong(request. getParameter("id")));
return SUCCESS;
}
The url tag is used to create a new URL. Along with the URL we append the id value, this can be done using the param tab. In the OGNL expression language we use "%{}" as the escape sequence to refer a value on the ActionContext.

Download Struts 2 all examples source code

3 comments:

  1. in above example how we can upload a image database and and destination folder and how to excel sheet data upload database and destination folder

    ReplyDelete
  2. please give me solution

    ReplyDelete
  3. Respect and I have a keen present: How Much House Renovation house repair quotes

    ReplyDelete