Using Validate Method of ActionForm to validate JSP

Hi...
Am working on a struts application in which i have a struts jsp page which will contain a table of records that am populating while loading the page itself, each record of the table will have a check box associated with it.
my requirement is that, i must select atleast one checkbox from the list of records before going for further processing from the page ie. i must validate whether the the user had selected any one of the check boxes. i am not usings struts validation plugin for this, instead am going for overrideing the validate method of ActionForm in my form bean.
Now comes my problem:
When i tried to validate the page without selecting any of the check boxes,the validate method is being called and its checking the values and returning the error message to my jsp page, but by the time the msg comes back to the jsp page the page is getting refreshed and all the previous list of records i had displayed in the page is lost giving me an error msg on jsp that "collection not found". The application scope is set to request and not to session. So i tried with setting the scope to session (which was not permissible by my requirements, still just for testing) but still am geting the same error
i am stuck up with this problem for a long time and i couldnt find out any one who could solve it, and i have to use the Validate method of Action Form
Please any one can explain whats the problem and what should i do
Thanks in advance
Rens

ok, i'm going to try and make this short and sweet. let me know if you run into problems.
first off, you may need to add apache commons-collections to your project.
#1
you will need to make a new bean class to represent your 'line' object. so if it was a Person we'd make a Person class with a String name, int age... blah blah blah.
#2
in your ActionForm class, add a
java.util.List personList;and make a normal setter and getter for it
#3
this is the only tricky part, make (or add this to) your reset( ) function in your ActionForm...
public void reset(ActionMapping actionMapping, HttpServletRequest httpServletRequest) {
     personList = ListUtils.lazyList(new java.util.ArrayList(), new Factory() {
          public Object create() { return new Person(); }
}but replace the 'new Person()' part with whatever the bean class you made in Step 1 is
#4
now, in your Action class build the list of objects from the database, and set it into your form.
#5
in your .jsp code you will need to use the nested tags like so
<nested:iterate id="personLine" property="personList">
          <TR>
               <td><nested:write property="name"/></td>
               <nested:hidden property="age"/>
          </TR>
</nested:iterate>
#6
then back in your validate code or in your Action class you can access the list by calling yourForm.getPersonList() and validating it. if you find a problem and return with an error all the values will remain without having to talk to the database again.
hope that helps.

Similar Messages

  • How to use ActionForm validate() method in ADF/Struts project

    Hi
    We are developing a project using ADF/Struts. We are not planning to use entity level validation. Rather we prefer to have it at Struts Form Bean level. So we need to have validate() method in Form Bean.
    That mean we need to have seperate bean for all the actions /jsp. The ADF's DataForm form bean is not gonna work for us. Is that correct.
    Please let me know...am I in the right direction.
    That could be a different discussion why we don't prefer entity level validation

    You can use the Struts validator plug-in (there's a howto on doing that on OTN) and it will handle the basics for you through XML definitions.
    If you want to specifically have a Form bean with a Validate() then the issue is that the current "DataForm" is a generic bean driven of the databinding files, so yes you'd have to write a bean per screen to use instead and loose that benefit of having a universal Bean. (Internally the DataPage and DataActions will respect the ActionForm APIs so you can pluf your own ActionForm subclass in with no problem.
    Plan B might be to leave the DataForm Bean in place and instead override the lifecycle of the datapage, probably in prepareModelUpdates()

  • Why is the ActionForms validate-Method called twice?

    Hello forum,
    I'm new to struts and want to develop a form, where an internetuser can leave a comment to an article. Just like most sides, an image with an text is displayed, the text has to be written into an inputfield before the comment is commited in order to be saved.
    When an user puts in no text or a wrong one, a errormessage is displayed, the old image is deleted and an new one is created and shown to the user. His input still stays in the fields.
    I proof the correctness of the word in the validate-Method of the ActionForm and it works fine.
    Now I've the following problem:
    If the user puts in the correct text, the comment is saved and the side is displayed again including his comment.. But also all the input of the form should be erased. But for some reason, its not and the validate method is called again and since there is a new wordvarifyingimage and a new text to be inserted, it throws an error which is displayed again. Also, all the input of his last message is present!
    So, I guess I miss a big point about the ActionForm handling. Why is the ActionForm called twice and why doesn't it erase the old input? I try to do this in the Action class after saving the comment, setting all the formparameters to "" or null.
    Can anybody give me a hint?
    Would be a big big help since I've not found anything googling about this issue.
    If you need code, just tell me which part I put in here (ActionForm, Action, struts-config or jsp-file)
    Thanxs in advance,
    strutsnewbytopro

    my jsp:
    <%@ taglib uri="/WEB-INF/tld/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="struts/html-el" prefix="html" %>
    <%@ taglib uri="jstl/c" prefix="c" %>
    <%@ taglib uri="/WEB-INF/tld/struts-logic.tld" prefix="logic" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
    <style type="text/css" title="currentStyle" media="screen">
              @import "../library/css/blog.css";     
         </style>
    <script language="javascript">
         function sendMail(){
              document.forms[0].formaction.value ='mail';
              document.forms[0].submit();
         function saveComment(){
              document.forms[0].formaction.value ='comment';
              document.forms[0].submit();
         </script>
    </head>
    <body>
    <html:form action="/blog">
    <div id="container">
         <div id="leftside">
              <logic:messagesPresent>
                   <div id="errors">
                        <div style="color:#CC3333; ">
                        <p><span id="errorHeaders"><bean:message key="errors.validation.header"/></span>
                             <html:messages id="error">
                             <c:out value="${error}"/>
                             </html:messages>
                        </p></div>
                     </div>
              </logic:messagesPresent>
                 .... show blogentry ...          
              <logic:present name="comments">
                   <div id="divblogcomment">
                   <logic:iterate name="comments"  id="com">
                   <div class="breaker10" style="clear:left; "></div>
    <div class="rowblogcommentdate" style="width:150px;"<a href="<bean:write name="com" property="website" />"><bean:write name="com" property="username" /></a> am <bean:write name="com" property="postdate" /></div>
                   <div class="rowblogcomment"><bean:write name="com" property="comment" /></div>
                   </logic:iterate>
                   <div class="breaker10" style="clear:left; "></div>
    </div>
              </div>
                             </logic:present>
                             <logic:notPresent name="savedcomment">
                                  <div id="writeblogcomment">
                                  <div class="topbig"><div class="headsmall">enter Comment</div></div>
                                  <div id="bginhaltwriteblogcomment">
                                       <div class="breaker10" style="clear:left; "></div>
                                       <div align="center">
                                            <table cellpadding="0" cellspacing="0" border="0">
                                                 <tr>
                                                      <td>Name:</td>
                                                      <td>  </td>
                                                      <td><html:text size="50" name="blogForm2" styleClass="inputtext" property="username"/></td>
                                                      <td>  </td>
                                                      <td>Web:</td>
                                                      <td>  </td>
                                                      <td><html:text size="50" name="blogForm2" styleClass="inputtext" property="webaddress"/></td>
                                                 </tr>
                                                 <tr>
                                                      <td>Enter Code:</td>
                                                      <td>  </td>
                                                      <td><html:text size="66" name="blogForm2" styleClass="inputtext" property="commentword"/></td>
                                                      <td>  </td>
                                                      <td >Code:</td>
                                                      <td>  </td>
                                                      <td><img src="<bean:write name="entry" property="commentpicurl" />"></td>
                                                 </tr>
                                                  <tr>
                                                      <td colspan="7">Comment<br><html:textarea name="blogForm2" styleClass="comment" property="comment" /></td>
                                                 </tr>
                                                 <tr>
                                                      <td colspan="7"><html:submit styleClass="inputtext" onmousedown="javascript:saveComment();"><bean:message key="button.save"/></html:submit></td>
                                                 </tr>                                        
                                            </table>
                                       </p>
                                       </div>
                                       <div class="bottombig"></div>
                                  </div>
                             </div>
                             </logic:notPresent>
                             <logic:present name="savedcomment">
                             <div id="writeblogcomment">
                                  <div class="topbig">Comment saved<div class="headsmall">Kommentar gespeichert</div></div>
                                  <div id="bginhaltwriteblogcomment">
                                       <div class="breaker10" style="clear:left; "></div>
                                       <div align="center">
                                            <table cellpadding="0" cellspacing="0" border="0">
                                                 <tr>
                                                      <td>Comment saved</td>
                                                 </tr>
                                            </table>
                                       </p>
                                       </div>
                                       <div class="bottombig"></div>
                                  </div>
                             </div>
                             </logic:present>
                             </div>
    </div>
    <html:hidden name="blogForm2" property="formaction"/><br>
    <html:hidden name="blogForm2" property="id"/><br>
    <% session.removeAttribute("savedcomment"); %>
    </html:form>
    </body>
    </html>

  • Using bean methods within JSP declaration

    Is it true that bean methods will not work in JSP Methods ?
    For example:
    // get the bean
    <jsp:useBean id="FormValidate" scope="session" class="fsm.frontendCtr.FormValidate" />
    // build a new method in jsp
    <%!
    boolean validate(HttpServletRequest req, String submitFlag) {
    FormValidate.checkMandatory("ADRNACHNAME");
    %>ServletExec return:
    Undefined Variable or class name: FormValidate
    If i use the bean Methods outside the method it worx.
    Is there a trick with which I can use BeanMethods in a JSP Method?

    Is it true that bean methods will not work in JSP
    Methods ?
    For example:
    // get the bean
    <jsp:useBean id="FormValidate" scope="session"
    class="fsm.frontendCtr.FormValidate" />
    // build a new method in jsp
    <%!
    boolean validate(HttpServletRequest req, String
    submitFlag) {
    FormValidate.checkMandatory("ADRNACHNAME");
    %>ServletExec return:
    Undefined Variable or class name: FormValidate
    If i use the bean Methods outside the method it worx.
    Is there a trick with which I can use BeanMethods in a
    JSP Method?FormValidate is this Object. If you need others, pass them from parameters. Try to understand the structure of servlet generated by your JSP.
    <%!
    boolean validate(HttpServletRequest req, String submitFlag) {
    this.checkMandatory("ADRNACHNAME");
    %>
    hope this helps,
    yang

  • Validate Method doesn't fire in insert - is it a bug ?

    I tried to use the validate method in a VO based upon 2 Entities.
    It works but when I insert a new row it doesn't fire.
    Is it a bug ?
    If not what's explanation for that behaviour ?
    Tks
    Tullio

    ViewObjectImpl.validate() is not called automatically in the BC4J framework.
    Validation by default should be implemented in the entities and EntityImpl.validate() is called by the framework on invalid entities when the Entity needs to be validated.

  • Struts - How not to lose parameter after validate() method

    Hi
    I have following problem. When I submit a form(action= sendMessage.do) from site generated in writeMessage.do?id=1 action and validate method find errors it forwards to writeMessage.do I need to forward to writeMessage.do?id=1
    <action path="/sendMessage"
    type="SendMessageAction"
    name="writeMessageForm"
    scope="request"
    validate="true"
    input="/writeMessage.do">
    <forward name="ok" path="/info.jsp"/>
    </action>
    I need something like input="/writeMessage.do?id=xx" , but xx will be changing in runtime. How to solve that problem?

    Swap input="/writeMessage.do" with input="/sendMessage.jsp" (or whatever the name of the input JSP was). If I remember rightly this will fix it for the automatic validation errors, however you'll still get this problem if you need to test business rules/custom validation rules from within your application. To fix this copy the following class and specify a className attribute for your action element in the struts config
    i.e. <action ... className="com.whatever.CustomActionMapping" ... />
    package com.whatever
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class CustomActionMapping extends ActionMapping
        public ActionForward findForward(String forwardName, HashMap requestParams)
            ActionForward fwd = findForward(forwardName);
            Iterator iter1 = requestParams.keySet().iterator();       
            if (iter1.hasNext())
                StringBuffer basePath = new StringBuffer(fwd.getPath());           
                basePath.append("?");
                 while (iter1.hasNext())
                     String paramName = (String) iter1.next();
                     ArrayList paramValues = (ArrayList) requestParams.get(paramName);
                     Iterator iter2 = paramValues.iterator();
                     while (iter2.hasNext())
                         String paramValue = String.valueOf(iter2.next());
                          basePath.append(paramName);
                          basePath.append("=");
                          basePath.append(paramValue);
                          if (iter2.hasNext())
                              basePath.append("&");
                     if (iter1.hasNext())
                         basePath.append("&");
                 fwd = new ActionForward(fwd);
                 fwd.setPath(basePath.toString());
            return fwd;
    }Then in the execute method of your action do something like
    // Creates a map to store the request parameters in
    HashMap requestParams = new HashMap();
    // Helper method to extract a request parameter for 'teamId'
    Integer teamId = RequestHelper.getTeamIdParam(request);       
    // Adds the teamId parameter to the hash map
    setRequestParam(RequestHelper.TEAM_ID, teamId, requestParams);
    // Creates a new forward with the required request parameters dynamically appended to the forward path
    return ((CustomActionMapping) mapping).findForward(forwardName, requestParams);

  • Validate method on EoImpl

    hi jdev groups
    using 11.1.1..5.0-adfbc
    i had a validate method in particulalr xxxeoimpl class.
    Reason: while perform tab out in ui the function will fires. well it performs it's work correclty.
    code in Eoimpl class
        public boolean validatexxxSubTerr(String xxxsubterr) {
            if(xxxsubterr!=null){
                 setAttributeInternal("xxxTerrId",FuncFindTerritory("somevaluevalue",prospsubterr));
            else{
               throw new JboException("Territory Not Found") ;
            return true;
      code in Eoimpl class
        public String FuncFindTerritory(String pbu, String pxxxsubterr){
            CallableStatement cs = null;
            try{
            cs=getDBTransaction().createCallableStatement("begin ? := FUNC_FIND_TERRITORY(?,?); end;",0);
            cs.registerOutParameter(1, Types.VARCHAR);
            cs.setString(3,pxxxsubterr);
            cs.setString(2,pbu);
            cs.executeUpdate();
            return cs.getString(1);
            catch(SQLException e){
            throw new JboException(e);
            finally
            if (cs!=null)
            try{
               cs.close();
             catch (Exception e){System.out.println (" Function Find Territory Exception Thrown "+e);}
        }my question is : I use this FuncFindTerritory in most of the eoimpl class.
    so i dont want to duplicate the same FuncFindTerritory in all eo class.
    is there any chance to define this function in am module access/call this function in eo particular validate method.
    setAttributeInternal("xxxTerrId",FuncFindTerritory("somevaluevalue",prospsubterr)); // this what i meanif wrote like this means i have to define method(FuncFindTerritory) in eoimpl class.
    instead of doing like this..
    Adf provides to access the methods which is define in am? is there any way...
    sorry for updating late.
    thanks&&regards
    adf7.

    In theory you can access the AM from the EO but you should not. An EO represents one row of a table whereas the AM represents the the whole business logic. From this point of view where is no reason why an EO should need access to the AM.
    Extending is a normal java mechanism which is wildly uses in frameworks. If you read the dev guide you'll find a paragraph which encourages you to build an extension for each framework class (for just this reason). This extension classes can hold all the stuff which is global for your application.
    Timo

  • Validate() method not working as it should

    I have a very weird problem here. I have a form-bean where i validate the user input and add them to the errors. When i click the submit button, the errors are displayed not on the same page but on the page as indicated in the <forward name="success" ...> page. very strange. i have done the following:-
    added <html:errors/>
    included the input attribute for that action in struts-config
    set the validate attribute to true in struts-config.
    i cant think of anything else. I've been picking my brains for a while now. Am i missing something really obvious folks? Please let me know !!!!!
    Regards
    Lexus

    Lemme see your validate method implementation and the appropriate snippet from the struts-config.xml file and I'll see what I can do for ya.

  • How to use protected method in jsp code

    Could anyone tell me how to use protected method in jsp code ...
    I declare a Calendar class , and I want to use the isTimeSet method ,
    But if I write the code as follows ..
    ========================================================
    <%
    Calendar create_date = Calendar.getInstance();
    if (create_date.isTimeSet) System.out.println("true");
    %>
    ============================================================
    when I run this jsp , it appears the error wirtten "isTimeSet has protected access in java.util.Calendar"

    The only way to access a protected variable is to subclass.
    MyCalendar extends Calendar
    but I doubt you need to do this. If you only want to tell if a Calendar object has a time associated with it, try using
    cal.isSet( Calendar.HOUR );

  • How to use getContent() method in custom JSP Provider to display a HTML Pag

    Hi,
    If anybody knows how to use getContent() method to use in custom jsp providers (developed by ourselves) so that it can be used to retrieve a jsp page (a simple html page) ..
    I want the code in the provider java file to for the getContent method...
    Pls. get back to me asap....if any body has implemented a custom jsp provider...as it's urgent...
    I have alreday placed the JSP file in the directory structure /etc/opt/SUNWps/desktop/default/channel_dir..But still the jsp is not being displayed..
    Pls get me the getContent() method code to retrive the JSP file..
    satyabrata

    Hi,
    You don't have to do anything in the custom JSPProvider's getContent method except the call {  return super.getContent(request,response); } . If all you want is just to show your jsp, then create a channel from the default JSPProvider, and edit the property contentPage of that channel from samplecontent.jsp to your jsp name, save the changes and login again. You should see your JSP.
    Sanjeev.

  • Problems using GET method in JSP

    Hi,
    I had some problems using GET method in JSP.
    I'm using Apache web server 1.3 and Tomcat 3.3.1 in windows 2000.
    And I'm using language English and Korean.
    When I send messages using POST method, all is good
    But when I send message using GET method, English is good, but Korean is not good.
    I tried to encode using
    URLEncode.encode(str, "UTF-8")
    and decoding it using
    URLDecode.decode(request.getParameter(tag), "UTF-8")
    but it didn't work.
    How can I receive request including Korean using GET method in JSP?
    If anyone have solutions, please let me know.
    thanks.

    Hi,
    I had some problems using GET method in JSP.
    I'm using Apache web server 1.3 and Tomcat 3.3.1 in
    windows 2000.
    And I'm using language English and Korean.
    When I send messages using POST method, all is good
    But when I send message using GET method, English is
    good, but Korean is not good.
    I tried to encode using
    URLEncode.encode(str, "UTF-8")
    and decoding it using
    URLDecode.decode(request.getParameter(tag), "UTF-8")
    but it didn't work.
    How can I receive request including Korean using GET
    method in JSP?
    If anyone have solutions, please let me know.
    thanks.This problem appears, when one use UTF-16 encoding in JSP - am I right?
    If so there are two solutions:
    1) Temporary: Use "UTF-8" - or any other 8 bit encoding scheme and
    encode Korean symbols with "&1234;" kind of escapes - though it
    may not work
    2) Absolute: get my piece of code, which I have managed to write
    just a month ago resolving absolutely similar problem with UTF-16
    in code using Chinese/Russian/English encodings
    But I wouldn't say that it's costs 10 DDs :) - it's much more
    expensive... So try 1st variant if it wouldn't help - let me know.
    I'll figure :)
    Paul

  • How to use the method getParameterValues() of request object in JSP?

    I'm trying to use the method
    String a[]=request.getParameterValues("ch_box");
    to retrieve the values from the form
    but it gives the error
    "Method getParamaterValues(java.lang.String) not found in interface javax.servlet.http.HttpServletRequest."
    so plz tell me how to overcome this hurdle?
    thanx

    Well, just one note... either you have a typo in your code, or else in your post.
    If you cut and pasted the error message (which it looks like you did), then the method getParamaterValues() should be getParameterValues() instead (notice the spelling difference), so you probably just have a typo in your code.

  • Want to send information in Header dynamically using HTTP adapter using post method

    Hi ,
    I have a requirement to send below information in http Adapter header dynamically using post method. which will be authenticated by third party system.
    Authorization : WSSE realm="SDP", profile="UsernameToken", type="AppKey" X-WSSE : UsernameToken Username="XXXX", PasswordDigest="Qd0QnQn0eaAHpOiuk/0QhV+Bzdc=", Nonce="eUZZZXpSczFycXJCNVhCWU1mS3ZScldOYg==", Created="2013-09-05T02:12:21Z"
    I have followed below link to create UDF
    http://scn.sap.com/thread/3241568
    As if now my third party system is not available while sending request I am getting 504 gateway error. is there any approach I can validate my request is working fine?
    Regards,

    Hi Abhay,
    Correct me if I'm wrong but I think WSSE requires a SOAP Envelope. If that is the case, there are two approaches: the first one is to use SOAP Axis and the second one is just to build SOAP Envelope via Java mapping.
    You also need to test it successfully externally, capture the request and replicate it in XI.
    Hope this helps,
    Mark

  • Why we are using servlet as a controller instead of Jsp?

    Can any explain answer for this question
    Thanks in Advance
    Why we are using servlet as a controller instead of Jsp?

    nareshannam wrote:
    Can any explain answer for this question
    Thanks in Advance
    Why we are using servlet as a controller instead of Jsp?Basically JSPs are suited to do just one thing, to generate HTML with variable content. You can put Java code in there too, but it's not a good place for it. Messy to validate, messy to debug. In fact, with tag libraries like JSTL, actual Java code is rare in professionally written JSPs.
    A controller does the bit that comes before you've decided what kind of response the user is going to get, typically it may invoke one of several JSPs according to validation etc.. There's a lot of logic, a lot of parsing parameters and so on. Much cleaner to do this from a Java class like a Servlet.
    Judging by this forum quite a lot of people come to JSPs from ASP or PHP and don't want to bother with actually writing Java classes. That's never going to be much good.

  • Programatic actionForm access from JSP

    I am migrating an application that uses a lot of JavaScript that, in turn, uses embedded Java to initialize JavaScript variables, within the JSPs (see example below)
    In the migrated code, using a page flow, I initialize an actionForm that is used to preset values into a <netui:form>. However I also need to access (reuse) the actionForm to initialize JavaScript variables with values contained in the actionForm.
    Is there a way to access the actionForm programatically (with Java code) from a JSP?
    Example
    =======
    In the example below, the cities JavaScript variable is initialized from the cityList Java variable.
    Note that this example is very simple. The real code complexity precludes from initializing a hidden form variable and using it from JavaScript.
    Eg: (My.jsp)
    <% String[] cityList = (String[]) request.getAttribute( "city_names" );
    %>
    <script>
    var cities = new Array();
    <% for ( int i = 0; i < cityList.length; i++ )
    %> cities[<%= i %>] = "<%= cityList[i] %>";
    <% } %>
    </script>
    What I am trying to do is to replace
    String[] cityList = (String[]) request.getAttribute( "city_names" )
    by something like this
    String[] cityList = (String[]) request.getAttribute( "{actionForm.cityNames}" )
    Thanks

    Hi
    Im not sure if it works but you might try
    <Forward returned />.addOutputForm method
    Then the form bean is also available in request under the name determined by PageFlowUtils.getFormBeanName(ActionForm, HttpServletRequest).
    The action form should be correctly picked up elsewhere without needing any changes
    See the How Do i: Use Multiple forms in a JSP in workshop help under pageflows and the Forward class javadocs
    regards
    deepak

Maybe you are looking for

  • Unable to load OS bound to a domain after power-outage

    I currently manage 200 2013 iMac but since installing Yosemite I've noticed that after the macs are joined to the domain and a network user is using the machine and a power outage occurs ALL iMac running Yosemite will not boot up. The boot process re

  • Is there any way to create a field that will auto increment i.e. document request id field?

    I would like to have a "Request #" automatically assigned to a form.  Is there any way to do that?

  • Will 400 GB 16 MB HD work?

    I am about to buy a seagate 400 GB 16MB HD and just want to be certain that it will work in my imac G4 15 inch flat panel 800 MHz 2002 model. Or should i go with 8 MB cache. Ovation

  • BPMN Diagrams

    Hi, maybe I'm doing something wrong, or this is expected behaviour, but ... I'm trying to configure PD in such a way, that f.e. names for elements like events and gateways would be visible on the diagrams. I can certainly do that by changing the disp

  • Itunes can't connect

    I have a MacBook running 10.5.8 with latest version of itunes.  I am trying to log into my itunes account, but it is saying there is a problem connecting to the internet and that I should check my connection or check back later.  My internet connecti