Newsletter

Struts2 Insert,Update,Delete,Operations Through JDBC [ Real Time Application ]

Struts » on Feb 1, 2012 { 29 Comments } By Sivateja

Let us see  on how to work with Insert,Update,Delete operations through struts 2 with JDBC connect, a real time application.  Even we will see the same application using Struts 2 and Hibernate.

Actually i have not covered example on ServletRequestAware, ServletResponseAware Interface(s) earlier,  but its time to use these interfaces too :-).  Yeah i have used these interfaces in this program.

 

Directory Structure

Files Required

  • Delete.java
  • Display.java
  • Links.java
  • Mybean.java
  • Save.java
  • Update.java
  • Updates.java
  • web.xml
  • struts.xml
  • dsuccess.jsp
  • edit.jsp
  • error.jsp
  • index.jsp
  • retrive.jsp
  • ssuccess.jsp
  • usuccess.jsp

Delete.java

package java4s;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class Delete extends ActionSupport implements ServletRequestAware{    
    private static final long serialVersionUID = 1L;

    HttpServletRequest request;        

    public String execute()
    {            

    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    java.sql.Connection con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
    PreparedStatement ps=null;

    String cv[]=request.getParameterValues("rdel");

    for(int i=0;i<cv.length;i++)
    {
        ps=con.prepareStatement("delete from details where SNO=(?)");
        int k = Integer.parseInt(cv[i]);
        System.out.println("this is" +k);
        ps.setInt(1,k);        
        ps.executeUpdate();
        con.commit();
    }    

        ps.close();          
        con.close();

            }
        catch(Exception e){
             e.printStackTrace();
         }

            return SUCCESS;

    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletRequest getServletRequest() {
        return request;
    }

}

Display.java

package java4s;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class Display extends ActionSupport implements ServletRequestAware{
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;

	public String execute()
	{

	try{
	Class.forName("oracle.jdbc.driver.OracleDriver");
    java.sql.Connection con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
	Statement st=con.createStatement();
	ResultSet rs = st.executeQuery("select * from details");

    	List li = null;
    	li = new ArrayList();
    	Mybean mb = null;

		while(rs.next())
			{
			    mb = new Mybean();

			    mb.setNo(rs.getInt("sno"));
			    mb.setNam(rs.getString("sname"));
			    mb.setCt(rs.getString("scountry"));		  

			    li.add(mb);

			}

		request.setAttribute("disp", li);

		rs.close();
 		st.close();
		con.close();

		    }
		catch(Exception e){
 			e.printStackTrace();
 		}

			return SUCCESS;

	}

	public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletRequest getServletRequest() {
        return request;
}

}

Links.java

package java4s;
import com.opensymphony.xwork2.ActionSupport;
public class Links extends ActionSupport{	

	public String save()
	{
		return "save";	

	}
	public String display()
	{
		return "display";	

	}

}

Mybean.java

package java4s;
public class Mybean
{
	private int no;
	private String nam;
	private String ct;

	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getNam() {
		return nam;
	}
	public void setNam(String nam) {
		this.nam = nam;
	}
	public String getCt() {
		return ct;
	}
	public void setCt(String ct) {
		this.ct = ct;
	}		

}

Save.java

package java4s;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.opensymphony.xwork2.ActionSupport;
public class Save extends ActionSupport{
	private static final long serialVersionUID = 1L;

	Mybean mb=new Mybean();	

	public Mybean getMb() {
		return mb;
	}
	public void setMb(Mybean mb) {
		this.mb = mb;
	}

	public String execute()
	{

	try{
	Class.forName("oracle.jdbc.driver.OracleDriver");
    java.sql.Connection con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");

	String s = "insert into details values(?,?,?)";
	PreparedStatement ps=con.prepareStatement(s);
	ps.setInt(1, mb.getNo());
	ps.setString(2, mb.getNam());
	ps.setString(3, mb.getCt());

	ps.executeUpdate();
	con.commit();

		ps.close();
		con.close();

		    }
		catch(Exception e){
 			e.printStackTrace();
 		}

			return SUCCESS;

	}

}

Update.java

package java4s;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class Update extends ActionSupport implements ServletRequestAware,ApplicationAware{
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	Map m;

	public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletRequest getServletRequest() {
        return request;
    }

    public void setApplication(Map m)
	{
		this.m=m;
	}   

	public String execute()
	{
	try{
	Class.forName("oracle.jdbc.driver.OracleDriver");
    java.sql.Connection con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
    PreparedStatement ps=null;	

	    ps=con.prepareStatement("select * from details where SNO=?");
	    String a = request.getParameter("fid");
		int k = Integer.parseInt(a);
		ps.setInt(1,k);
	    //System.out.println("This is" +k);

		ResultSet res = ps.executeQuery();
		List l=new ArrayList();

		while(res.next())
		{
			m.put("a",res.getInt("sno"));
			m.put("b", res.getString("sname"));
			m.put("c",res.getString("scountry"));
		}

		ps.close();
		con.close();

	    }
		    catch(Exception e){
 			e.printStackTrace();
 	}

			return SUCCESS;

	}

}

Updates.java

package java4s;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.opensymphony.xwork2.ActionSupport;
public class Updates extends ActionSupport{
	private static final long serialVersionUID = 1L;

	Mybean mb=new Mybean();	

	public Mybean getMb() {
		return mb;
	}
	public void setMb(Mybean mb) {
		this.mb = mb;
	}

	public String execute()
	{

	try{
	Class.forName("oracle.jdbc.driver.OracleDriver");
    java.sql.Connection con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");

	String s = "update details set sname=?,scountry=? where sno=?";
	PreparedStatement ps=con.prepareStatement(s);
	ps.setString(1, mb.getNam());
	ps.setString(2, mb.getCt());
	ps.setInt(3, mb.getNo());

	ps.executeUpdate();
	con.commit();

		ps.close();
		con.close();

		    }
		catch(Exception e){
 			e.printStackTrace();
 		}

			return SUCCESS;

	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<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>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

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>
<include file="struts-default.xml"/>
<package name="a" extends="struts-default">

<action name="view" class="java4s.Display">
<result name="success">/retrive.jsp</result>
<result name="error">/error.jsp</result>
</action>

<action name="insert" class="java4s.Save">
<result name="success">/ssuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>

<action name="del" class="java4s.Delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>

<action name="update" class="java4s.Update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>

<action name="updates" class="java4s.Updates">
<result name="success">/usuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>

<action name="*Link" class="java4s.Links" method="{1}" >
<result name="save">/insertr.jsp</result>
<result name="display">/retrive.jsp</result>
</action>

</package>
</struts>

index.jsp

<META HTTP-EQUIV="Refresh" CONTENT="0;URL=view.action">

insertr.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<head>
<link rel="stylesheet" type="text/css" href="css/java4s.css" />
</head>

<body>
<a href="<s:url action="view.action"/>">Display Records</a>
<br><br>
<b><font color="#5d8122" face="verdana">Insert Details</font></b>
<s:form action="insert">

<s:textfield label="Number" name="mb.no" cssClass="bord"/>
<s:textfield label="Name" name="mb.nam" cssClass="bord"/>
<s:textfield label="Country" name="mb.ct" cssClass="bord"/>

<s:submit value="Insert" />

</s:form>
</body>
</html>

error.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
Unable to process your request....
<% out.println("Failed"); %>

edit.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page import="java.util.*;" %>

<html>

<head>
<link rel="stylesheet" type="text/css" href="css/java4s.css" />
</head>

<body>
<a href="<s:url action="view.action"/>">Display Records</a>
<br><br>

<%--   This is -- <s:property value="#application.a" /> --%>

<b><font color="#5d8122" face="verdana">Update Details</font></b>

<s:form action="updates">

<s:textfield label="Number" value="%{#application.a}" name="mb.no" readonly="true" cssClass="bord"/>
<s:textfield label="Name" value="%{#application.b}" name="mb.nam" cssClass="bord"/>
<s:textfield label="Country" value="%{#application.c}" name="mb.ct" cssClass="bord"/>

<s:submit value="Update" />

</s:form>

</body>
</html>

dsuccess.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
Record deleted successfully......
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=view.action">

retrive.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page import="java.util.*;" %>

<head>
<link rel="stylesheet" type="text/css" href="css/java4s.css" />
<script type="text/javascript">
function deleteRecord()
{
document.fom.action="del.action";
document.fom.submit();
}
function editr(val)
{
document.fom.action="update.action?fid="+val;
document.fom.submit();
}
</script>
</head>

<a href="<s:url action="saveLink.action"/>">Insert</a>

<br><br>

<table>
<form name="fom" method="post">
<%
List l=(List)request.getAttribute("disp");
if(l!=null)
{

Iterator it=l.iterator();

while(it.hasNext())
{

java4s.Mybean b=(java4s.Mybean)it.next();
int tempNum = b.getNo();
String tempName = b.getNam();
String tempCountry = b.getCt();

%>
<tr>
<td><input type="checkbox" value="<%= tempNum %>" name="rdel"></td>
<td><%= tempNum %></td>
<td><%= tempName %></td>
<td><%= tempCountry %></td>
<td><a href="javascript:editr('<%= tempNum %>')">Edit</a></td>
</tr>

<%

}
}

%>
<input type="button" value="delete" onclick="deleteRecord();">
</table>

</form>

ssuccess.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
Record inserted successfully......
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=view.action">

usuccess.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
Record updated successfully......
<META HTTP-EQUIV="Refresh" CONTENT="1;URL=view.action">

 Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

29 Responses to “Struts2 Insert,Update,Delete,Operations Through JDBC [ Real Time Application ]”
  1. Anirban Chakraborty says:

    In the example STRUTS-JDBC-CRUD in every action you write the JDBC code.
    Please write the JDBC code separately & call the methods in ACTION & also upload the code as soon as possible.

  2. suhel Mulla says:

    hi,
    I don’t get the “struts-tags” file from your code…..
    please help me.

  3. Java4s says:

    @suhel Mulla

    You no need to add separately 🙂

  4. parivallal says:

    I don’t get the “struts-tags” file from your code…..
    please help me.

  5. Java4s says:

    @Parivallal

    We no more need to add any external struts-tags in 2.x 🙂

  6. Pushker says:

    you should use custom tag in JSP page and use a separate class for the connection

  7. preeti says:

    Can you Please give this code in war file.

  8. Sameer says:

    Really Nice Example. Thanks you so much.If you have some other examples plaese share.

  9. Manoj says:

    Hi sir i am new in struts2, i want to display all records in tabular format including Edit button ; When user click on that edit button the open new form in that all details will be displayed and that user will be edit that particuler record only please give me that code..
    Thanks in advance…

  10. Sanjeev K says:

    Hi,
    I have trying to develop“Struts2 Insert,Update,Delete,Operations Through JDBC, Everything i configure correctly but i didn’t get a pre-defined classes or methods while developing progm Pls help me.

  11. Hey great article.
    Can you please post an article on the best practices for struts2+jdbc application cdrud operations?
    I read somewhere that it’s not a good practice to use ServletRequestAware for db connections. Please help

  12. rakesh says:

    you have to add jar files first, then “/struts-tags” will work…

  13. harsh says:

    can you provide me code for CRUD operation in struts2 using session as persistent technique and not database

  14. Anil says:

    Where did you fix the context path Struts-insert-edit-delete.

  15. Harendra says:

    to connect the jdbc jar file.
    ojdbc.jar

  16. Tanuj says:

    In above example my update action is not working . Number column is not working
    plz help…

  17. Soubhagya Padhi says:

    In the above example you used a map to populate data in update through sno..but what is that #application you used in edit.jsp,can you just explain me?

  18. hari says:

    STRUTS 2.X CRUD OPeration program is wrong. I t is showing error .kindly rectify

  19. pradeep solanki says:

    realy nice code

  20. my dear sir,
    i am very grateful to you. your codes work well. i learn much from them. thanks.

  21. sir,
    can you add the search option in this application of yours? i need this application with search. sir, plz help me.

  22. Swapnil Mahajan says:

    Great example for new learners, But I don’t get the “struts-tags” file, Please provide me

  23. Jitendra Modi says:

    Really nice working example.

    @for All, who don’t get the “struts-tags”, Add Struts2-core-XXX.jar – library into your class path by add as external Jar from “Java Build Path” in Eclipse.

  24. Ravi says:

    i need search page in struts2 search with name,mobile number pls

  25. sandeep says:

    me getting request always as null

    Mar 12, 2016 11:42:59 PM org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler error
    SEVERE: Exception occurred during processing request: null
    java.lang.NullPointerException
    at com.sandeep.struts.DisplayAction.execute(DisplayAction.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

    would you anyone please help me

  26. vadgama kapur says:

    very nice example ,completely work I code , thank you ..

  27. sathish says:

    where to create struts.xml
    –>what is inside css ans js(folders)
    —> weather i need to create table in sql scrabbook
    do reply me ….am getting 404 error

  28. pravat says:

    type Exception report

    message

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    java.lang.NullPointerException
    org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
    org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:37)
    com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:557)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:434)

    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.41 logs.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.