java4all@1986 java. Powered by Blogger.
Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Developing our own struts PlugIn?

>> Friday, June 24, 2011

Understanding Of Plug In:

Struts PlugIns are configured using the <plug-in> element within the Struts configuration file. This element has only one valid attribute, 'className', which is the fully qualified name of the Java class which implements the org.apache.struts.action.PlugIn interface.

For PlugIns that require configuration themselves, the nested <set-property> element is available.

The plug-in tag in the struts-config.xml file is used to declare the PlugIn to be loaded at the time of server start-up. Following example shows how to declare the Tiles PlugIn:
<plug-in className="org.apache.struts.tiles.TilesPlugin">
  <set-property
  property="definitions-config"
   value="/WEB-INF/tiles-defs.xml"/>
</plug-in>

The above declaration instructs the struts to load and initialize the Tiles plugin for your application on startup.

Writing Struts PlugIn Java Code

In this example we write Sailajaword Struts PlugIn example that will give you idea about creating, configuring and checking Struts PlugIn. Our Sailajaword Stuts PlugIn contains a method called Say Hello, which simply returns HelloWorld message.

Here is code of Sailajaword Struts Plugin:

package roseindia.net.plugin;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.apache.struts.action.PlugIn;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;

/**
* @author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/


public class SailajawordStrutsPlugin implements PlugIn {


  public static final String PLUGIN_NAME_KEY 
  = SailajawordStrutsPlugin.class.getName();

 public void destroy() {
  System.out.println("Destroying Sailajaword World PlugIn");
 }

 public void init(ActionServlet servlet, ModuleConfig config) 
throws ServletException {
  System.out.println("Initializing Sailajaword World PlugIn");
 ServletContext context = null;
 context = servlet.getServletContext();
SailajawordStrutsPlugin objPlugin = new SailajawordStrutsPlugin();
 context.setAttribute(PLUGIN_NAME_KEY, objPlugin);

 }

  public String sayHello(){
  System.out.println("Sailaja Plugin");
  return "Hello Plugin";
  }
  
}

Configuring PlugIn in Struts-config.xml


To configure the plugin add the following line your struts-config.xml file.

<plug-in className="roseindia.net.plugin.SailajawordStrutsPlugin">
</plug-in>

How to Call PlugIn In Jsp Page
 Here is the code how to call the plugIn
<%@page contentType="text/html" import="java.util.*,roseindia.net.plugin.*" %>
<%

ServletContext servletContext = this.getServletContext();


HelloWorldStrutsPlugin plugin= (HelloWorldStrutsPlugin) servletContext.getAttribute
(HelloWorldStrutsPlugin.PLUGIN_NAME_KEY);

String strMessage = plugin.sayHello();

%>

Message From Plugin: <%=strMessage%>

The output will be sailaja PlugIn

Read more...

Getting struts datasource from struts-config.xml?

This tutorial shows you how you can configure Struts DataSource Manager on the Tomcat 5.5.9 server. We will use struts 1.2.7 in this tutorial. In this tutorial we will configure Struts DataSource Manager to use MySQL Database and use the connection provided by Struts DataSource in action class.

Downloading and Installing Tomcat 5.5.9
Download jakarta-tomcat-5.5.9 from http://jakarta.apache.org/tomcat/. Install it on your machine. Run and test the pages that comes with the tomcat.

Download Struts
Download Struts struts-1.2.7 from http://struts.apache.org/download.cgi and unzip it to your favorite directory. Go to the struts-1.2.7\webapps directory and then unzip struts-blank.war file. We will use this file to write our tutorial.

Download MySQL JDBC Driver

Download mysql-connector-java-3.0.16-ga-bin.jar from here mysql-connector-java-3.0.16-ga-bin.jar or you can download and use the latest version of mysql jdbc driver. Copy the JDBC driver file (mysql-connector-java-3.0.16-ga-bin.jar or latest version) to the jakarta-tomcat-5.5.9\common\lib directory of your tomcat installation. This will add the MySQL JDBC driver to the tomcat server.

Creating MySQL Database

In this tutorial I am using MySQL server installed on my local machine. You can download and install MySQL on your local machine and use for this tutorial. If you already have MySQL server then you can use the existing MySQL server.


Configuring Struts Application
Now create a directory "strutsdatabase" in the jakarta-tomcat-5.5.9\webapps\ directory and copy the content of struts-blank application (unzipped above) in the strutsdatabase directory.

Now start the tomcat and try to access the strutsdatabase application by typing the url http://localhost:8080/strutsdatabase in browser. Your browser should display the welcome page. After testing shutdown the tomcat server.

Configuring Struts DataSource Manager
The Struts DataSource manager makes it easy for your Action class get the database connection. To configure the Stuts DataSource Manager we will uncomment the <data-sources> entry in the struts-config.xml.

Uncomment and then <data-sources> entry in the struts-config.xml and then change the line "org.apache.commons.dbcp.BasicDataSource" to "org.apache.tomcat.dbcp.dbcp.BasicDataSource". In tomcat 5.5.9 dbcp classes are packaged in naming-factory-dbcp.jar archieve, so we are using "org.apache.tomcat.dbcp.dbcp.BasicDataSource" instead of "org.apache.commons.dbcp.BasicDataSource". After this change the database dirver, database url and passwor in the <data-sources> tag.

In struts-config.xml your <data-source> look like below

<data-sources>
<data-source type="org.apache.tomcat.
dbcp.dbcp.BasicDataSource">
    <set-property
      property="driverClassName"
      value="com.mysql.jdbc.Driver" />
    <set-property
      property="url"
      value="jdbc:mysql://localhost:3306
/strutsdatabase?autoReconnect=true" />
    <set-property
      property="username"
      value="root" />
    <set-property
      property="password"
      value="" />
    <set-property
      property="maxActive"
      value="10" />
    <set-property
      property="maxWait"
      value="5000" />
    <set-property
      property="defaultAutoCommit"
      value="false" />
    <set-property
      property="defaultReadOnly"
      value="false" />
    <set-property
      property="validationQuery"
      value="SELECT COUNT(*) FROM test" />
</data-source>
</data-sources>
Create an action class to test the Data source
  
package test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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 java.sql.*;

public class TestDataSource extends Action
{
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception{

 javax.sql.DataSource dataSource;
 java.sql.Connection myConnection=null;
 try {
  dataSource = getDataSource(request);
  myConnection = dataSource.getConnection();
  Statement stmt=myConnection.createStatement();
  ResultSet rst=stmt.executeQuery("select

 username from test");
  System.out.println("*************

*****************************");
  System.out.println("********Out

 Put from TestDataSource ******");
  while(rst.next()){
  System.out.println("User Name is:

 " + rst.getString("username"));
  }
  System.out.println("************

******************************");
  rst.close();
  stmt.close();
  // do what you wish with myConnection
 } catch (SQLException sqle) {
  getServlet().log("Connection.process", sqle);
 } finally {
  //enclose this in a finally block to make
  //sure the connection is closed
  try {
 myConnection.close();
  } catch (SQLException e) {
 getServlet().log("Connection.close", e);
  }
 }


  return mapping.findForward("success");
  }
}  
The following code can be used to get Datsource ans connection from Struts DataSource
dataSource = getDataSource(request);
myConnection = dataSource.getConnection();


Save this file(TestDataSource.java)  into jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\java\test directory. Add the servlet API into class path. Then open dos prompt and navigate to jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\ directory and issue run ant. This will compile the action class (TestDataSource.java) and copy it to the classes directory of the webapplication.


Our <action-mappings>  looks below
 
<action
  path="/DataSource"
  type="test.TestDataSource">
  <forward name="success" path="/success.jsp"/>
</action>

This is all about how to get DataSource and Connection From Struts DataSource

Read more...

Deployement Discriptor in Struts or web.xml in struts?

Deployment Descriptor
                       What we will configure in web.xml in struts
            
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

  <!-- Action Servlet Configuration -->
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
    <param-name>application</param-name>
    <param-value>test.struts.MessageResources</param-value>
  </init-param>
    <init-param>
      <param-name>mapping</param-name>
      <param-value>org.apache.struts.action.RequestActionMapping</param-value>
    </init-param>
    <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>
    <load-on-startup>2</load-on-startup>
  </servlet>


  <!-- Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
      <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <!-- Struts Tag Library Descriptors -->
  <jsp-config>
  <taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>

  <taglib>
    <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-template.tld</taglib-location>
  </taglib>
  <taglib>
    <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>
</jsp-config>
</web-app>

Read more...

What do we will configure in struts-config.xml?

                                            STRUTS-CONFIG.XML

The main control file in the Struts framework is the struts-config.xml XML file, where action mappings are specified.

This file’s structure is described by the struts-config DTD file, which is defined at http://jakarta.apache.org/struts/. A copy of the DTD can be found on the /docs/dtds subdirectory of the framework’s installation root directory. The top-level element is struts-config.

        STRUTS-CONFIG.XML
           
<struts-config>

 <!-- ========== Data Source Decleration ============ -->
<data-sources>
<data-source type="org.apache.tomcat.
dbcp.dbcp.BasicDataSource">
    <set-property
      property="driverClassName"
      value="com.mysql.jdbc.Driver" />
    <set-property
      property="url"
      value="jdbc:mysql://localhost:3306
/strutsdatabase?autoReconnect=true" />
    <set-property
      property="username"
      value="root" />
    <set-property
      property="password"
      value="" />
    <set-property
      property="maxActive"
      value="10" />
    <set-property
      property="maxWait"
      value="5000" />
    <set-property
      property="defaultAutoCommit"
      value="false" />
    <set-property
      property="defaultReadOnly"
      value="false" />
    <set-property
      property="validationQuery"
      value="SELECT COUNT(*) FROM test" />
</data-source>
</data-sources>

 <!-- ========== Form Bean Definitions ============ -->
 <form-beans>
   <form-bean name="login" type="com.bhaskar.NewActionForm" />
 <form-bean name="UserForm" type="org.apache.struts.action.DynaActionForm">
    <form-property name="givenName"type="java.lang.String"
        />
    <form-property name="firstname" type="java.lang.String"/>
</form-bean>

<!-- ========== Global Forwards Definitions ============ -->
 <global-forwards type="org.apache.struts.action.ActionForward">
      <forward name="sucess" path="mypage.jsp" />
 </global-forwards>


<!-- ========== Global Exceptions Definitions ============ -->
<global-exceptions>
<exception key="some.key" type="java.lang.NullPointerException"
       path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>

<!-- ========== Action Mappings Definitions ============ -->
<action-mappings>
        <action
            path="/logon"
            type="org.apache.struts.webapp.example.LogonAction"
            name="logonForm"
            scope="request"
            input="/logon.jsp"
            unknown="false"
            validate="true" >
<forward name="key" path="/me.jsp"/>
<forward name="key1" path="/me1.jsp"/>
       </action>
    </action-mappings>

<!-- ========== Controller ============ -->
<controller
    processorClass="org.apache.struts.action.RequestProcessor"
       contentType="text/html"/>;

    <!-- ========== Message Resources ============ -->
    <message-resources parameter="MyWebAppResources" null="false" />

<!-- ========== PlugIns ============ -->
<plug-in className="org.apache.struts.tiles.TilesPlugin">
    <set-property property="definitions-config"         value="/WEB-INF/tiles-defs.xml"/>
</plug-in>
        
</struts-config>

<!-- ========== All about Configuration File ============ -->

Read more...

Tiles Simple Program?

>> Tuesday, June 21, 2011


Simple Struts program Using Tiles

Welcome to Struts Tiles Component.Tiles is a templating system.It can be used to create a common look and feel for a webapplication.This can be used to  reusable view components.

The main features of Tiles:                                                               

    Inheritance mechanism on definitions
    Common layouts with overriding mechanism
    Dynamic page reload based on parameter layout
    We can load different tiles according to LocaleInternationalization(i18).
    It is possible to load different Tiles according to a key.

The additional elements to develop Tiles application

    layout.jsp
    tiles-defs.xml


These two elements we have to add our struts application.
step1. Develop your jsp pages to create layout to your application.

here i am using header,body,footer this is layout.If you perform some action in body part the page will be replaced with bodyone.jsp page.It means body.jsp is going to overriden by bodyone.jsp based on struts configurations.

step2. Create a layout by using the three pages.

step3. If you are using html,tiles tld files in your jsp pages dont forget to configure in web.xml as taglib.Configure the tld files in WEB-INF folder.
<jsp-config>
  <taglib>
   <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>
  <taglib>
   <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
 </jsp-config>

step4. Develop web.xml with all tags.(best to copy and paste in you application).

step5. Develop tiles-defs.xml with definitions.

Here the mappings can be done to perticular attribute name given in jsps and the path of perticular jsp pages.The definition name and parent definition name which is extending to antoher definition.
<definition name="layout" path="/layout.jsp"> 
         <put name="header" value="/header.jsp">
         <put name="body" value="/body.jsp">
         <put name="footer" value="/footer.jsp">   
 </put></put></put></definition>
 
 <definition extends="layout" name="bodypart"> 
         <put name="body" value="/bodyone.jsp">   
 </put></definition>
step6. Configure tiles plugin in struts-config.xml with action path and parameter to forward in the layout.
<plug-in classname="org.apache.struts.tiles.TilesPlugin">
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml">      
        <set-property property="moduleAware" value="true">
    </set-property></set-property></plug-in>
Based on the path given in addressbar the action will be done in struts-config.xml.
<action-mappings>
        <action parameter="layout" path="/tiles" type="org.apache.struts.actions.ForwardAction">
        
        <action parameter="bodypart" path="/bodypart" type="org.apache.struts.actions.ForwardAction">
    </action></action></action-mappings>
Start your Server(Tomcat) and run your application by giving this url in addressbar
http://localhost:8080/TilesDemo/tiles.do
The Given programs for this application:
                  1).header.jsp
<%@ 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>
  <center>Header to my Site</center>
</body>
</html>
2.)body.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
     
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<!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>
 
<center><h3>Body to my Site
</br></h3><html:link action="/bodypart">Click</html:link> </center>
</body>
</html>
3.)footer.jsp
<%@ 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>
  <center>Footer to my Site
 
  <a href="http://javabynataraj.blogspot.com">http://javabynataraj.blogspot.com</a></center>
</body>
</html>
4.)bodyone.jsp
<%@ 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>
 <center><h3><font color="red">Body One to my Site</font></h3></center>
</body>
</html>
6.)layout.jsp
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
 
<table border=2 width="50%">
<tr>
 <td bgcolor="pink"><tiles:insert attribute="header" /></td>
</tr>
 
<tr>
<td><tiles:insert attribute="body" /></td>
</tr>
 
<tr>
 <td bgcolor="pink"><tiles:insert attribute="footer" /></td>
</tr>
 
</table>
7.)tiles-defs.xml
<?xml version="1.0" encoding="UTF-8" ?>
 
 <!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
       "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
        
<tiles-definitions>
 <definition name="layout" path="/layout.jsp">
         <put name="header" value="/header.jsp" />
         <put name="body"   value="/body.jsp" />
         <put name="footer" value="/footer.jsp" />  
 </definition>
  
 <definition name="bodypart" extends="layout">
         <put name="body"   value="/bodyone.jsp" />  
 </definition>
</tiles-definitions>
8.)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  
 <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>
 
 <session-config>
  <session-timeout>30</session-timeout>
 </session-config>
 
 <welcome-file-list>
  <welcome-file></welcome-file>
 </welcome-file-list>
 
 <jsp-config>
  <taglib>
   <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>
  <taglib>
   <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
 </jsp-config>
</web-app>
<tiles-definitions>
 <definition name="layout" path="/layout.jsp">
         <put name="header" value="/header.jsp" />
         <put name="body"   value="/body.jsp" />
         <put name="footer" value="/footer.jsp"/>
</defination>
9.)struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
 
<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
 
<struts-config>
 
    <form-beans></form-beans>
     
    <global-exceptions></global-exceptions>
 
    <global-forwards></global-forwards>
 
    <action-mappings>
        <action path="/tiles" parameter="layout" type="org.apache.struts.actions.ForwardAction"/>
         
        <action path="/bodypart" parameter="bodypart" type="org.apache.struts.actions.ForwardAction"/>
    </action-mappings>
     
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
     
    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />     
        <set-property property="moduleAware" value="true" />
    </plug-in>
     
</struts-config>
After running the application the output looks like below screen
  By clicking the hyperlink the next screen looks like below

                      

Read more...

Struts Dispatch Action Example?

>> Monday, June 20, 2011





Dispatch Action 
               DispatchAction provides a mechanism for grouping a set of related functions into a single action,
thus eliminating the need to create seperate actions for each functions. In this example we will see
how to group a set of user related actions like add number , subtract number , multiply number and
dividing numbers  into a single action called UserAction.

The class UserAction extends org.apache.struts.actions.DispatchAction. This class does not provide an
implementation of the execute() method as the normal Action class does. The DispatchAction uses the
execute method to manage delegating the request to the individual methods based on the incoming request parameter.
For example if the incoming parameter is "method=add", then the add method will be invoked. These methods should
have similar signature as the execute method.

Let us look the Example:

Step1:
   Take a jsp named as Calculate.jsp

  

<%@ 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">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<title>Insert title here</title>
</head>
<body>
 <h2>Do your Calculations</h2>
 <html:form action="/calc.do">
 <table>
 <tr>
  <td width="60%">
  Enter First Number:<html:text property="fno"></html:text><br>
  Enter Second Number:<html:text property="sno"></html:text><br>
  
  
  <html:submit property="method" value="add">add</html:submit>
  <html:submit property="method" value="sub">sub</html:submit>
  <html:submit property="method" value="mul">mul</html:submit>
  <html:submit property="method" value="div">div</html:submit>
  </td>
  <td><img src="http://www.accountservonline.com/images/calculator_djk3.jpg" height="100" width="150"></img></td> 
 </tr>

 </table>
 </html:form>
 
 </body>
</html>

 Take a FormBean Class i.e CalculateForm.java
package com.bhaskar.dispatch;

import org.apache.struts.action.ActionForm;

public class CalculateForm extends ActionForm{
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 private int fno;
 private int sno;
 
 
 public int getFno() {
  return fno;
 }
 public void setFno(int fno) {
  this.fno = fno;
 }
 public int getSno() {
  return sno;
 }
 public void setSno(int sno) {
  this.sno = sno;
 }
 
 

}
Take An Action Class Which extends DispatchAction i.e CalculateAction.java
package com.bhaskar.dispatch;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class CalculateAction extends DispatchAction {
  
 private int a = 0;
 private int b = 0;
 private int c1 = 0;
 Calculate c;
 ArrayList al=null;
 
 public String key="";
 
 public ActionForward add(ActionMapping maping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
  CalculateForm cf = (CalculateForm)form;
  a = cf.getFno();
  b = cf.getSno();
  c1 = (a+b);
  Calculate c=new Calculate();
  c.setResult(c1);
  c.setFno(a);
  c.setSno(b);
  al=new ArrayList();
  al.add(c);
  HttpSession session=request.getSession();
  session.setAttribute("add", al);
  return maping.findForward("add1");
 }
 
 public ActionForward sub(ActionMapping maping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
  CalculateForm cf = (CalculateForm)form;
  
  a = cf.getFno();
  b = cf.getSno();
  if(a>b){
   c1 = (a-b);
   Calculate c=new Calculate();
   c.setResult(c1);
   c.setFno(a);
   c.setSno(b);
   al=new ArrayList();
   al.add(c);
   HttpSession session=request.getSession();
   session.setAttribute("sub", al);
   
  }
  
  else{
   
   c1 = (b-a);
   Calculate c=new Calculate();
   c.setResult(c1);
   c.setFno(a);
   c.setSno(b);
   al=new ArrayList();
   al.add(c);
   HttpSession session=request.getSession();
   session.setAttribute("sub", al);
  }
  
  return maping.findForward("sub1"); 
 }
 
 public ActionForward mul(ActionMapping maping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
  CalculateForm cf = (CalculateForm)form;//It is  a Dto Class
  a = cf.getFno();
  b = cf.getSno();
  c1 = (a*b);
  Calculate c=new Calculate();
  c.setResult(c1);
  c.setFno(a);
  c.setSno(b);
  al=new ArrayList();
  al.add(c);
  HttpSession session=request.getSession();
  session.setAttribute("mul", al);
  return maping.findForward("mul1"); 
 }
 
 public ActionForward div(ActionMapping maping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
  CalculateForm cf = (CalculateForm)form;
  a = cf.getFno();
  b = cf.getSno();
  if(b==0){
   c1 = 0;
   Calculate c=new Calculate();
   c.setResult(c1);
   c.setFno(a);
   c.setSno(b);
   al=new ArrayList();
   al.add(c);
   HttpSession session=request.getSession();
   session.setAttribute("div", al);
  }
  else{
  c1 = (a/b);
  Calculate c=new Calculate();
  c.setResult(c1);
  c.setFno(a);
  c.setSno(b);
  al=new ArrayList();
  al.add(c);
  HttpSession session=request.getSession();
  session.setAttribute("div", al);
  }
  
  return maping.findForward("div1"); 
 }
}


Take A Dto class DTO means Data Transfer Object(It is Same A bean class)  i.e Calculate.java
package com.bhaskar.dispatch;
public class Calculate {
 private int fno;
 private int sno;
 private int result;
 public int getFno() {
  return fno;
 }

 public void setFno(int fno) {
  this.fno = fno;
 }

 public int getSno() {
  return sno;
 }

 public void setSno(int sno) {
  this.sno = sno;
 }

 

 public int getResult() {
  return result;
 }

 public void setResult(int result) {
  this.result = result;
 }


 

}


Configuring Form uri,actionForm And action Class And Respective Jsp Pages in struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

    <form-beans>
        <form-bean name="Calculator" type="com.bhaskar.dispatch.CalculateForm"/>     
    </form-beans>
    
    <global-exceptions></global-exceptions>

    <global-forwards></global-forwards>
   //If you notice the signature of the add, sub,mul and div  methods are 
similar to the execute method except the name. The next step is to 
create an action mapping for this action handler. The request parameter 
name is specified using the parameter attribute. Here the request 
parameter name is method.

    <action-mappings>
        <action  parameter="method" name="Calculator" path="/calc" scope="session" type="com.bhaskar.dispatch.CalculateAction">
            <forward name="add1" path="/add.jsp" />
            <forward name="sub1" path="/sub.jsp" />
            <forward name="mul1" path="/mul.jsp" />
            <forward name="div1" path="/div.jsp" />
            
        </action>
    </action-mappings>
    <message-resources parameter="application"/>
</struts-config>

First the output looks is shown below

  
add.jsp
<%@ 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">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<logic:present name="add" scope="session">
<table cellpadding="1" cellspacing="1">
<tr>
<th>FIRST NUMBER</th>
<th>SECONDNUMBER</th>
<th>TOTAL</th>
</tr>
<logic:iterate id="c" name="add" >
<tr>
<td><bean:write name="c" property="fno"/></td>
<td><bean:write name="c" property="sno"/></td>
<td><bean:write name="c" property="result"/></td>
</logic:iterate>
</table>
</logic:present>
</body>
</html>

sub.jsp
<%@ 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">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<logic:present name="sub" scope="session">
<table cellpadding="1" cellspacing="1">
<tr>

<th>FIRST NUMBER</th>
<th>SECONDNUMBER</th>
<th>TOTAL</th>
</tr>
<logic:iterate id="c" name="sub" scope="session">
<tr>
<td><bean:write name="c" property="fno"/></td>
<td><bean:write name="c" property="sno"/></td>
<td><bean:write name="c" property="result"/></td>
</logic:iterate>
</table>




</logic:present>
</body>
</html>
mul.jsp
<%@ 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">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<logic:present name="mul" scope="session">
<table cellpadding="1" cellspacing="1">
<tr>

<th>FIRST NUMBER</th>
<th>SECONDNUMBER</th>
<th>TOTAL</th>
</tr>
<logic:iterate id="c" name="mul" scope="session">
<tr>
<td><bean:write name="c" property="fno"/></td>
<td><bean:write name="c" property="sno"/></td>
<td><bean:write name="c" property="result"/></td>
</logic:iterate>
</table>




</logic:present>
</body>
</html>
div.jsp
<%@ 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">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<logic:present name="div" scope="session">
<table cellpadding="1" cellspacing="1">
<tr>

<th>FIRST NUMBER</th>
<th>SECONDNUMBER</th>
<th>TOTAL</th>
</tr>
<logic:iterate id="c" name="div" scope="session">
<tr>
<td><bean:write name="c" property="fno"/></td>
<td><bean:write name="c" property="sno"/></td>
<td><bean:write name="c" property="result"/></td>
</logic:iterate>
</table>




</logic:present>
</body>
</html>






OUTPUT AS SHOWN BELOW IMAGES ONE AFTER ONE
 Entering Values Are 5,2
When we click on add button the outout is shown in below image





     When we click on subtract button the output shown below

        
When we click on "mul"  button the output vis shown below

         
When we click on "div"   the output is shown below
    


Read more...

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP