javax.servlet.ServletException: BeanUtils.populate


javax.servlet.ServletException: BeanUtils.populate
org.apache.struts.util.RequestUtils.populate(RequestUtils.java:497)
org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:798)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:205)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Root Cause:

java.lang.IllegalArgumentException: argument type mismatch
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:585)
org.apache.commons.beanutils.PropertyUtils.setSimpleProperty(PropertyUtils.java:1789)
org.apache.commons.beanutils.PropertyUtils.setNestedProperty(PropertyUtils.java:1684)
org.apache.commons.beanutils.PropertyUtils.setProperty(PropertyUtils.java:1713)
org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:1019)
org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:808)
org.apache.struts.util.RequestUtils.populate(RequestUtils.java:495)
org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:798)
org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:205)
org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Solution:

Fallowings are may be the reason for the above exception
1) The action attribute of an tag must match exactly the path attribute of the action definition in the struts-config.xml file. This is how Struts associates the ActionForm bean with the action.

2) This error usually occurs when you have specified a form name that does not exist in your tag. For example, you specific and ‘myForm’ is not the name of a form associated with myAction in the struts-config file

3) You get this message when Struts is unable to map the data in the HTML form to the properties in your ActionForm bean. Make sure each of the properties on your bean is either a String or a Boolean. Do you have any properties of type java.util.Date or other objects? That might cause this error. Also check to see that you have public getters and setter for each of your properties.

Struts Internationalization Example


web.xml :

<?xml version=”1.0″ encoding=”Shift_JIS”?>

<!DOCTYPE web-app
PUBLIC “-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN”
http://java.sun.com/dtd/web-app_2_3.dtd”&gt;

<web-app>
<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>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

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

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

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

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

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

</web-app>

struts-config.xml:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE struts-config PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 1.2//EN” “http://struts.apache.org/dtds/struts-config_1_2.dtd”&gt;
<struts-config>
<data-sources>
</data-sources>
<form-beans>
<form-bean name=”loginform” type=”org.apache.struts.validator.DynaValidatorForm”>
<form-property name=”username” type=”java.lang.String”></form-property>
<form-property name=”password” type=”java.lang.String”></form-property>
</form-bean>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
</global-forwards>
<action-mappings>
<action path=”/login” type=”in.javatutorials.actions.LoginAction” name=”loginform” validate=”true” input=”/login.jsp”>
<forward name=”success” path=”/welcome.jsp”></forward>
<forward name=”failure” path=”/login.jsp”></forward>
</action>
</action-mappings>
<controller locale=”true” processorClass=”org.apache.struts.tiles.TilesRequestProcessor”/>
<message-resources parameter=”ApplicationResources”/>
<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>
<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>
<set-property property=”pathnames” value=”/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml”/>
</plug-in>
</struts-config>

login.jsp :

<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>
<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-nested” prefix=”nested” %>

<html:html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=Cp1252″/>
<title></title>
</head>
<body bgcolor=”yellow”>
<center>
<html:errors/>
<bean:message key=”welcome.message”/>
<html:form method=”POST” action=”login”>
<bean:message key=”username”/><html:text property=”username”></html:text><br><br>
<bean:message key=”password”/><html:text property=”password”></html:text><br><br>
<html:submit><bean:message key=”register.submit”/></html:submit>
</html:form>
</center>
</body>
</html:html>

LoginAction.java:

 package in.javatutorials.actions;
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 org.apache.struts.validator.DynaValidatorForm;

/**
* LoginAction Class
*/

public class LoginAction extends Action {
/**
* Action class execute method
*/

public ActionForward execute(ActionMapping actionMapping,ActionForm actionForm,HttpServletRequest request,HttpServletResponse response)throws Exception{

String responseKey=”failure”;
DynaValidatorForm dynaValidatorForm=(DynaValidatorForm) actionForm;
String user=(String)dynaValidatorForm.get(“username”);
String pwd=(String)dynaValidatorForm.get(“password”);

if(user.equals(pwd))
responseKey=”success”;
return actionMapping.findForward(responseKey);

}
}

welcome.jsp :

<%@ page contentType=”text/html; charset=Cp1252″ %>
<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>
<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-nested” prefix=”nested” %>

<html:html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=Cp1252″/>
<title></title>
</head>
<body bgcolor=”green”>
<h1><bean:message key=”welcome”/></h1>
</body>
</html:html>

ApplicationResources_it.properties :

welcome.message=Dare if benevenuato all aperatoreitaliano(in english:welcome to italian user)
welcome=<b>Dare if benevenuato all aperatoreitaliano</b>
username=<b>nome de operatore</b>
password=<b>parola de ordine</b>
register.submit=registero
errors.required=<li><i>if compo di{0}non puo essere vuoto</i></li>
errors.minlength=<li><i>la {0}non puo essere vuoto {2} carreteri.</i></li>

ApplicationResources_en.properties :

welcome.message = welcome to english user
welcome=<b>Hello english user welcome to our website</b>
username=<b>username</b>
password=<b>password</b>
register.submit=register
errors.required=<li><i>{0}field cannot be empty.</i></li>
errors.minlength=<li><i>{0}cannot be lessthan {2} charecters.</i></li>

What are the differences between DispatchAction and LookupDispatchAction in Struts Framework?


Dispatch Action
LookupDispatchAction
 
It’s a parent class of  LookupDispatchAction
Subclass of Dispatch Action
DispatchAction provides a mechanism for grouping a set of related functions into asingle action, thus eliminating the need to create separate actions for each function.
An abstract Action that dispatches to the subclass mapped executes method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping.
If not using Internalization functionality then dispatch action is more useful.
 
Lookup Dispatch Action is useful when we are using Internalization functionality
 
DispatchAction selects the method to execute depending on the request parameter valuewhich is configured in the xml file.
LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method. 
DispatchAction is not useful for I18N
 
LookupDispatchAction is used for I18N
 
Find the DispatchAction Example here
Others Posts:

What design patterns are used in Struts 1.X?


Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.

  • Service to Worker
  • Dispatcher View
  • Composite View (Struts Tiles)
  • Front Controller
  • View Helper
  • Synchronizer Token

Struts MVC


Struts is MVC based framework developed by Apache. Framework generally provides the basic functionality for a project. Struts provides the set of Action classes, set of tag-libraries, set of Form beans and etc.

Struts combines the most of the design patterns in to a single framework. Struts implements the Single-ton design pattern, Delegate design pattern, Factory Design pattern, Chain of responsibilities.

Struts is Strongly Model View Controller (MVC)based framework MVC fallows the three tier architecture. The model, view and controllers regarding to the Struts are explained as fallows.

View:

View is used to show something to user. Struts allows to use htmls, jsps as view components. To develop the more friendly views struts provided the set of tag libraries. You can download these libraries from the apache site and you can use those into your view components. The set of tag libraries are

struts-html : These tags are replacement of normal html tags. The struts html tags are binds with the form bean properties.

Ex: <html:text property=”userName” />

tag replaces the normal html tag like

<input type=”text” name=”userName” />

struts-bean : These tags are replacement for the jsp action tags. The bean properties are defined with this tags, you can get the bean properties using struts-bean tags.

Ex: <bean:define id=”tempVar” value=”10” />

Above tag defines a variable as ‘tempVar’ and assign 10 to it as string value.

<bean:write name=”Employee” property=”empId” />

Above tag get the value of empId from the Employee form bean.

Struts-logic: These tags are used to write the logical operations. To validate the if conditions or equals conditions you can use these tags.

Ex: <logic:equal name=”empId” value=”100” >Adimin</logic:equal>

Admin is displayed when the empId equals to 100 only.

To get the for loop type iterations you can use the <logic:iterate /> tag.

struts-nested: To display the group of objects you can use the nested tags.

You can implement most of the functionality of above three tags with the nested tags.

Inplace of <bean:write /> you have <nested:write /> and so on…….

Model:

Business logic and persistence logic (database dependent logic) will be developed in Model. In struts you can use normal Java beans, DTOs, Dos as models. You can develop the Model layer using other tools also. Struts allows to use Hibernate, spring in the model layer.

Controller:

Controller is most important concept in the Struts 1.3. In struts ActionServlet acts as Front controller. Each and every request must passes through the ActionServlet. You can change the ActionServlet functionality by extending ActionServlet to your own class.

RequestProcessor class also acts as the controller to process the request. In struts 1.3 Request processor is the ComposableRequestProcessor. It has processXXX() methods. These methods are controls the execution of action classes, controlling of form beans ..etc.

Actions, Dispatch actions, Action Forms , Validator forms ..etc all are come under the controller.

Difference Normal HTML tags and Struts HTML tags


Apache struts provided the struts html tags as the replacement of normal html tags for the Jsps. These Struts html tags are directly bind to the form bean using ActionForm where as normal html tags cannot bind with form beans. HTML tags are static but Struts tags are Dynamic (At the run-time struts tags are called)

But coming to performance half of the code in struts tags is pre-compiled one. If we use normal html tags web container has to load the jsp from the scratch. Where as struts tags loads with the pre-compiled code. So that struts tags improves the performance.

Struts 2


The core features of the struts 2 framework:

  1. Pluggable framework architecture that allows request life cycles to be customized for each action.
  2. Flexible validation framework that allows validation rules to be decoupled from action code.
  3. Hierarchical approach to internationalization that simplifies localizing applications.
  4. Integrated dependency injection engine that manages component life cycle and dependencies. (By default, the framework utilizes Spring for dependency injection.)
  5. Modular configuration files that use packages and namespaces to simplify managing large projects with hundreds of actions.
  6. Java 5 annotations that reduce configuration overhead. (Java 1.4 is the minimum platform.)

Struts 2 request Processing:

Each and every request made using struts 2 framework fallows the same request processing as below:

  1. Initially the web browser requests for request. (Ex: /index.acion or /myreport.pdf .. etc)
  2. The filter dispatcher looks at the request and determines the appropriate action.
  3. The interceptors automatically apply common functionality to the request, like work flow, validation, and file upload handling.
  4. The action method executes, usually storing and/or retrieving information from a database.
  5. The request renders the output to the browser, be it HTML, images, pdf, or something else.

The features added in struts2 over the struts1:

  1. Programming the abstract classes instead of interfaces is one of the design problem of struts1 framework that has been resolved in struts2.
  2. Most of the struts2 classes are based on interfaces and most of its core interfaces are HTTP independent.
  3. Unlike ActionForwards, Struts2 results provide flexibility to create multiple type of outputs.
  4. Actions in struts1 have dependencies on the servlet API since HttpServlertRequest and HttpServletResponse objects are passed to the execute() Method. But in struts2 any Java class with execute() method can be used as an Action Class. Actions to be neutral to the underlying framework
  5. ActionForms feature is no more known to the struts2 framework. Simple Java Bean flavored actions are used to put properties directly.
  6. Struts2 actions are HTTP independent and framework neutral. This enables to test struts2 applications very easily with out resorting mock objects.
  7. Struts2 tags enables to add style sheet driven markup capabilities.  ie. You can create consistent pages with less code. Struts2 tag markup can be altered by changing an underlying stylesheet.
  8. Struts tags are more capable and result oriented.
  9. Both JSP and Free maker tags are fully supported.
  10. Java 5 annotations can be used as an alternative to XML and Java properties configuration.
  11. Struts 2 check boxes do not require special handling for false values.
  12. Many changes can be done on fly without restarting the web container.
  13. Struts1 lets to customize the request processor per module. Struts2 lets to customize request handling per action if desired.
  14. Struts 2 Actions are spring aware. Just need to add spring beens.
  15. Struts2 extensions can be added by dropping in jar. No need of any addition XML or properties files. Metadata is expressed through convention and annotations.

Ajax support in Struts2:

  1. AJAX client side validation
  2. Remote form submission support (works with the submit tag as well)
  3. An advanced div template that provides dynamic reloading of partial HTML
  4. An advanced template that provides the ability to load and evaluate JavaScript remotely
  5. An AJAX-only tabbed Panel implementation
  6. A rich pub-sub event model
  7. Interactive auto complete tag

Struts1 and Struts2 at a glance:

Struts 1 vs. Struts 2

  1. Action                                    Action
  2. ActionForm                        Action or POJO
  3. ActionForward                  Result
  4. struts-config.xml              struts.xml
  5. ActionServlet                     FilterDispatcher
  6. RequestProcessor             Interceptors
  7. validation.xml                    Action-validation.xml