ActionMessage in struts

hi
ActionError was deprecated in struts 1.2.so instead of "ActionError" we are using " ActionMessage". my doubts are
1.What actually "ActionMesages" class will do .is it's functioning is similar to
"ActionErrors" class. anyway "ActionErrors" was not deprecated.so what is
the need of "ActionMessages" class.
2.to display "ActionErrors" in our jsp we use <html:errors/>.can we use this for "ActionMessages" errors or we have to use "<html:messagesPresent>".
please clear me usage and concepts of "ActionMessage" ,"ActionMessages".

thnks for your reply .I tried an example by using both "ActionMessages" and "ActionMessage".but the problem is "eventhough there is an error it's not displaying that error.if i used "ActionErrors" iam able to see that error.I am mentioning hte code .plz tell me where the mistake is ..
Jsp file:---------------------
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="netui-tags-databinding.tld" prefix="netui-data"%>
<%@ taglib uri="netui-tags-html.tld" prefix="netui"%>
<%@ taglib uri="netui-tags-template.tld" prefix="netui-template"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic"%>
<!--
<html:errors />
-->
<logic:messagesPresent>
<html:messages id="msg" locale="fr">
<b><bean:write name="msg" /></b><br><br><hr>
</html:messages>
</logic:messagesPresent>
<html:form action="/myservice2">
<bean:message key="app.user" />:::
<html:text property="user"/>
<br>
<bean:message key="app.name" />:::
<html:text property="name"/>
<html:submit value="submit"/>
</html:form>
Action class--------------------
package com.action;
import com.form.Lookform;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.Globals;
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.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class actionmess extends Action
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest req,HttpServletResponse res)
{String target;
Lookform f=(Lookform) form;
String user=f.getUser();
if(user.endsWith("88"))
target="failure";
ActionMessages errors=new ActionMessages();
errors.add("myerror",new ActionMessage("myerror.errors"));
saveMessages(req,errors);
else
target="success";
return mapping.findForward(target);
validate() method in Action form returns only ActionErrors.that's why i mention "ActionMessages" in "execute()" method of Action class.
I tried both <html:errors/> ,<html:messages> but i am unable to see errors.

Similar Messages

  • Displaying "Literal" ActionMessage in Struts 1.2.7

    Hi!
    Sorry, I have posted this topic before, but I haven't got an answer, so here's a second try.
    I need some help concerning a new feature in Struts 1.2.7.
    The ActionMessage class now has a new Constructor.
    ActionMessage(java.lang.String key, boolean resource)Setting the "resource" value to "false" allows you to define a "literal"
    Message without having to specify a key in the properties bundle. It will
    display exactly the string that is given in the 'key' argument.
    In my Action Class, I create two or more ActionMessages:
    ActionErrors errors = new ActionErrors();
    ActionMessage error1 = new ActionMessage("Literal Error 1", false);
    errors.add(ActionMessages.GLOBAL_MESSAGE, error1);
    ActionMessage error2 = new ActionMessage("Literal Error 2", false);
    errors.add(ActionMessages.GLOBAL_MESSAGE, error2);
    saveErrors(request, errors);In my JSP, I iterate over the ActionMessages in the follwing way:
    <table>
      <html:messages id="errors">
        <tr>
          <td>
            <bean:write name="errors"/>
          </td>
        </tr>
      </html:messages>
    </table>The poblem now is that in the HTML-Output, only the first Item in the Error
    list appears as a literal message, whereas Struts seems to interpret the next message as a resource key:
    - Literal Error 1
    - ???de.Literal Error 2???
    What could be the problem? Any help is appreciated!
    Thanks, Ren�

    Sorry, the same Message as above, now correctly formatted:
    I need some help concerning a new feature in Struts 1.2.7.
    The ActionMessage class now has a new Constructor
    ActionMessage(java.lang.String key, boolean resource)Setting the "resource" value to "false" allows you to define a "literal"
    Message without having to specify a key in the properties bundle.
    In my Action Class, I create two or more ActionMessages:
    ActionErrors errors = new ActionErrors();
    ActionMessage error1 = new ActionMessage("Literal Error 1", false);
    errors.add(ActionMessages.GLOBAL_MESSAGE, error1);
    ActionMessage error2 = new ActionMessage("Literal Error 2", false);
    errors.add(ActionMessages.GLOBAL_MESSAGE, error2);
    saveErrors(request, errors);In my JSP, I iterate over the ActionMessages in the follwing way:
    <table>
              <html:messages id="errors">
                   <tr>
                        <td>
                             <bean:write name="errors"/>
                        </td>
                   </tr>
              </html:messages>
    </table>The poblem now is that in the HTML-Output, only the first Item in the Error
    list appears as a literal message, whereas Struts seems to interpret the next message as a resource key:
    - Literal Error 1
    - ???de.Literal Error 2???
    What could be the problem? Any help is appreciated!
    Thanks, Ren�

  • How to resolve Warning? -- in Struts

    Hi all,
    I am doing a mini project in STRUTS.
    All the code i did so far is fine and working fine.
    Now i am trying to add additional functionalities in login section in my project. To reflect the errors in the same Jsp file
    I had imported both
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionErrors;
    both classes..
    I am getting the warning --- "Warning -[ deprication ]org.apache.struts.action.ActionError in org.apache.struts.action has been depricated "
    Please le me know how to solve this one.
    Thanks,
    oreh

    Dont worry on the warnings. I was getting the same as well and the code still works. But its better to handle warnings for deprecations.
    Ideally ...instead of using ActionErrors its required to use another class i.e. ActionMessages in struts 1.2
    Use add("variable",ActionMessage) instead of add("variable",ActionError)
    Also in your Action form if you are using the validate method then change the following ...
    public ActionErrors validate(ActionMapping mapping,
                   HttpServletRequest request) to
    public ActionMessages validate(ActionMapping mapping,
                   HttpServletRequest request) Cheers
    -Rohit
    I havent swicthed over to the ActionMessages yet but it seems that html:errors tag has been deprecated in favour of html:messages. Check it out if this works well .
    Message was edited by:
    RohitKumar

  • Displaying Success/failurre messages in a struts landing page.

    Hi,
    I am selecting some values from a landing page, going to add/update page andthen submitting the data from add/update.
    After that the control comes to the landing page and I am displaying the message " successfully edited" in the landing page.
    Now the problem is if I come to landing page from any other page after this operation, the old message is still retained.
    how to overcome this?
    I am writing the messgaes to the session and retrieving it in the JSP page(Struts).
    Thanks,
    Dommu

    domstom wrote:
    Hi,
    I am selecting some values from a landing page, going to add/update page andthen submitting the data from add/update.
    After that the control comes to the landing page and I am displaying the message " successfully edited" in the landing page.
    Now the problem is if I come to landing page from any other page after this operation, the old message is still retained.
    how to overcome this?
    I am writing the messgaes to the session and retrieving it in the JSP page(Struts).
    Thanks,
    DommuWell if i were you i'd have define and ActionError object and would have have added respective status message under respective action method and could have forwaded it to the respective landing View and render it accordingly using <html:errors/> tag.
    or to put it in simple in struts 1.3 i'd have used the below methods.
    [http://struts.apache.org/1.x/struts-core/apidocs/org/apache/struts/action/Action.html#addErrors(javax.servlet.http.HttpServletRequest,%20org.apache.struts.action.ActionMessages)]
    [http://struts.apache.org/1.x/struts-core/apidocs/org/apache/struts/action/Action.html#addMessages(javax.servlet.http.HttpServletRequest,%20org.apache.struts.action.ActionMessages)]
    And i'd advice you to go through Best Practices which we can follow at the time of Application Devolopment using struts-1.2 framework in front-controller tier.
    [http://www.ibm.com/developerworks/web/library/wa-struts/]
    Hope that might help :)
    REGARDS,
    RaHuL

  • Struts - Problem with ActionMessages

    Hi everyone:
    Here is my problem: This is the code in my action class
    catch (Exception e){
                        ActionMessages errors = new ActionMessages();
                        if (e instanceof DatabaseException)
                             errors.add("error", new ActionMessage("errors.database", e
                                       .getMessage().toString()+" Hay un error en la BD"));
                        else
                             errors.add("error", new ActionMessage("error", e
                                       .getMessage().toString()+" Hay un error"));
                        saveMessages(request, errors);
                        System.out.println(errors.size());
                        res = mapping.findForward("repetimos");
                   }I print the errors.size in order to check if it's not empty. Well, it's size is 1.
    In my jsp my code is this:
    <logic:messagesPresent message="true">
         <html:messages id="error" message="true">
              <c:out value="${error}" />
         </html:messages>
    </logic:messagesPresent>But I don't get any message when an error occurs. Am I doing anything wrong? I can't see the fail.
    I appreciate very much your attention. Thanks a lot

    In your action do you add errors to the Request or Session? It's been a while since I have worked with struts. Looking back I think we used lists to contain our error messages and displayed them in our JSP.

  • ClassNotFoundException ActionMessage Struts 1.3.5

    Hello,
    When I try to use the ActionMessage class in a class that is not an Action or Form, I get a ClassNotFoundException.
    I have the following function in a common utility class.
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionMessage;
    public static void creatNetfError(String errorCode, ActionErrors errors)
    if (errorCode == null)
    errors.add("keyError", new ActionMessage("title.error.msg"));
    else
    errors.add("title", new ActionMessage("title.error.msg", errorCode));
    errors.add("description", new ActionMessage("error.msg"+errorCode));
    Then call it in my Action class:
    ActionErrors errors = new ActionErrors();
    CommonUtil.creatNetfError(request.getParameter("errorCode"), errors);
    this.saveErrors(request, errors);
    I get the following two exceptions (expanded format is attached at the end):
    java.lang.NoClassDefFoundError: org/apache/struts/action/ActionMessage
    java.lang.ClassNotFoundException: org.apache.struts.action.ActionMessage
    This seems to happen if I call org.apache.struts.util.MessageResources, or org.apache.struts.util.ActionErrors in an outside helper class as well. I haven't seen anything in the documentation discouraging use of this package in other classes. Am I missing something? Usually when I get a ClassNotFoundException it is because I am missing a jar file, but in this case I am able to use the classes directly in the Action so that leads me to believe the jar file is installed correctly. Is it possible it is installed incorrectly?
    Can anybody point my search in the right direction please?
    Thank you
    Alfreda
    java.lang.NoClassDefFoundError: org/apache/struts/action/ActionMessage
    at ca.gc.cra.ghnf.netf.util.CommonUtil.creatNetfError(CommonUtil.java:428)
    at ca.gc.cra.ghnf.netf.web.actions.HelpAction.execute(HelpAction.java:40)
    at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:53)
    at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:64)
    at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:48)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
    at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
    at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:280)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1858)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:446)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3495)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Unknown Source)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2180)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2086)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1406)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)
    java.lang.ClassNotFoundException: org.apache.struts.action.ActionMessage
    at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:283)
    at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:256)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
    at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:176)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    at ca.gc.cra.ghnf.netf.util.CommonUtil.creatNetfError(CommonUtil.java:428)
    at ca.gc.cra.ghnf.netf.web.actions.HelpAction.execute(HelpAction.java:40)
    at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:53)
    at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:64)
    at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:48)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
    at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
    at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
    at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:280)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1858)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:446)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:292)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3495)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Unknown Source)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2180)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2086)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1406)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)

    Look like your classpath is a mess. Clean it up. Place the libraries only there where they belong and remove any older versioned duplicates.

  • Unable to retrive the uploaded file in Struts

    hi i am getting error while retrieving the uploaded file in struts. The code is
    struts-config.xml
    ===========
    <form-bean name="GreivanceForm" type="org.apache.struts.validator.DynaValidatorActionForm" >
                   <form-property name="compcode" type="java.lang.String" />
                   <form-property name="complaintName" type="java.lang.String" />
                   <form-property name="category" type="java.lang.String" />
                   <form-property name="subcategory" type="java.lang.String" />
                   <form-property name="priority" type="java.lang.String" />
                   <form-property name="occdate" type="java.lang.String" />
                   <form-property name="occtime" type="java.lang.String" />
                   <form-property name="desc" type="java.lang.String" />
                   <form-property name="comments" type="java.lang.String" />
                   <form-property name="onbehalf" type="java.lang.String"/>
                   <form-property name="employeeId" type="java.lang.String"/>
                   <form-property name="hidSelectedNames" type="java.lang.String"/>
                   <form-property name="individual" type="java.lang.String"/>
                   <form-property name="compOption" type="java.lang.String" />
                   <form-property name="selectedrequestor" type="java.lang.String" />
                   <form-property name="file" type="java.lang.String"/>
              </form-bean>
    <action path="/helpdesk/GrievanceComplaint"
                   type="com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintAction"
                   scope="request" name="GreivanceForm"
                   input=""
                   validate="true"
                   parameter="compOption" >
                   <forward name="success" path="/helpdesk/GrievanceRedressalMechanism/ComplaintDetails.jsp"/>
                   <forward name="showmeetingform" path="/helpdesk/complaint/MeetingDetailsForm.jsp"/>
                   <forward name="transconfirm" path="/helpdesk/GrievanceRedressalMechanism/TransConfirm.jsp"/>
                   <forward name="ViewCompForm" path="/helpdesk/GrievanceRedressalMechanism/ViewCompForm.jsp"/>
              </action>
    and
    Actionclass:
    ========
    * Created on Nov 5, 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package com.srit.hrnet.helpdesk.grievancemechanism;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.List;
    import java.util.StringTokenizer;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.commons.beanutils.BeanUtils;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;
    import org.apache.struts.action.ActionMessages;
    import org.apache.struts.action.DynaActionForm;
    import org.apache.struts.actions.DispatchAction;
    import org.apache.struts.upload.FormFile;
    import org.apache.struts.validator.DynaValidatorActionForm;
    import org.apache.struts.validator.DynaValidatorForm;
    import com.srit.hrnet.components.SequenceCodeGenerator;
    import com.srit.hrnet.emp.EmployeeGenTO;
    import com.srit.hrnet.emp.courier.CourierMailDAO;
    import com.srit.hrnet.emp.courier.CourierMailTO;
    import com.srit.hrnet.emp.parameter.ParamMasterTO;
    import com.srit.hrnet.helpdesk.SessionValidate;
    import com.srit.hrnet.helpdesk.category.CategoryDAO;
    import com.srit.hrnet.helpdesk.category.CategoryTO;
    import com.srit.hrnet.helpdesk.mails.HDMail;
    import com.srit.hrnet.utilities.DateUtilities;
    import com.srit.hrnet.helpdesk.complaint.TaskDAO;
    import com.srit.hrnet.helpdesk.SessionValidate;
    import com.srit.hrnet.helpdesk.grievancemechanism.GrievanceComplaintForm;
    public class GrievanceComplaintAction extends DispatchAction{
         public ActionForward submitForm(ActionMapping mapping,
                   ActionForm form, HttpServletRequest request,
                   HttpServletResponse response)throws ServletException,IOException {  
                   String msg=null;
                   DynaValidatorActionForm objDyna = (DynaValidatorActionForm)form;
                   GrievanceComplaintDAO gcDao= new GrievanceComplaintDAO();
              ActionForward forward = new ActionForward();
    //          GrievanceComplaintForm gcForm=(GrievanceComplaintForm)form;
                        String CompId = null;
              try
                             SequenceCodeGenerator seq=new SequenceCodeGenerator("GrievanceMechanism");
                             CompId=seq.generateCode();
                   GrievanceComplaintTO gcTO=new GrievanceComplaintTO();
                   System.out.println("Inside GrievanceComplaintAction ......");
                   String CompName=request.getParameter("complaintName");
                   String Category=request.getParameter("category");
                   String prority=request.getParameter("priority");
                   String dateofocc=request.getParameter("occdate");
                   String timeofocc=request.getParameter("occtime");
                   String desc=request.getParameter("desc");
                   String comments=request.getParameter("comments");
    //          String file=request.getParameter("file");
    //          String complaintcode = .generateCode();
                   System.out.println("Inside insert()::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
                   System.out.println("Name Of the Complaint name>>>>>>>>>>>>>>"+CompName);
                   System.out.println("Name Of the Categoryt>>>>>>>>>>>>>>"+Category);
                   System.out.println("Name Of the prority>>>>>>>>>>>>>>"+prority);
                   System.out.println("Name Of the dateofocc>>>>>>>>>>>>>>"+dateofocc);
                   System.out.println("Name Of the timeofocc>>>>>>>>>>>>>>"+timeofocc);
                   System.out.println("Name Of the desc>>>>>>>>>>>>>>"+desc);
                   System.out.println("Name Of the comments>>>>>>>>>>>>>>"+comments);
    //          System.out.println("Name Of the file>>>>>>>>>>>>>>"+file);
                   GregorianCalendar occdate=DateUtilities.getGCDateForString(objDyna.getString("occdate"),((com.srit.hrnet.emp.EmployeeGenTO)request.getSession().getAttribute("LoginUser")).getDateFormat(),'/');
                   gcTO.setComplaintCode(CompId);
                   gcTO.setComplaintName(CompName);
                   gcTO.setCategory(Category);
                   gcTO.setPriority(prority);
                   gcTO.setOccdate(occdate);
                   System.out.println("After Setting date in GTO is>>>>>>>>>>>>>>"+gcTO.getOccdate());
                   gcTO.setOcctime(timeofocc);
                   gcTO.setDesc(desc);
                   gcTO.setComments(comments);
                        HDMail mailComp = new HDMail();
                   String errorFlag = null;
                   String filePath = ""+objDyna.get("file");// Attachment path
                   StringTokenizer st=new StringTokenizer(filePath,".");
                   String extension=null;
    //               String filename=null;
                   String attachmentPath = null;
                   while(st.hasMoreTokens())
                        extension=st.nextToken();
    //          while(st1.hasMoreTokens()){
    //               filename=st1.nextToken();
                   System.out.println("Attachment path : "+attachmentPath);
              System.out.println("Extension is.........."+extension);
    //          System.out.println("Name of the file is.............."+filename);
              if(filePath != null && filePath.indexOf(".") != -1 && filePath.length()>=5 ){// If attachment exists
    //               attachmentPath = filePath.substring(filePath.indexOf(".")+1,filePath.length());// file extension
    ////               System.out.println("Attachment path : "+attachmentPath);
                   if(!extension.equalsIgnoreCase("txt") && !extension.equalsIgnoreCase("htm")
                             &&!extension.equalsIgnoreCase("doc") &&!extension.equalsIgnoreCase("rtf")
                                       &&!extension.equalsIgnoreCase("msg") &&!extension.equalsIgnoreCase("oft")
                                       && !extension.equalsIgnoreCase("xls")){
                        errorFlag = "1"; // if the file is not a valid type (not in the above mentioned extensions)
              gcTO.setAttachmentName(filePath);
              if(errorFlag.equals("1")){
    //          String attachmentName = null;
    ////          String attachmentPath = request.getParameter("agendaAttachment");
    //          DynaValidatorForm dyna=(DynaValidatorForm)form;
    //                         FormFile file= (FormFile)objDyna.get("file");
    //                         //dyna.get("file");      
    //          System.out.println("Name of the file after casting....."+file.getFileName());
    //                         if(file!=null && file.getFileName()!=null && !file.getFileName().trim().equals("")){
    //                              String fileName = null;                         
    //                              fileName = file.getFileName();
    //                              attachmentName = fileName;
    //                              if(validFile(fileName))
    //                              writeFile(file,request,fileName);
    //                              else
    //                                   ActionMessages errors=new ActionMessages();
    //                                   errors.add("Err:MsgDesc",new ActionMessage("com.srit.hrnet.helpdesk.complaint.form.fileupload"));                              
    //                                   saveErrors(request,errors);                         
    ////                                   ActionForward map1 = submitSubCategory(mapping,form,request,response);                              
    //                                   resetToken(request);     
    //                                   saveToken(request);
    //                                   return mapping.findForward("ViewCompForm");                              
    //                    int recordexists = gcDao.getComplaint(CompId);
    //                    if(recordexists == 1){
    //                         System.out.println("Calling the update method");
    //                         gcDao.updateComplaintDetails(gcTO);     
    //                    }else{
                        boolean retVal=gcDao.insert(gcTO);
              if (retVal){
                   System.out.println("Record Inserted inside Action.");
                   msg = "<font color='blue'>Record Inserted Successfully .</font>";
                             request.setAttribute("status", msg);
              else{
                   System.out.println("Unable to insert Record inside Action.");
                   msg = "<font color='red'>Unable to insert Record .</font>";
                             request.setAttribute("status", msg);
              else
                   System.out.println("Upload a file of extension(.jpg,.gif,.doc,.htm,.xls,.rtf,oft,msg) inside Action.");
                   msg = "<font color='red'>Upload a file of extension(.jpg,.gif,.doc,.htm,.xls,.rtf,.oft,.msg) </font>";
                             request.setAttribute("status", msg);
              catch (Exception e) {
                   // TODO: handle exception
                   System.out.println("Exception Occurred inside insert action....."+e.getMessage());
                   e.printStackTrace();
    //          else
    //               String insStatus="10";
    //               System.out.println("Accept:Redirecting due to resubmission");
    //               request.setAttribute("transStatus",insStatus);
    //               forward =mapping.findForward("transconfirm");
                   return mapping.findForward("success");
         public boolean validFile(String fileName){
              if(!fileName.equals("")){     
                        int filelength=fileName.length();
                        int sublength= fileName.indexOf('.');
                        String extension = fileName.substring(sublength+1,filelength);
                        if(extension.trim().equalsIgnoreCase("msg") || extension.trim().equalsIgnoreCase("txt") || extension.trim().equalsIgnoreCase("xls") || extension.trim().equalsIgnoreCase("ppt") || extension.trim().equalsIgnoreCase("jpg") || extension.trim().equalsIgnoreCase("gif")|| extension.trim().equalsIgnoreCase("doc" )|| extension.trim().equalsIgnoreCase("pdf") || extension.trim().equalsIgnoreCase("wmv") || extension.trim().equalsIgnoreCase("zip") || extension.trim().equalsIgnoreCase("jpeg") || extension.trim().equalsIgnoreCase("xml") || extension.trim().equalsIgnoreCase("html") ||extension.trim().equalsIgnoreCase("bmp") ||extension.trim().equalsIgnoreCase("htm") ||extension.trim().equalsIgnoreCase("ppt")||extension.trim().equalsIgnoreCase("oft")||extension.trim().equalsIgnoreCase("csv")){
                        return true;
                        }else{
                        return false;
                   return true;
         public int writeFile(FormFile file,HttpServletRequest request,String fileName){
                   int retValue = 0;
                   String size = (file.getFileSize() + " bytes");
                   if(file.getFileSize()>0){
                        //System.out.println("The size of the file is :" + file.getFileSize() + " bytes");
                        String data = null;
                        try {
                             //retrieve the file data
                             String fileTodelete = request.getRealPath("/helpdesk/meetingsagenda/"+fileName);
                             boolean success = (new File(fileTodelete)).delete();
                             //System.out.println("sucess......"+success);          
                             ByteArrayOutputStream baos = new ByteArrayOutputStream();
                             InputStream stream = file.getInputStream();
                             //write the file to the file specified
                             System.out.println("sfsdfkjdsfds "+request.getRealPath("/helpdesk/meetingsagenda/"+fileName));
                             OutputStream bos = new FileOutputStream(request.getRealPath("/helpdesk/meetingsagenda/"+fileName));
                             int bytesRead = 0;
                             byte[] buffer = new byte[8192];
                                  while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                                       bos.write(buffer, 0, bytesRead);
                             bos.close();
                             data =      "The file has been written to \""+ "/helpdesk/meetingsagenda/"+ "\"";
                             System.out.println("data........."+data);
                                  //close the stream
                             stream.close();
                        }catch(FileNotFoundException fnfe) {
                                  System.out.println("com.srit.hrnet.homepage.fromceo.FromCEOAction.writeFile.Exception :"+ fnfe.toString());
                                  fnfe.printStackTrace();
                                  //retValue = FORMFILE_FILE_NA;
                        }catch(IOException ioe) {
                                  System.out.println("com.srit.hrnet.homepage.fromceo.FromCEOAction.writeFile.Exception :"+ ioe.toString());
                                  ioe.printStackTrace();
                                  //retValue = FORMFILE_ERR_UPD;
                   }//end of try catch:~
                   }else{
                        //The file was a not available
                        //retValue = FORMFILE_SIZE_ZERO;
                   }//end of if else:~
              //     System.out.println("retValue........."+retValue);
                   return retValue;                         
    }//end of ComplaintAction
    and GrievanceFormTO:(Dummy form bean)
    ==========
    * Created on Nov 4, 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package com.srit.hrnet.helpdesk.grievancemechanism;
    import java.util.GregorianCalendar;
    import org.apache.struts.upload.FormFile;
    public class GrievanceComplaintTO implements java.io.Serializable {
    private String complaintCode;
    private String compcode; //complaind Id
    private String complaintName;
    private String category;
    private String priority;
    //private GregorianCalendar date;
    private FormFile theFile;
    private String compOption;
    private String desc;
    private String comments;
    private String status;
    private String serviceperson;     //employee who is going to serve the complaint.Applicatble only in case of manual flow.
    private String loggedEmpId; //the employee who has logged the complaint
    private String applyEmpId; //employee to whom the cmplaint belongs to or owner of the complaint
    private String associateComm;
    private String associateRating;
    private GregorianCalendar occdate;
    private String occtime;
    private String attachmentName;
         public String getApplyEmpId() {
              return applyEmpId;
         public void setApplyEmpId(String applyEmpId) {
              this.applyEmpId = applyEmpId;
         public String getAssociateComm() {
              return associateComm;
         public void setAssociateComm(String associateComm) {
              this.associateComm = associateComm;
         public String getAssociateRating() {
              return associateRating;
         public void setAssociateRating(String associateRating) {
              this.associateRating = associateRating;
         public String getCategory() {
              return category;
         public void setCategory(String category) {
              this.category = category;
         public String getComments() {
              return comments;
         public void setComments(String comments) {
              this.comments = comments;
         public String getCompcode() {
              return compcode;
         public void setCompcode(String compcode) {
              this.compcode = compcode;
         public String getComplaintName() {
              return complaintName;
         public void setComplaintName(String complaintName) {
              this.complaintName = complaintName;
         public String getCompOption() {
              return compOption;
         public void setCompOption(String compOption) {
              this.compOption = compOption;
         public String getDesc() {
              return desc;
         public void setDesc(String desc) {
              this.desc = desc;
         public String getLoggedEmpId() {
              return loggedEmpId;
         public void setLoggedEmpId(String loggedEmpId) {
              this.loggedEmpId = loggedEmpId;
         public String getOcctime() {
              return occtime;
         public void setOcctime(String occtime) {
              this.occtime = occtime;
         public String getPriority() {
              return priority;
         public void setPriority(String priority) {
              this.priority = priority;
         public String getServiceperson() {
              return serviceperson;
         public void setServiceperson(String serviceperson) {
              this.serviceperson = serviceperson;
         public String getStatus() {
              return status;
         public void setStatus(String status) {
              this.status = status;
         public String getComplaintCode() {
              return complaintCode;
         public void setComplaintCode(String complaintCode) {
              this.complaintCode = complaintCode;
         public void setOccdate(GregorianCalendar occdate) {
              this.occdate = occdate;
         public GregorianCalendar getOccdate() {
              return occdate;
         public String getAttachmentName() {
              return attachmentName;
         public void setAttachmentName(String attachmentName) {
              this.attachmentName = attachmentName;
         public FormFile getTheFile() {
              return theFile;
         public void setTheFile(FormFile theFile) {
              this.theFile = theFile;
    but i am getting error
    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)
         com.srit.hrnet.filter.SessionValidateFilter.doFilter(SessionValidateFilter.java:81)
    root cause
    org.apache.commons.beanutils.ConversionException: Cannot assign value of type 'org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile' to property 'file' of type 'java.lang.String'
         org.apache.struts.action.DynaActionForm.set(DynaActionForm.java:424)
         org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1733)
         org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)
         org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)
         org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022)
         org.apache.commons.beanutils.BeanUtilsBean.populate(BeanUtilsBean.java:811)
         org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:298)
         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)
         com.srit.hrnet.filter.SessionValidateFilter.doFilter(SessionValidateFilter.java:81)
    and my jsp is:
    =========
    <%@ page language="java" %>
    <%@ taglib uri="struts-bean" prefix="bean" %>
    <%@ taglib uri="struts-html" prefix="html" %>
    <%@ taglib uri="struts-logic" prefix="logic" %>
    <%@ taglib uri="TabGenerator" prefix="GenerateTab" %>
    <%@ page import="com.srit.hrnet.utilities.DateUtilities"%>
    <%@ page import="com.srit.hrnet.components.BasicDAOConstants" %>
    <%@ taglib uri="AccessLogin" prefix="GeneralAccess" %>
    <%@ taglib uri="iterateTag" prefix="iterateTag" %>
    <%@ page import="com.srit.hrnet.components.BasicDAOConstants,com.srit.hrnet.emp.EmployeeGenTO,com.srit.hrnet.helpdesk.grievancemechanism.*"%>
    <%@ page import="com.srit.hrnet.tags.*"%>
    <html:html locale="true">
    <HEAD>
         <TITLE>
                   <bean:message key="com.srit.hrnet.helpdesk.complaint.form.title"/>
         </TITLE>
         <META NAME="Generator" CONTENT="EditPlus">
         <META NAME="Author" CONTENT="">
         <META NAME="Keywords" CONTENT="">
         <META NAME="Description" CONTENT="">
    <link rel="stylesheet" type="text/css" href="<%= (session.getAttribute("LoginUser") != null ?
                             ((com.srit.hrnet.emp.EmployeeGenTO)session.getAttribute("LoginUser")).getEmpPageStyleSheet() :
                             com.srit.hrnet.components.access.AccessCodes.GLOBAL_STYLESHEET)%>">
    <script language="javaScript" src="<%= request.getContextPath()%>/jscript/GlobalValidationScript.js" purpose="include"></script>
    <%      
    int dateFormat = (session.getAttribute("LoginUser") != null ? ((com.srit.hrnet.emp.EmployeeGenTO)session.getAttribute("LoginUser")).getDateFormat() : 2);
         System.out.println("/reports/training/TRngBaseReport dateFormat = "+dateFormat);
         /* *** get the current date *** */
         java.util.GregorianCalendar gc1 = new java.util.GregorianCalendar();
         int yy = gc1.get(java.util.Calendar.YEAR);
         int mm = gc1.get(java.util.Calendar.MONTH);
         int dd = gc1.get(java.util.Calendar.DATE);     
         mm = mm + 1;
         String mon;
         String day;
         if(dd <= 9)
              day = "0" + java.lang.String.valueOf(dd);
         else
              day = java.lang.String.valueOf(dd);
         if(mm <= 9)
              mon = "0" + java.lang.String.valueOf(mm);
         else
              mon = java.lang.String.valueOf(mm);
         java.lang.String currentDate = "";
         if(dateFormat == 3){
              currentDate = java.lang.String.valueOf(yy+"/"+mon+"/"+day);/* (yyy-mm-dd format) */
         }else if(dateFormat == 1){
              currentDate = java.lang.String.valueOf(mon+"/"+day+"/"+yy);/* (mm-dd-yyy format) */
         }else if(dateFormat == 2){
              currentDate = java.lang.String.valueOf(day+"/"+mon+"/"+yy);/* (dd-mm-yyy format) */
         System.out.println("/reports/training/TRngBaseReport currentDate = "+currentDate);
    %>
    <script language="javaScript" src="<%= (session.getAttribute("LoginUser")!=null ? ((com.srit.hrnet.emp.EmployeeGenTO)session.getAttribute("LoginUser")).getScriptFile() : "")%>" purpose="include"></script>
    <script language="javaScript" src="jscript/CommonDialog.js" purpose="include"></script>
    <script language="javaScript" src="jscript/GlobalValidationScript.js"></script>
    <script language="javascript">
         var gNow = new Date("<%=currentDate%>");
         function val_complaint()
    if(document.GreivanceForm.complaintName.value.length==0)
         alert("Enter Complaint Name");
         document.GreivanceForm.complaintName.focus();
         return false;
    if(document.GreivanceForm.category.value =='NA')
         alert("select category");
         document.GreivanceForm.category.focus();
         return false;
    if(document.GreivanceForm.priority.value == 'NA')
         alert("select priority");
         document.GreivanceForm.priority.focus();
         return false;
         if(document.GreivanceForm.occdate.value == "")
              alert("Enter Date (dd/mm/yy)");
              document.GreivanceForm.occdate.focus();
              return false;
         else     
         if(document.GreivanceForm.occdate.value>document.GreivanceForm.currentDate.value){
                   alert("select Previous or Current date");
                   document.GreivanceForm.occdate.focus();
                   return false;
         if(document.GreivanceForm.occtime.value == "")
         alert("Select Time of Occurence.");
         document.GreivanceForm.occtime.focus();
         return false;
    else
    if(!IsValidTime(document.GreivanceForm.occtime.value) )
    alert("Enter Valid Time (HH:MM)");
              return false;
         if(document.GreivanceForm.desc.value == "")
         alert("Enter Description");
         document.GreivanceForm.desc.focus();
         return false;
              document.forms[0].compOption.value='submitForm';
              document.forms[0].submit();
              return false;
         function IsValidTime(givenTime)
              var hour = 0;
              var minute = 0;
              var timePat = /^(\d{1,2}):(\d{1,2})?$/;
              var matchArray = givenTime.match(timePat);
              if (matchArray == null)
                   alert("Enter Valid Time.");
                   return false;
              hour = matchArray[1];
              minute = matchArray[2];
              if(hour==0 && minute==0)
              alert("The Time You Entered is 0:0");
              return false;
              if (hour < 0 || hour > 23)
              alert("Hour must be between 0 and 23");
              return false;
              if (minute<0 || minute > 59)
              alert ("Minute must be between 0 and 59.");
              return false;
              return true;
    unction help(url)
         var attributes = 'menubar=no,toolbar=no,location=no,width=625,height=375,resizable=yes';
         var name = 'Help';
         window.open(url,name,attributes);
    //return false;
    </script>
    <script language = "javaScript" src = "<%=request.getContextPath()%>/jscript/CommonDialog.js" purpose = "include"></script>
    </HEAD>
    <body bgcolor="#FFFFFF" onload="setFocus()">
    <GenerateTab:displaytabs tabId="<%=com.srit.hrnet.masters.gui.GUIConstants.HD_GRIEVANCE_REDRESSAL_FORM%>" activeSubTab="0" >
    <table align="right">
              <tr>
                   <td>
                        <img src="<%=request.getContextPath()%>/images/help.gif" border="0" alt="Help">
                   </td>     
              </tr>     
         </table>
         <html:form action="/helpdesk/GrievanceComplaint" enctype="multipart/form-data" method="POST" onsubmit="javascript:return val_complaint()">
         <html:hidden property="compOption" value="submitForm" />
         <html:hidden property="onbehalf"/>
         <html:hidden property="employeeId"/>
         <html:hidden property="hidSelectedNames"/>
         <html:hidden property="selectedrequestor"/>
         <html:hidden property="individual"/>
         <table cellpadding="3" cellspacing="0" align="center" >
              <th align="center" class="tablehead" colspan="2">
              <b> Complaint Form </b>
              </th>
    <tr>
                   <td colspan="1" class='tablesubhead'>
                   <b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.complaintname"/></b><font class="star"> *</font>
                   </td>
                   <td class='subhead'>
                   <html:text property="complaintName" maxlength="99"/>
                   </td>
              </tr>
         <tr>
                   <td class='tablesubhead' colspan="1"><b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.category"/></b>
                   <font class="star">*</font></td>
                        <td class="tableright" property="category" >
                        <iterateTag:iterate propertyName='<%=IterateInterface.ITERATE_HELPDESK_GRIEVANCE_CATEGORY%>' defaultSelected='<%=request.getAttribute("category")==null?null:""+request.getAttribute("category")%>' selectSize='<%=100%>' tabInd='<%="3"%>'>
                        </iterateTag:iterate>
                   </td>
              </tr>
              <tr>
                   <td class='tablesubhead' colspan="1"><b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.priority"/></b>
                   <font class="star">*</font></td>
                   <td class="subhead">
                        <iterateTag:iterate propertyName='<%=IterateInterface.ITERATE_HELPDESK_GRIEVANCE_PRIORITY%>' defaultSelected='<%=request.getAttribute("priority")==null?null:""+request.getAttribute("priority")%>' selectSize='<%=100%>' tabInd='<%="3"%>'>
                                  </iterateTag:iterate>
                   </td>
         </tr>
         <tr>
                             <td class='tablesubhead' colspan=1><b>Date of Occurence</b>
                             <font class="star">*</font> </td>
                             <td class="subhead">     
                             <html:text name="GreivanceForm" property="occdate" maxlength="10"/>
                             <input type="hidden" name="currDate" />
                             <img src="<%= request.getContextPath()%>/images/calendar.jpg" border="0" alt="Calendar" >
                             </td>                         
                   </tr>
                                  <tr>
                                       <td class='tablesubhead' colspan=1><b>Time of Occurence</b>
                                       <font class="star">*</font></td>
                                       <td class="subhead">     
                                       <html:text name="GreivanceForm" property="occtime" maxlength="10"/> (24 Hrs format)</td>
                             </tr>
                             <tr>
                        <td class="tablesubhead" colspan=1>
                             <b>Description</b>
                             <font class="star">*</font></td>
                                       <td class="subhead">
                                       <html:textarea property="desc" styleClass="formObject" cols="40" rows="4"></html:textarea>
                                       </td>
                        </tr>
                   <tr>
              <td class="tablesubhead" colspan=1>
                   <b>Comments/Suggestions</b>
              </td>
                             <td class="subhead">
                             <html:textarea property="comments" styleClass="formObject" value="" cols="40" rows="4"></html:textarea>
                             </td>
                   </tr>
                   <tr>
                   <td class="tableleft">
              <b><bean:message key="com.srit.hrnet.helpdesk.redressal.form.attachment"/> </b>
                                  </td>
                             <td class="tableright">
                                  <html:file property="file" size="18" />
                             </td>
              </tr>
                   <tr>
                   <td colspan="2" align="center" class="tablesubhead">
                   <input type="submit" class="submit" value="Submit" >
                    <html:reset property="reset" styleClass="submit" />
                   </td>
              </tr>
    </table>
         <input type="hidden" name="currentDate" value="<%=currentDate%>">
    </html:form>
    </GenerateTab:displaytabs>
    <html:javascript formName="/SubmitComplaint"/>
    </body>
    </html:html>
    please help me..

    VAS_MS wrote:
    please help me..First help yourself by posting a clear question
    You have far to much code posted and without the use of the correct code tags its almost unreadable.
    You have a question about uplaoding files with Struts then get rid of all the junk in your code thats not related to uploading files.
    If you have an error then post the relevant information on the error
    like
    org.apache.commons.beanutils.ConversionException:
    Cannot assign value of type 'org.apache.struts.upload.CommonsMultipartRequestHandler$CommonsFormFile' to property 'file' of type 'java.lang.String'
    org.apache.struts.action.DynaActionForm.set(DynaActionForm.java:424)If you had posted only that you would have given enough information, that error says it all you are trying to put your file into a String and its not working.
    reread the tutorial/documentation provided and try again
    Edited by: pgeuens on 21-mrt-2008 8:04

  • Struts validation not working properly

    Hi,
    I'm using the struts validator to validate my form.. I've followed all the steps required.. I've checked it quite a few times :)
    Currently I want to verify if my form fields have any value, so am verifying the required property.. but when I submit an empty form, it doesn't show an error.. but the log shows the following;
    Any suggestions what could be missing?
    2005-08-11 16:20:08,804 [http-8080-Processor25] ERROR org.apache.struts.validator.ValidatorForm - org.apache.struts.validator.FieldChecks.validateRequired(java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages, org.apache.commons.validator.Validator, javax.servlet.http.HttpServletRequest)
    org.apache.commons.validator.ValidatorException: org.apache.struts.validator.FieldChecks.validateRequired(java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionMessages, org.apache.commons.validator.Validator, javax.servlet.http.HttpServletRequest)
         at org.apache.commons.validator.ValidatorAction.loadValidationMethod(ValidatorAction.java:627)
         at org.apache.commons.validator.ValidatorAction.executeValidationMethod(ValidatorAction.java:557)
         at org.apache.commons.validator.Field.validateForRule(Field.java:827)
         at org.apache.commons.validator.Field.validate(Field.java:906)
         at org.apache.commons.validator.Form.validate(Form.java:174)
         at org.apache.commons.validator.Validator.validate(Validator.java:367)
         at org.apache.struts.validator.ValidatorForm.validate(ValidatorForm.java:152)
         at org.apache.struts.action.RequestProcessor.processValidate(RequestProcessor.java:942)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:255)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1480)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:524)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)

    I had a similar problem upgrading from struts 1.1 to 1.2.7. The method signatures in FieldChecks changed to include a Validator object:
    1.1
    validateRequired(java.lang.Object bean, org.apache.commons.validator.ValidatorAction va, org.apache.commons.validator.Field field, ActionErrors errors, javax.servlet.http.HttpServletRequest request)
    1.2.7
    validateRequired(java.lang.Object bean, org.apache.commons.validator.ValidatorAction va, org.apache.commons.validator.Field field, ActionMessages errors, org.apache.commons.validator.Validator validator, javax.servlet.http.HttpServletRequest request)
    After I added org.apache.commons.validator.Validator to the methodParams attribute of validator in validator-rules.xml I no longer got the error (which was a NoSuchMethodException... I had to look at the ValidatorAction code to find that out, for some reason it wasn't in the stack trace).

  • Problem in struts validator

    hai
    I have a problem while using the struts validator in my program.
    It gives the error as:
    HTTP Status 404 - Servlet action is not available
    type Status report
    message Servlet action is not available
    description The requested resource (Servlet action is not available) is not available.
    The program is given below
    File : one.jsp
    <html:form action="/test" method="post">
    <table width="309">
    <tr>
    <td width="149"><div align="right">User Name: </div></td>
    <td width="148"><html:text property="username" value=""/></td>
    </tr>
    <tr>
    <td><div align="right">PassWord: </div></td>
    <td><html:password property="password" value="" /> </td>
    </tr>
         <tr>
    <td><div align="right">Number: </div></td>
    <td><html:password property="number" value="" /> </td>
    </tr>
    <tr>
    <td><div align="right"></div></td>
    <td><html:submit /> </td>
    </tr>
    </table>
    </html:form>
    web.xml file is ordineary file which contains the tag which is necessary for the struts.
    File : struts-config.xml
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
    "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
    <struts-config>
    <global-forwards>
    <forward name="database" path="/database"/>
    </global-forwards>
    <form-beans>
    <form-bean name="form1" type="struts1.bean1">
    </form-bean>      
    </form-beans>
    <action-mappings>
    <action path="/test" name="form1" type="struts1.one" input="one.jsp" validate="true" scope="request" >
         <forward name="success" path="/two.jsp"/>
    </action>
    </action-mappings>
    <message-resources parameter="ApplicationResources" />
    <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>
    File validator.xml
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE form-validation PUBLIC
    "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN"
    "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd">
    <form-validation>
    <formset>
    <!-- Form for Validation example -->
    <form name="form1">
    <field property="username" depends="required">
    <arg0 key="test.string"/>
    </field>
    <field property="password" depends="required">
    <arg0 key="test.password"/>
    </field>
    <field property="number" depends="required">
    <arg0 key="test.number"/>
    </field>
    </form>
    </formset>
    </form-validation>
    File validator-rules.xml
    The validator-rules.xml file is default validator-rules.xml file.
    Iam using the two java file for ActionForm and Action
    ActionForm file
    package struts1;
    import org.apache.struts.validator.ValidatorForm;
    public class bean1 extends ValidatorForm
    private String username=null;
    private String password=null;
    private int number=0;
    public void setUsername(String username)
    this.username=username;
    public String getUsername()
    return username;
    public void setPassword(String password)
    this.password=password;
    public String getPassword()
    return password;
    public void setNumber(int number)
    this.number=number;
    public int getNumber()
    return number;
    Action class:
    package struts1;
    import struts1.bean1;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.DynaActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.validator.ValidatorActionForm;
    import org.apache.struts.validator.ValidatorForm;
    import java.io.IOException;
    import javax.servlet.ServletException;
    public class one extends Action
    public ActionForward execute(ActionMapping mapping,ActionForm form1,HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    String uname=null;
    String pword=null;
    String target=new String("success");
    int num=0;
    HttpSession session=request.getSession(true);
    try
    if(form1 !=null)
    bean1 form=(bean1) form1;
    uname=form.getUsername();
    pword=form.getPassword();
    num=form.getNumber();
    session.setAttribute("uname",uname);
    session.setAttribute("word",pword);
    session.setAttribute("num",""+num);
    catch(Exception e)
    return mapping.findForward(target);
    In two.jsp file Iam just getting the session value and displaying the result.
    The Action and ActionForm are used inside the struts1 file which is placed inside the classes folder.
    The Two file is also compiled successful.
    When executing the one.jsp file is displayed but when clicking the submit button it giving the error as servlet action is not available.
    So Iam try to change some coding in the Action Class
    In the execute method I changed ValidatorForm instead of ActionForm.
    but it giving the same error.
    The same error is displayed when Iam trying the DynaValidatorForm
    instead of struts bean class i.e ActionForm.
    If any one knows what is the problem in the program please give some instrutction to correct the error or give some simple example program for practice.
    Regards
    A.K. Raj

    Add the Validator as the 6th argument and it should work fine.
    Amy
    <validator name="required"
    classname="org.apache.struts.validator.FieldChecks"
    method="validateRequired"
    methodParams="java.lang.Object,
    org.apache.commons.validator.ValidatorAction,
    org.apache.commons.validator.Field,
    org.apache.struts.action.ActionMessages,
    org.apache.commons.validator.Validator,
    javax.servlet.http.HttpServletRequest"
    msg="errors.required"/>

  • Problem Displaying Struts Message - UIX

    Hi,
    I am using UIX, ADF Model and JDeveloper 10.1.2.0.0 (Build 1811)
    I want to display some confirmation messages on a UIX Page -by example: delete successful or user XYZ added-
    I already put the messages using the next code: (overwriting the findForward method)
    ActionMessages messages = new ActionMessages();
    messages.add("feedback", new ActionMessage("tiposdocumentos.message.update.success", val1, val2));
    saveMessages(actionContext.getHttpServletRequest(), messages);
    After that I put a "MessageBox" on the UIX page but I am unable to display the messages...
    Any idea?
    Thanks

    Hello,
    I looked around on this forum, and found 2 posts that hopefully will help.
    Using Struts ActionErrors in UIX
    Re: Displaying Struts messages/errors in 10g
    I'm not sure if you did this or not, but in case you didn't:
    add to your <page> element:
    xmlns:struts="http://xmlns.oracle.com/uix/struts"
    Then use a messageBox like this:
    <struts:dataScope xmlns="http://xmlns.oracle.com/uix/ui"
                                          xmlns:data="http://xmlns.oracle.com/uix/ui">
    <contents>
       <messageBox messageType="error" automatic="true"/>
    </contents>
    </struts:dataScope>Jeanne

  • Integrate struts validator framework

    (JHeadstart 9.0.4: Toplink/JSP/Struts)
    I am trying to integrate the struts validator framework . I'm encountering the following
    problem. When a validation rule(defined in the struts validation.xml) is violated I would expect
    that the JSP include named jhsInfo.jsp would show the errormessage because I assumed that it also
    reads from the same Error Bean (ActionErrors object ) struts normally uses.
    When I include a jsp of my own, containing the following:
    <%@ 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:errors/>
    then messages raised by the struts validation framework are shown and everything seems to work.
    I have the following questions:
    - Is it possible to show struts validation error messages using the jhsInfo.jsp ?
    I investigated the <jhs:ifContainsError> in the JHeadstart Taglibrary
    and noticed how it checks for the JHS_USER_INFO session attribute; apparently, when the validate()
    method in JhsDynaActionForm finds ActionErrors through the Struts Validator framework, this session attribute is not set.
    However, even if we add this attribute explicitly to sessionData in validate(), we do not get the Struts Validator Action Errors.
    - If not possible, how could we adapt the code to make it work? Should we instantiate JHeadstart UserExceptions
    for all ActionErrors or does JHeadstart have built-in functionality to deal with these ActionErrors in the proper way?
    Are we running into a bug, is it intentional to keep Struts Validator Error separate from JHeadstart Exception Errors
    or is JHeadstart currently not equipped with the logic to deal with the ActionErrors?
    Thanks in advance,
    Rob Brands (Amis)

    Rob,
    JHeadstart transforms UserExceptions (controller-independent) to Struts specific ActionErrors and ActionMessages in JhsRequestprocessor.convertUserExceptions.
    So, with JHeadstart you can either use ACtionErrors/ActionMessages directly, or indirectly by thrwoing UserExceptions.
    In jhsInfo we use html:messages to loop over both messages and errors (The boolean attribute message determines whether ActionErrors or ActionMessages are iterated). We do not use html:errors because that does not provide you with control over the layout of individual messages.
    You are right that our custom tags ifContainsError and ifContainsInformation should also directly check for existence of ActionErrors and ActionMessages. We will fix that for the upcoming release.
    With that fix in place, you should be able to use jhsInfo.jsp to display validator messages.
    You mentioned you tried to put a "dummy" JHS_USER_INFO exception on the session in the validate() method. This approach should work, however, to display ActionErrors (as is the case with the validator framework), you should use JHS_USER_ERROR as the key, noy JHS_USER_INFO.
    For now, you could choose to modify jhsInfo.jsp and use your own ifContains tags, until we have fixed this.
    Steven Davelaar.

  • Struts client side validation....

    Hello all,
    I am using struts client and server validation but only the server validation works. I tired looking around the forum but wouldnt find any similar problem.
    I am getting value from the previous action class and i am able to successfully retrieve and display the value. I inserted the value in a object and pass over to my jsp. When i try inserting the validation, the server side works fine but i get nth on the client side. I viewed the source code of my jsp and the JAVASCRIPT is successfully inserted but no pop up when i leave the fill blank. Please advise mi..
    1)update.jsp will retrieve data from a object and display them in text box
    struts config file**
    <form-bean name="UpdateMarks" type="fypms.form.UpdateMarksForm" />
    <action name="UpdateMarks"
    path="/updateMarks"
    type="fypms.action.UpdateStudentMarks"
    scope="request"
    validate="true"
    input="/pages/UpdateStudentMarks.jsp" >
    <forward name="successfulUpdate" path="/pages/successfulUpdate.jsp" />
    <forward name="wrongHelloId" path="/pages/wrongHelloWorld.jsp" />
    </action>
    <message-resources parameter="MessageResources"/>
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property
    property="pathnames"
    value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>
    validation.xml**
    <!-- javascript validation for Update Presentation marks page -->
    <form name="UpdateMarks">
    <field property="first_Present"
    depends="creditCard">
    <arg key="prompt.firstPresent" />
    </field>
    <field property="final_Present"
    depends="creditCard">
    <arg key="prompt.finalPresent" />
    </field>
    </form>
    updatemarksform.java**
    private String adminNo[];
         private String first_Present[];
         private String final_Present[];
         private String batchNumber;
         //private String batchNumber;
         public ActionErrors validate( ActionMapping mapping, HttpServletRequest request)
              ActionErrors errors = new ActionErrors();
              List testing = new ArrayList();
              System.out.println("out");
              for(int x=0; x < first_Present.length;x++)
                   System.out.println("firsT" + first_Present[x].length());
                   if (first_Present[x].length()<1)
                        System.out.println("a");
                        //userId not entered
                        errors.add("marks.firstPresentation", new ActionMessage("marks.firstPresentation"));
                   if (final_Present[x].length()<1)
                        //password not entered
                        errors.add("marks.finalPresentation", new ActionMessage("marks.finalPresentation"));
              request.setAttribute("StudentList", testing);
              return errors;
    update.jsp**
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ page import="fypms.model.*" %>
    <link href="/FYPMS/css/style.css" rel="stylesheet" type="text/css">
    <!--Can contains: JSP -->
    <html:html locale="true">
    <html:form action="/updateMarks" method="post" onsubmit="return validateUpdateMarks(this);">
    <html:errors/>
         <table>
    <tr>
    <td>Name</td>
    <td>Admin Number</td>
    <td>First Presentation</td>
    <td>Final Presentation</td>
    </tr>
    <logic:iterate id="myCollectionElement" name="StudentList">
    <tr>
    <td> <bean:write name="myCollectionElement" property="name"/><html:hidden name="hiddenBatch" property="batchNumber"/></td>
    <td> <bean:write name="myCollectionElement" property="adminNo"/><html:hidden name="myCollectionElement" property="adminNo"/></td>
    <td> <html:text name="myCollectionElement" property="first_Present" /></td>
    <td> <html:text name="myCollectionElement" property="final_Present" /> </td>
    </tr>
    </logic:iterate>
    >
    <tr><td colspan="4"><html:submit value="enter"/></td></tr>
         </table>
    <!-- Begin Validator Javascript Function-->
    <html:javascript formName="UpdateMarks" staticJavascript="true" />
    <!-- End of Validator Javascript Function-->
    </html:form>
    </html:html>
    thank in advance

    # -- validation text(display text) for login page --
    valid.title=Simple Validation Test Form
    prompt.username=Username
    prompt.password=Password
    prompt.phone=Phone Number
    prompt.email=E-Mail Address
    prompt.url=URL (Website Address)
    login.userid = Username is required
    login.password = Password is required
    #-- validation text(display text) for Update presentation marks page --
    prompt.firstPresent=first_Present
    prompt.finalPresent=final_Present
    marks.firstPresentation=First Presentation marks is required
    marks.finalPresentation=Final Presentation marks is required
    thx for ur help ^^
    Message was edited by:
    fatmond

  • Struts basics

    can anybody help me
    i am getting error while compiling my class CustomerAction ....
    i alrdy have compiled my acrionform class i.e... CustomerForm
    my classes are in WEB-INF/src/net
    the error is
    CustomerAction.java:5: cannot find symbol
    symbol : class CustomerForm
    location: package net
    import net.CustomerForm;
    ^
    CustomerAction.java:26: cannot find symbol
    symbol : class CustomerForm
    location: class net.CustomerAction
    CustomerForm custForm = (CustomerForm) form;
    ^
    CustomerAction.java:26: cannot find symbol
    symbol : class CustomerForm
    location: class net.CustomerAction
    CustomerForm custForm = (CustomerForm) form;
    code
    package net;
    import net.CustomerForm;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;
    import org.apache.struts.action.ActionMessages;
    public class CustomerAction extends Action
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
              throws Exception
    if (isCancelled(request)){
    System.out.println("The cancel operation Performed");
    return mapping.findForward("mainpage.jsp");
    CustomerForm custForm = (CustomerForm) form;
    String firstname=custForm.getFirstname();
    String lastname=custForm.getLastname();
    System.out.println("Customer Firstname is " + firstname);
    System.out.println("Customer Lastname is " + lastname);
    ActionForward forward=mapping.findForward("success");
    return forward;
    i have alrdy compiled the CustomerForm.jave and placed the clas file in side the same folder

    i think u didn't compile ur CustomerForm or the class is misplaced u have to place the class of ur CustomerForm "CustomerForm.class" in the directory were the error message point.. getch()?

  • Struts HTTP Status 500 - Error 404-resolved

    Hi, classes12,
    I was getting 404 Error, and it got solved as I copied some (commons-collections,-dbcp, pool, )*.jars into /lib folder. I am using Tomcat 5.5, Struts 1.2.
    Now I am getting 500 error ! Can you help in finding out the bug ....
    Error:DUMP
    javax.servlet.ServletException
         org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:535)
         org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:433)
         org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
         org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
         org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    root cause
    java.lang.NullPointerException
         com.myapp.struts.LoginAction.getAuthenticated(LoginAction.java:57)
         com.myapp.struts.LoginAction.execute(LoginAction.java:114)
         org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
         org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
         org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
         org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:368)
    THE CODE DUMP
    try{
                dataSource = getDataSource(request);
                conn=dataSource.getConnection();
                stmt=conn.createStatement();
                rs=stmt.executeQuery("select psswd from logindetails where associateid_pk='"+associateid+"'");
                if(rs.next()){
                    psswdFromDB=rs.getString(1);
                if(psswdFromDB.equals(apassword)){
                    result=true;
            } catch(SQLException e){
                System.err.println("error");
            finally{
                if(rs!=null){
                    try{
                        rs.close();
                    } catch(SQLException sqle){
                        System.err.println(sqle.getMessage());
                    rs=null;
                if(stmt!=null){
                    try{
                        stmt.close();
                    } catch(SQLException sqle){
                        System.err.println(sqle.getMessage());
                    stmt=null;
                if(conn!=null){
                    try{
                        conn.close();
                    } catch(SQLException sqle){
                        System.err.println(sqle.getMessage());
                    conn=null;
            return result;
        public ActionForward execute(ActionMapping mapping, ActionForm  form,
                HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            if(form!=null){
                LoginActionForm laForm=(LoginActionForm)form;
                String associateid=laForm.getAssociateid();
                String password=laForm.getApassword();
                authenticated=getAuthenticated(request,associateid,password);
            if(authenticated==true)
                return mapping.findForward(SUCCESS);
            else
                return mapping.findForward(FAILURE);        I am new to Struts ! I am learning a lot from you guys, thanks in advance !
    -Ganesh T a.k.a Ganex
    Hyderabad
    South India

    ----->actionform
    public class LoginActionForm extends org.apache.struts.action.ActionForm {
        private String associateid;
        private String apassword;
         * @return
        public String getAssociateid() {
            return associateid;
         * @param string
        public void setAssociateid(String string) {
            associateid = string;
         * @return
        public String getApassword() {
            return apassword;
         * @param string
        public void setApassword(String string) {
            apassword = string;
        public LoginActionForm() {
            super();
            // TODO Auto-generated constructor stub
        public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
            ActionErrors errors = new ActionErrors();
            if (getAssociateid() == null || getAssociateid().length() < 1) {
                errors.add("associateid", new ActionMessage("error.associateid.required"));
                // TODO: add 'error.name.required' key to your resources
            if (getApassword() == null || getApassword().length() < 1) {
                errors.add("apassword", new ActionMessage("error.apassword.required"));
                // TODO: add 'error.name.required' key to your resources
            return errors;
    }------->action class
    public class LoginAction extends Action {
        /* forward name="success" path="" */
        private final static String SUCCESS = "success";
        private final static String FAILURE = "failure";
        boolean authenticated=false;
         * This is the action called from the Struts framework.
         * @param mapping The ActionMapping used to select this instance.
         * @param form The optional ActionForm bean for this request.
         * @param request The HTTP Request we are processing.
         * @param response The HTTP Response we are processing.
         * @throws java.lang.Exception
         * @return
        protected boolean getAuthenticated(HttpServletRequest request, String associateid, String apassword){
            boolean result=false;
            Connection conn=null;
            Statement stmt=null;
            ResultSet rs = null;
            DataSource dataSource=null;
            String psswdFromDB=null;               
            try{
                dataSource = getDataSource(request);
                conn=dataSource.getConnection();
                stmt=conn.createStatement();
                rs=stmt.executeQuery("select psswd from logindetails where associateid_pk='"+associateid+"'");
                if(rs.next()){
                    psswdFromDB=rs.getString(1);
                if(psswdFromDB.equals(apassword)){
                    result=true;
            } catch(SQLException e){
                System.err.println("error");
            finally{
                if(rs!=null){
                    try{
                        rs.close();
                    } catch(SQLException sqle){
                        System.err.println(sqle.getMessage());
                    rs=null;
                if(stmt!=null){
                    try{
                        stmt.close();
                    } catch(SQLException sqle){
                        System.err.println(sqle.getMessage());
                    stmt=null;
                if(conn!=null){
                    try{
                        conn.close();
                    } catch(SQLException sqle){
                        System.err.println(sqle.getMessage());
                    conn=null;
            return result;
        public ActionForward execute(ActionMapping mapping, ActionForm  form,
                HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            if(form!=null){
                LoginActionForm laForm=(LoginActionForm)form;
                String associateid=laForm.getAssociateid();
                String password=laForm.getApassword();
                authenticated=getAuthenticated(request,associateid,password);
            if(authenticated==true)
                return mapping.findForward(SUCCESS);
            else
                return mapping.findForward(FAILURE);
        }THANKS IN ADVANCE
    Edited by: ganeshtyarala on Oct 10, 2007 6:38 PM

  • Unexplained Issue with working with ActionMessages.

    All,
    BACKGROUND:
    I have a simple Struts application that is connected to MySQL. In one of my Actions that calls a method that accesses the database, I'm handling the SQLExceptions by catching the exception and storing (as strings) the error code and message into two bean properties (both properties have the appropriate getter/setter methods) and the bean is passed back to my "calling" action:
    ...catch (SQLException ex) {
    beanname.setCaughterror(Integer.toString(ex.getErrorCode()));
    beanname.setCaughterrormessage(ex.getMessage());
    return beanname;
    Now, I can create a scenario where I create a SQL Exception by inserting a record that duplicates the primary key. This creates the exception code 1062 (Duplicate Primary Key error) in MySQL.
    Once back in the action code, I now have a bean with the error code and message. I then add these two pieces of information to the Action Messages object with the following code:
    ActionMessages messages = new ActionMessages();
    messages = MyExceptionHandler.handleMyErrors(messages,beanname.getCaughterror(),beanname.getCaughterrormessage());
    saveErrors(request, messages);
    Now the MyExceptionHandler.handleMyErrors looks like this:
    public static ActionMessages handleMyErrors (ActionMessages messages,
    String errorcode,
    String myerrormessage) {
    if (errorcode.equals("1062")) {
    messages.add("myerrortext", new ActionMessage("myerrortext", myerrormessage));
    return messages;
    My ApplicationResources file looks like this:
    myerrortext= The system generated error message is noted below: <br> {0}
    ISSUE:
    The error message prints out correctly; however, at any point in time, whenever I try and print the error message itself, (either by displaying the bean property value in my JSP page via ${beanname.caughterrormessage} or by saving it to a string String ttest = beanname.getCaughtErrorMessage()) it comes up null. Can anyone explain why that is happening this way? I can't for the life of me figure out why it displays in the ErrorMessage, but it appears to be null if accessed directly.
    Please Help.

    Problem Solved.
    The error messages from MySQL can contain single quotes in them and have to escaped out before writing to the Log4j logger.

Maybe you are looking for