Monday, April 18, 2011

DynaAction

Q).what is a DynaAction?
Why actually we need DynaAction Form this is the real question,one proverb is there "necessity is the mother of invention " this proverb is applicable here.

Starting from Struts 1.0 where we are having one jsp page ,one form bean  is there which has all setter() and getter() mehod and one action class is there which has the execute() method,there was a overhead of creating a form bean for ever method, so they came up with the idea of DynaActionForm bean, where all the from properties are defined in the Struts configuration file,so that creation of the concrete class can be avoided.

<form-beans>
    <form-bean name="LoginForm" type="org.apache.struts.action.DynaActionForm">
        <form-property name="userName" type="java.lang.String" />
       <form-property name="password" type="java.lang.String" />
    </form-bean>
</form-beans>
 
Then came Struts2 where there is a single java class, where we are having all the from properties and the execute() method,so if you had noticed there nothing called DynaAction Form in Struts2.0,since all the form properties are defined in the action class it shelf,no need to define the form  properties in the sturts configuration file .



Exapmle of DiapatchAction in Struts2

There is a little bit of difference in DispatchAction Functionality in Struts1.x and Struts2.0.
We would talk about DispatchAction in Struts2.0 since it is somewhat simpler.
Before taking this example I guess  you must be knowing what actually is a DispatchAction if not please go through this,what actually is a DispatchAction and why it is needed is explained in simple words.
http://rathursp.blogspot.com/2011/04/what-is-dispatchaction-in-struts2.html

Guess now you must have little bit of idea about DispatchAction
Its good to start..

we would create a form with multiple buttons on it,such that each button will have different action to perfrom.

index.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="/struts-tags" prefix="s" %>
<html>
<head> 
 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="User" >
<s:submit />
<s:submit action="addUser" value="Add" />
<s:submit action="updateUser" value="Update" />
<s:submit action="deleteUser" value="Delete" />
</s:form>
</body>
</html>
 
 
struts.xml 
Configure struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="User" class="rathur.UserAction">
            <result name="success">/success.jsp</result>
        </action>      
        <action name="addUser" method="add" class="rathur.UserAction"> 
/*will call the add() declared in pkg rathur.UserAction*/
            <result name="success">/success.jsp</result> 
/*it will check if the add() has returned success then it will go to the success.jsp page*/
        </action>
        <action name="updateUser" method="update" class="rathur.UserAction">
            <result name="success">/success.jsp</result>
        </action>
        <action name="deleteUser" method="delete" class="rathur.UserAction">
            <result name="success">/success.jsp</result>
        </action>  
    </package>
</struts>
notice we are having same UserAction for all the action mapping.
when the requested URL is User the execute() of UserAction would be called,
when the requested url is addUser the add() in the UserAction is called.
UserAction.java

package rathur;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

    private String message;
        public String execute()
       {
        message = "Inside execute method";
        return SUCCESS;   
       }
       public String add()
      {
        message = "Inside add method";
        return SUCCESS;          /* these return would be checked in struts.xml  */ 
      }
      public String update()
      {
        message = "Inside update method";
        return SUCCESS;       
       }
      public String delete()
     {
       message = "Inside delete method";
        return SUCCESS;       
      }
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}



success.jsp

create a success.jsp page
<%@ 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>
${message}
</body>
</html>


output





hi if you got the required output please do comment. :-)





Sunday, April 10, 2011

what is dispatchaction in struts

Q)explain dispatchaction.
Q)what is a dispatch action.
Q)dispatchaction in struts

When we talk about struts,when we go for creating a form we need three things.
1.jsp page
2.login form.
3.login action
since we show that for creating a form be need to create three differnt file,if our application involve multiple (x)form there would be overhead of creating 3*x file.Inorder to prevent this we came up with the idea of DispactchAction,where multiple action class is not required,in one action class we can declare the implementation of  i.e business logic of all the form.




Thursday, April 7, 2011

dispatchaction in struts2

Dispatch Action

Basically Dispatch action is used when you have multiple submit buttons in a single form.
The Dispatch action is a class which extends the Struts DispatchAction,
and encpsulates all the action methods (similar to execute method in Action class)
in one single class.
In the Struts-Config.xml you need to define the DispatchAction class and the parameter name that you passing in the URL.
Based on the parameter the Controller will invoke the action method.

The DispatchAction is a special Action class within Struts
that allows different functions to be called depending on a value of a parameter in a request object

Every Action in the JSP page need not have a different/Separate Action class to handle the request.
Instead one Dispatch Action class can handle all this.
Basing on the action selected a value is passed to the Dispatch Action and the corresponding method gets executed which
would handle the Action. Dispatch Action extends the Action class.
This way the Dispatch Action reduces the Developement time and also eases the process of maintenance.

DispatchAction is another useful built-in Struts Action. However you cannot use it as is.
You will have to extend it to provide your own implementation.

An interesting thing to notice is that the value of the HTTP
request parameter named step is same as the four method names in CreditAppAction
http://localhost:8080/bank/screen-credit-app.do?step=reject&id=2 
http://localhost:8080/bank/screen-credit-app.do?step=approve&id=2    
http://localhost:8080/bank/screen-credit-app.do?step=addComment&id=2

DispatchAction knows what parameter to look for in the incoming URL
request through this attribute named parameter in struts-config.xml.
(the request parameter that will uniquely identify all actions.)
the arguments and their order in these methods is fixed by DispatchAction
the method invocation by reflection at runtime is successful.

uploading image and displaying

FileUploadAction.java


package net.viralpatel.struts2;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
        ServletRequestAware {
 private File userImage;
 private String userImageContentType;
 private String userImageFileName;

 private HttpServletRequest servletRequest;

    @Override
  public String execute() {
       try {

           String filePath = servletRequest.getRealPath("/");
           System.out.println("Server path:" + filePath);
           File fileToCreate = new File(filePath, this.userImageFileName);

           FileUtils.copyFile(this.userImage, fileToCreate);
       } catch (Exception e) {
            addActionError(e.getMessage());

         return INPUT;
       }
       return SUCCESS;
 }

   public File getUserImage() {
        return userImage;
   }

   public void setUserImage(File userImage) {
      this.userImage = userImage;
 }

   public String getUserImageContentType() {
       return userImageContentType;
    }

   public void setUserImageContentType(String userImageContentType) {
      this.userImageContentType = userImageContentType;
   }

   public String getUserImageFileName() {
      return userImageFileName;
   }

   public void setUserImageFileName(String userImageFileName) {
       this.userImageFileName = userImageFileName;
 }

   @Override
   public void setServletRequest(HttpServletRequest servletRequest) {
      this.servletRequest = servletRequest;

   }
}





UserImage.jsp


This is done using the struts2.0  framework,you need to have the plugin for it.


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
<s:file name="userImage" label="User Image" />

<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>

SuccessUserImage
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>

</head>
<body>
   <h2>Struts2 File Upload Example</h2>
  
 User Image: <s:property value="userImage"/>

 Content Type: <s:property value="userImageContentType"/>

 File Name: <s:property value="userImageFileName"/>

 Uploaded Image:


 <img src="<s:property value="userImageFileName"/>"/>
</body>
</html>


struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="example.xml"/>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="userImage"
    class="net.viralpatel.struts2.FileUploadAction">
    <interceptor-ref name="fileUpload">
          <param name="maximumSize">2097152</param>

          <param name="allowedTypes">
              image/png,image/gif,image/jpeg,image/pjpeg
         </param>
     </interceptor-ref>
       <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success">SuccessUserImage.jsp</result>

      <result name="input">UserImage.jsp</result>
</action>
    </package>
</struts>
 
output




java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...