Showing posts with label Eclipse IDE. Show all posts
Showing posts with label Eclipse IDE. Show all posts

Create first JSP page in Eclipse IDE with Apache Tomcat Server

Following steps you need to follow to create your first JSP page in Eclipse IDE.

Step 1: Create Server by following steps :
Click on servers and then click on link to create a server.
 
Select Tomcat version in Apache folder which is installed in your system.

Browse the Tomcat Server folder and Click Finish.

Step 2: File > New > Dynamic Web Project

Give name HelloJSP then click Next > Next > Finish





Step 3: Create JSP File
WebContent > New > JSP File

Give name index.jsp then click Next > Finish

Write some code inside it.

Step 4: Deploy it over the Server
Right Click on Project Name > Run As > Run on Server

Click on Finish.

Output of your First JSP page on Web Browser.

How to upload Multiple Files- Images (blob data) with enctype="multipart/form-data" in Oracle Database using Struts2, JDBC and Eclipse IDE

In this tutorial we are working with multiple images (blob data type) uploading with other two values as file id and name (these two values are not entered by user as input in database table). And every time we are replacing new values with previous stored values(here we are working with three user inputs as browse button or uploader).
 
Here we are using enctype="multipart/form-data", Struts2 jars and tags, Apache Tomcat 7.0 and Java 6 (but you can use them as other versions too, available on your system).

you can also Download full code with required Jars. 
Download Full Code with Jars 

Project View in Project Explorer

Create a table with name FILES and here we are using TEST Schema(but you can use others too for example HR Schema)
FILES Table

file_upload.jsp
This is page for user's input as well as output.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <%@ taglib uri="/struts-tags" prefix="s"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <script type="text/javascript" src="js/jquery-1.7.2.js"></script>  
 <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>  
 <title>FILE UPLOAD</title>  
 </head>  
 <body bgcolor="green">  
 <s:form id="uploadjdbc" name="uploadjdbc" theme="simple" method="POST" enctype="multipart/form-data">  
      <table width="75%" align="center" border="1">  
           <tr>  
                <td width="33%" colspan="2" align="center" ><img src="<s:url action='getimage?id=image_1' />" id="imgLogin_1" name="imgLogin_1" width="400" /></td>  
                <td width="34%" colspan="2" align="center" ><img src="<s:url action='getimage?id=image_2' />" id="imgLogin_2" name="imgLogin_2" width="400" /></td>  
                <td width="33%" colspan="2" align="center" ><img src="<s:url action='getimage?id=image_3' />" id="imgLogin_3" name="imgLogin_3" width="400" /></td>  
           </tr>  
           <tr><td colspan="6">&nbsp;</td></tr>  
           <tr>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                </td>  
                <td>  
                     <s:file id="upload_1" name="upload_1" label="File" onblur="javascript: validateFileName();" />  
                </td>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                </td>  
                <td>  
                     <s:file id="upload_2" name="upload_2" label="File" onblur="javascript: validateFileName();" />  
                </td>  
                <td align="right" width="30%">  
                     Select File :&nbsp;  
                </td>  
                <td>  
                     <s:file id="upload_3" name="upload_3" label="File" onblur="javascript: validateFileName();" />  
                </td>  
           </tr>  
           <tr><td colspan="6">&nbsp;</td></tr>  
           <tr>  
                <td colspan="6" align="center">  
                     <input type="button" id="btnUpload" value="Upload">&nbsp;&nbsp;  
                     <input type="reset" id="btnReset" value="Reset">  
                </td>  
           </tr>  
      </table>  
 </s:form>  
 </body>  
 <script type="text/javascript">  
      $.getScript('js/file_upload.js');  
 </script>  
 </html>  

struts.xml
This file contains information about which action class need to be invoked.
 <!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" />  
      <constant name="struts.ui.templateDir" value="template" />  
      <constant name="struts.multipart.maxSize" value="5242880" />  
      <package name="uploadjdbc" extends="struts-default">  
           <action name="upload" class="blog.webideaworld.com.FileUpload">  
                <result name="success">jsp/file_upload.jsp</result>  
                <result name="input">jsp/error.jsp</result>  
                <result name="error">jsp/error.jsp</result>  
           </action>  
           <action name="getimage" class="blog.webideaworld.com.FileUpload" method="invoke" />  
      </package>  
 </struts>  

FileUpload.java
This invoke() function will be called by struts.xml for displaying already uploaded images. It writes the byte array data to the output Stream.
 package blog.webideaworld.com;  
 import javax.servlet.http.HttpServletResponse;  
 import org.apache.struts2.ServletActionContext;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class FileUpload extends ActionSupport {  
      private static final long serialVersionUID = 1L;  
      private FileUploadHelper helper = new FileUploadHelper();  
      private String id = "";  
      public String execute() {  
           if (helper.saveFiles()) {  
                return SUCCESS;  
           } else {  
                return ERROR;  
           }  
      }  
       
      public void invoke() throws Exception {  
           HttpServletResponse response = ServletActionContext.getResponse();  
           response.getOutputStream().write(helper.getFiles(id));  
           response.getOutputStream().flush();  
      }  
      public String getId() {  
           return id;  
      }  
      public void setId(String id) {  
           this.id = id;  
      }  
 }  

FileUploadHelper.java
setFileMap() is setting all the files received from JSP to a map. "mapFile.get("upload_"+i)" is getting one file from map. "getFileBlob(oFile)" is reading file from the input stream. and some other required explanation is inside code.
 package blog.webideaworld.com;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
 import java.util.Enumeration;  
 import java.util.HashMap;  
 import java.util.Map;  
 import org.apache.struts2.ServletActionContext;  
 import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;  
 public class FileUploadHelper {  
      Map<String, File> mapFile = new HashMap<String, File>();  
      byte[] imageInByte = null;  
      public boolean saveFiles() {  
           Connection conn = null;  
           PreparedStatement pstmt = null;  
           Integer intRowsAffected = 0;  
           boolean flag = true;  
           byte[] bData = null;  
           File oFile = null;  
           try {  
                setFileMap();                    //Setting all the files received from JSP to a map  
                //Database connectivity  
                Class.forName("oracle.jdbc.OracleDriver");  
                conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "test", "test");  
                for (int i = 1; i <= 3; i++) {  
                     intRowsAffected = 0;  
                     oFile = mapFile.get("upload_"+i);               //Getting one file from map  
                     if (oFile != null) {  
                          bData = getFileBlob(oFile);                    //Reading file from the input stream  
                          //If file with id (i) already exists, then it is updated  
                          pstmt = conn.prepareStatement("UPDATE FILES SET FILE_DATA=? WHERE FILE_ID=?");  
                          pstmt.setBytes(1, bData);  
                          pstmt.setInt(2, i);  
                          intRowsAffected = pstmt.executeUpdate();  
                          if (intRowsAffected == 0) {               //If file does not exists, a new entry is inserted  
                               pstmt = conn.prepareStatement("INSERT INTO FILES (FILE_ID, FILE_NAME, FILE_DATA) VALUES (?,?,?)");  
                               pstmt.setInt(1, i);  
                               pstmt.setString(2, oFile.getName());  
                               pstmt.setBytes(3, bData);  
                               intRowsAffected = pstmt.executeUpdate();  
                               if (intRowsAffected == 0) {          // If insertion fails, error page will be displayed  
                                    return false;  
                               }  
                          }  
                     }  
                }  
           } catch (Exception e) {  
                System.out.println(e);  
                flag = false;  
           } finally {  
                try {  
                     pstmt.close();  
                     conn.close();  
                } catch (SQLException e) { }  
           }  
           return flag;  
      }  
      public byte[] getFileBlob(File file) {  
           byte[] bFile = new byte[(int) file.length()];  
           try {  
                FileInputStream fileInputStream = new FileInputStream(file);  
                fileInputStream.read(bFile);  
                fileInputStream.close();  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           return bFile;  
      }  
      private void setFileMap() {  
           MultiPartRequestWrapper mprw = (MultiPartRequestWrapper) ServletActionContext.getRequest();  
           Enumeration<String> e = mprw.getFileParameterNames();  
           while(e.hasMoreElements()) {  
                String str = e.nextElement();          //this will give the id from the JSP  
                mapFile.put(str, mprw.getFiles(str)[0]);  
           }  
      }  
      /**  
       * @param id  
       * @return byte array corresponding to the id.  
       */  
      public byte[] getFiles(String id) {  
           Connection conn = null;  
           Statement stmt = null;  
           ResultSet rs = null;  
           try {  
                Class.forName("oracle.jdbc.OracleDriver");  
                conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "test", "test");  
                stmt = conn.createStatement();  
                rs = stmt.executeQuery("SELECT FILE_DATA FROM FILES WHERE FILE_ID="+Integer.parseInt(id.split("_")[1]));  
                if (rs.next()) {  
                     imageInByte = rs.getBytes(1);  
                }  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
           return imageInByte;  
      }  
 }  

file_upload.js
This is for validation part.
 $('#btnUpload').click(function () {  
      if ($('#upload_1').val() == '' && $('#upload_2').val() == '' && $('#upload_3').val() == '') {  
           alert('Select atleast 1 Image !!!');  
           return false;  
      }  
      document.forms[0].action = 'upload.action';  
      document.forms[0].submit();  
 });  

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_3_0.xsd"  
      id="WebApp_ID" version="3.0">  
      <display-name>uploadjdbc</display-name>  
      <welcome-file-list>  
           <welcome-file>jsp/file_upload.jsp</welcome-file>  
      </welcome-file-list>  
      <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>  
 </web-app>  

Download Full Code with Jars

Output:

How to iterate user details through ArrayList with Iterator tag in Struts2 using Oracle 10g XE and Eclipse

In this tutorial we are working with iterator tag to print user details. Here we are working with temporary list and adding values to this list. finally adding temporary list to another list and this list will contain all the rows( in the form of smaller lists) , actual data in the ArrayList we are retrieving through oracle database table.

Iterator will iterate over a value. An iterable value can be any of java.util.Collection, java.util.Iterator.
The <s:property/> tag prints out the current value of the iterator.

Here we are using Apache Tomcat 7.0 and Java 6 (but you can use them as other versions too available on your system).

you can also Download full code with required Jars. 
Download Full Code with Jars 

Project View in Project Explorer :

Create a table with name USERS and here we are using TEST Schema(but you can use others too for example HR Schema)
users Table
users Table Data(showing some values)

homepage.jsp
This is page for user's input as well as output.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <%@ taglib uri="/struts-tags" prefix="s"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Search Users</title>  
 </head>  
 <body>  
 <s:form id="adagstatus" name="adagstatus" theme="simple" method="POST">  
 <h3>Search Users with a Click on Alphabets</h3>  
      <table>  
           <tr>  
                <td>  
                     <a href="finduser.action?id=a">A</a>  
                     <a href="finduser.action?id=B">B</a>  
                     <a href="finduser.action?id=s">S</a>  
                </td>  
           </tr>  
      </table>  
      <br>  
      <table cellpadding="0" cellspacing="0" border="1" width="100%" >  
      <thead>  
           <tr>  
                <th style="background-color: orange;">Column One(Users Name)</th>  
                <th style="background-color: orange;">Column Two(Users ID)</th>  
           </tr>  
      </thead>  
      <s:iterator id="lstUsers" var="usr" value="lstUsers" status="counter">  
           <tr>  
             <td align="center" style="background: grey;"><s:property value="#usr[0]" /></td>  
       <td align="center" style="background: yellow;"><s:property value="#usr[1]" /></td>  
           </tr>  
      </s:iterator>  
 </table>  
 <br>  
      <table>  
           <tr>  
                <td align="center"><a href="jsp/some_other_page.jsp">Go to some other page</a></td>  
           </tr>  
      </table>  
 </s:form>  
 </body>  
 </html>  

FindUser.java
This is a POJO class and it is working as action class for Struts.
 package blog.webideaworld.in;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.ArrayList;  
 import java.util.List;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class FindUser extends ActionSupport {  
      List lstUsers = new ArrayList();  
      String id = "";  
      public String execute() {  
           if (id != null) {  
                lstUsers = finduser();  
           }  
           return SUCCESS;  
      }  
      public List finduser() {  
           List<String> lstTemp = null;  
           List lst = new ArrayList();  
           Connection conn = null;  
           Statement stmt = null;  
           try {  
              Class.forName("oracle.jdbc.OracleDriver");  
              conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","test","test");  
              stmt = conn.createStatement();  
              ResultSet rs = stmt.executeQuery("SELECT * FROM USERS WHERE LOWER(USERNAME) LIKE LOWER('"+ id +"%')");  
              while (rs.next()) {  
                   lstTemp = new ArrayList();          
                   lstTemp.add(rs.getString(1));  
                   lstTemp.add(rs.getString(2));  
                   lst.add(lstTemp); 
              }  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
           return lst;  
      }  
      public String getId() {  
           return id;  
      }  
      public void setId(String id) {  
           this.id = id;  
      }  
      public List getLstUsers() {  
           return lstUsers;  
      }  
      public void setLstUsers(List lstUsers) {  
           this.lstUsers = lstUsers;  
      }  
 }  

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">  
  <display-name>findUserIterate</display-name>  
  <welcome-file-list>  
   <welcome-file>jsp/homepage.jsp</welcome-file>  
  </welcome-file-list>  
  <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>  
 </web-app>  

struts.xml
This file contains information about which action class to be invoked.
 <!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" />  
      <constant name="struts.ui.theme" value="nav" />  
      <constant name="struts.ui.templateDir" value="template" />  
      <package name="finduser" extends="struts-default">  
           <action name="finduser" class="blog.webideaworld.in.FindUser">  
                <result name="success">jsp/homepage.jsp</result>  
           </action>  
      </package>  
 </struts>  

Download Full Code with Jars

Output:
user data output

More Struts Topics :

How to use Struts2 Iterator tag to get Users Details with Oracle 10g XE and Eclipse

In this Tutorial we are retrieving users details from oracle database table USERS which is in TEST schema. We are using Struts2 Iterator tag in jsp page to show all retrieved details from database table by clicking hyperlink on same jsp page and sending users names first letter to Action Java Class using url Rewriting.

Iterator will iterate over a value. An iterable value can be any of java.util.Collection, java.util.Iterator. 

The following example retrieves the value of the current object on the value stack and uses it to iterate over. The <s:property/> tag prints out the current value of the iterator.

Here we are using Apache Tomcat 7.0 and Java 6 (but you can use them as other versions too available on your system).

you can also Download full code with required Jars. 
Download Full Code with Jars 

Project View in Navigator :

Create a table with name USERS and here we are using TEST Schema(but you can use others too for example HR Schema)
users Table
users Table Data(showing some values)
In following example the iterator tag will retrieve value object from the ActionContext and the status attribute is used to create an IteratorStatus object, which in this example, its odd() method is used to alternate row colors:

homepage.jsp
This is page for user's input
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <%@ taglib uri="/struts-tags" prefix="s"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Search Users</title>  
 <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>  
 </head>  
 <body>  
 <s:form id="adagstatus" name="adagstatus" theme="simple" method="POST">  
 <h3>Search Users with a Click on Alphabets</h3>  
      <table>  
           <tr>  
                <td>  
                     <a href="finduser.action?id=a">A</a>  
                     <a href="finduser.action?id=B">B</a>  
                     <a href="finduser.action?id=s">S</a>  
                </td>  
           </tr>  
      </table>  
      <br>  
      <table cellpadding="0" cellspacing="0" border="1" width="100%" >  
      <thead>  
           <tr>  
                <th>Column One(Users Name)</th>  
                <th>Column Two(Users ID)</th>  
           </tr>  
      </thead>  
      <s:iterator id="lstUsers" var="usr" value="lstUsers" status="counter">  
             <s:if test="#counter.odd == true">  
             <tr>  
                <td align="center" style="background: grey;"><s:property /></td>  
                </s:if>  
                <s:else>  
                <td align="center" style="background: yellow;"><s:property /></td>  
                </tr>  
                </s:else>  
      </s:iterator>  
 </table>  
 </s:form>  
 </body>  
 </html>  

FindUser.java
This is a POJO class and it is working as action class for Struts.
 package blog.webideaworld.in;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.ArrayList;  
 import java.util.List;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class FindUser extends ActionSupport {  
      List lstUsers = new ArrayList();  
      String id = "";  
      public String execute() {  
           if (id != null) {  
                lstUsers = finduser();  
           }  
           return SUCCESS;  
      }  
      public List finduser() {  
           List lst = new ArrayList();  
           Connection conn = null;  
           Statement stmt = null;  
           try {  
              Class.forName("oracle.jdbc.OracleDriver");  
              conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","test","test");  
              stmt = conn.createStatement();  
              ResultSet rs = stmt.executeQuery("SELECT * FROM USERS WHERE LOWER(USERNAME) LIKE LOWER('"+ id +"%')");  
              while (rs.next()) {  
                   lst.add(rs.getString(1));  
                   lst.add(rs.getString(2));  
              }  
           } catch (Exception e) {  
                System.out.println(e);  
           }  
           return lst;  
      }  
      public String getId() {  
           return id;  
      }  
      public void setId(String id) {  
           this.id = id;  
      }  
      public List getLstUsers() {  
           return lstUsers;  
      }  
      public void setLstUsers(List lstUsers) {  
           this.lstUsers = lstUsers;  
      }  
 }  

 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_3_0.xsd" id="WebApp_ID" version="3.0">  
  <display-name>finduser</display-name>  
  <welcome-file-list>  
   <welcome-file>jsp/homepage.jsp</welcome-file>  
  </welcome-file-list>  
  <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>  
 </web-app>  

struts.xml
This file contains information about which action class to be invoked. 
 <!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" />  
      <constant name="struts.ui.theme" value="naveen" />  
      <constant name="struts.ui.templateDir" value="template" />  
      <package name="finduser" extends="struts-default">  
           <action name="finduser" class="blog.webideaworld.in.FindUser">  
                <result name="success">jsp/homepage.jsp</result>  
           </action>  
      </package>  
 </struts>  

Download Full Code with Jars

Output:
users data output

More Struts Topics :

Store and Retrieve Numeric, Alphanumeric and Blob (Image) data with Struts2, Oracle 10g XE and Eclipse Indigo as IDE

In this Tutorial, our concern is to make you learn storing and also retrieving Image (Blob data) using Struts2, Oracle 10g and Eclipse. but we are also storing and retrieving Numeric and alphanumeric data which is a plus point of this tutorial.

Here we are using Apache Tomcat 7.0 and Java 6 but you can use them as other versions too available on your system.

you can also Download full code with required Jars. 
Download Full Code with Jars

Complete Project View in Project Explorer
Create table(imgtab) in Oracle database we are here using hr schema you can use other also.
imgtab table structure
imgtab table with Stored Data

Step 1 : Code for storing data into Database:

p1.jsp

This is page for user's input
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Post Image and Data</title>  
 </head>  
 <body>  
 <h4 align=right><a href=search.jsp>See your Data</a></h4><hr>  
     <center>  
  <form action="addpost1" enctype="multipart/form-data" method="post">  
  <table>  
      <tr><td>Enter Id:</td><td><input type="text" name="id"></td></tr>  
      <tr><td>Enter Category:</td><td><input type="text" name="cat"></td></tr>  
      <tr><td>Add Photo: </td><td><input type="file" name="pic"></td></tr>  
      <tr><td></td><td><input type="submit" value="Post"></td></tr>  
  </table>  
  </form>  
  </center>  
 </body>  
 </html>  
 
Post1Action.java
This is a POJO class and it is working as action class for Struts.
 package com.blog.webideaworld;  
 import java.io.FileInputStream;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.PreparedStatement;  
 import javax.servlet.annotation.MultipartConfig;  
 import java.io.File;  
 import com.opensymphony.xwork2.ActionSupport;  
 @MultipartConfig  
 public class Post1Action extends ActionSupport {  
      int id;  
      String cat;  
      File pic;  
      public String execute() throws Exception  
     {  
      // Connect to Oracle  
           Class.forName("oracle.jdbc.OracleDriver");  
           Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");  
     con.setAutoCommit(false);  
     System.out.println(pic.getPath());  
     FileInputStream pic1 = new FileInputStream(pic.getPath());  
     PreparedStatement ps = con.prepareStatement("insert into imgtab(id,category,photo) values(?,?,?)");  
     ps.setInt(1, id);  
     ps.setString(2, cat);  
     // size must be converted to int otherwise it results in error  
     ps.setBinaryStream(3, pic1, (int) pic1.available());  
     int i=ps.executeUpdate();  
     con.commit();  
     con.close();  
       if(i!=0)  
       return SUCCESS;  
       else  
       return INPUT;  
     }  
      public int getId() {  
           return id;  
      }  
      public void setId(int id) {  
           this.id = id;  
      }  
      public String getCat() {  
           return cat;  
      }  
      public void setCat(String cat) {  
           this.cat = cat;  
      }  
      public File getPic() {  
           return pic;  
      }  
      public void setPic(File pic) {  
           this.pic = pic;  
      }  
 }       

success.jsp
This page will display on successful submission of data.
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Insert title here</title>  
 </head>  
 <body>  
 <h4 align=right><a href=search.jsp>See your Data</a></h4><hr>  
     <center>  
 Record successfully submitted.</center>  
 </body>  
 </html>  


Step 2: Code for retrieve data from Database:

search.jsp
This page will display all data you stored in Database Table.
 <%@page import="java.sql.*"%>  
 <%@page import="com.opensymphony.xwork2.ActionContext"%>  
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>Your Uploaded Data</title>  
 </head>  
 <body>  
 <center>  
 <table border="1"><tr align="center"><td>Photo</td><td>Customer Id</td><td>Category</td></tr>  
 <%       
                Class.forName("oracle.jdbc.OracleDriver");  
                Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");  
                Statement st=conn.createStatement();  
       ResultSet rs=st.executeQuery("select * from imgtab");  
       while( rs.next()) {  
            int k=rs.getInt(1);          
          %>  
          <tr align="center">  
          <td><img width=200 height=150 src=image.jsp?idd=<%=k%> ></img></td>  
          <td><%=rs.getString("id")%></td>  
          <td><%=rs.getString("category")%></td>  
          </tr>  
       <%  
       }   
       %>  
 </table>  
 </center>  
 </body>  
 </html>  

image.jsp
This page code used to retrieve image from database table.
 <%@ page import="java.sql.*,java.io.*,java.util.*" %>   
 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
   pageEncoding="ISO-8859-1" session="false"%>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
 <head>  
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 <title>post</title>  
 </head>  
 <body>  
 <%  
 try {  
      Class.forName("oracle.jdbc.OracleDriver");  
      Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","hr","hr");  
   PreparedStatement ps = con.prepareStatement("select photo from imgtab where id = ?");  
   String idd = request.getParameter("idd");  
   int id=Integer.parseInt(idd);  
   System.out.print(id);  
   ps.setInt(1,id );  
   ResultSet rs = ps.executeQuery();  
   rs.next();  
   Blob b = rs.getBlob("photo");  
   response.setContentType("image/jpeg");  
   response.setContentLength((int) b.length());  
   InputStream is = b.getBinaryStream();  
   OutputStream os = response.getOutputStream();  
   byte buf[] = new byte[(int) b.length()];  
   is.read(buf);  
   os.write(buf);  
   os.close();  
 } catch (Exception ex) {  
   System.out.println(ex.getMessage());  
 }  
 %>  
 </body>  
 </html>  

 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">  
  <display-name>StoreImageDB</display-name>  
  <welcome-file-list>  
   <welcome-file>p1.jsp</welcome-file>  
    </welcome-file-list>  
    <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>  
 </web-app>  

struts.xml
This file contains information about which action class to be invoked. 
 <?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>  
   <package name="log" namespace="/" extends="struts-default">  
    <action name="addpost1" class="com.blog.webideaworld.Post1Action" method="execute">  
     <result name="success">success.jsp</result>  
     <result name="input">p1.jsp</result>  
   </action>  
   </package>  
   </struts>  

Download Full Code with Jars

Output:
For Storing data

Data Retrieved from database

More Struts Topics :

How to Configure methods in Action mappings with or without Wildcards using Struts2

Let take an example to understand methods in Action mappings
struts.xml
Here our action is mapped for same action class for two different methods, on place of execute() method we are calling takeForm() and addChart() methods on same action class for crossponding action names.
 <action name="takeForm" class="blog.webideaworld.in.takeAction" method="takeForm">  
 <result name="success">success.jsp</result>  
 <result name="failure">error.jsp</result>  
 </action>  
 <action name="addChart" class="blog.webideaworld.in.takeAction" method="addChart">  
 <result name="success">success.jsp</result>  
 <result name="failure">error.jsp</result>  
 </action>   

we can also perform above task with wildcards
struts.xml (With Wildcard)
 <action name="*" class="blog.webideaworld.in.takeAction" method="{1}">  
 <result name="success">success.jsp</result>  
 <result name="failure">error.jsp</result>  
 </action>  
The "*" in the path attribute allows the mapping to match the request URIs with same action and method name.
The part of the URI matched by the wildcard will then be substituted into various attributes of the action mapping and its action results replacing {1}.
For the rest of the request, the framework will see the action mapping and its action results containing the new values.

More Struts Topics :