Why do we need Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=469785
Created: Aug 5, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Java technologies give developers a serious boost when creating
and maintaining applications to meet the demands of today's
public Web sites and enterprise intranets. Struts combines Java Servlets,
Java ServerPages, custom tags, and message resources into
a unified framework. The end result is a cooperative, synergistic platform,
suitable for development teams, independent developers,
and everyone in between.
Comments and alternative answers
| Why do we need Struts?
Author: sanjay soni (http://www.jguru.com/guru/viewbio.jsp?EID=1319985), Nov 21, 2006 Because using struts you can separeate your bussiness logic from presentation logic and supports different implementation Model. So, Struts provide very flexible & extensible way to devlope your complex application. |
Who wrote Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=469786
Created: Aug 5, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Struts was created by Craig R. McClanahan, and donated to the Apache Software Foundation in May 2000. Craig actively leads the Struts project, and is also the lead developer on the Tomcat 4.0 project. There are now several committers to the Struts project, working cooperatively from around the globe. Other Java developers are invited to contribute to the project. Struts is an Apache Jakarta project, with the common mission to "provide commercial-quality server solutions based on the Java Platform that are developed in an open and cooperative fashion".
How is Struts licensed?
Location: http://www.jguru.com/faq/view.jsp?EID=469787
Created: Aug 5, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Struts is copyrighted software available under a "free-to-use-license" by the Apache Software Foundation. The license appears at the head of every source code file. A reference copy of the license is available here.
Is Struts compatible with other Java technologies?
Location: http://www.jguru.com/faq/view.jsp?EID=471929
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Yes. Struts is committed to supporting industry standards. Our lead developer is a member of JSR052, Sun's Expert group for developing a standard library of custom JSP tags. A primary design criteria is that Struts must be compatible with Sun's J2EE platform for corporate enterprises. In fact, Struts really acts as an integrator of Java technologies, so that they can be used in the "real world".
Where can I get help with Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471930
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
The Struts package comes complete with a users guide to introduce people to the framework and its underlying technologies. Various components also have their own in-depth developers guide, to cover more advanced topics. Of course, standard "JavaDocs" are included along with the full source code. The Strut's mailing list is also very active, and welcomes posts from new users. As a testament to its growing popularity, Struts users are also posting their own tutorials and resource pages, including those at Husted dot Com and Bluestone Software. Articles about using Struts have appeared in JavaWorld, InformIt, and JavaReport. MyWebAppCarbaret also offers free hosting of Struts applications, complete access to a MySQL database.
Where I can I get a copy of Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471931
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
The best place to download Struts is at jakarta.apache.org/struts. The nightly builds are very stable, and recommended as the best place to start today.
How do I install Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471932
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
To develop applications with Struts, you can usually just add the Struts JAR file to your Java development environment. You can then start using the Struts classes as part of your own application. A blank Struts application is provided, which you can just copy to get a quick-start on your own brainchild. Since the full source code for Struts is available, we also provide complete instructions for compiling your own Struts JAR from scratch. (This is actually easier that it looks!) Your Struts application can be usually be deployed using a standard WAR file. In most cases, you simply deposit the WAR file on your application server, and it is installed automatically. If not, step-by-step installation instructions for various servlet containers are available.Comments and alternative answers
| my "no" vote was not counted ?
Author: Onno Kreuzinger (http://www.jguru.com/guru/viewbio.jsp?EID=1160336), Apr 5, 2004 and i voted no because the link to the example on how to install in app. servers was dead... |
When do I need "struts.jar" on my classpath?
Location: http://www.jguru.com/faq/view.jsp?EID=471933
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
When you are compiling an application that uses the Struts classes, you must have the "struts.jar" on the classpath your compiler sees -- it does not have to be on your CLASSPATH environment variable. Why is that an important distinction? Because if you are using a servlet container on your development machine to test your application, the "struts.jar" must not be on your CLASSPATH environment variable when running the ontainer. (This is because each Web application must also have their own copy of the Struts classes, and the container will become confused if it is on the environment path as well.) There are several general approaches to this issue:Comments and alternative answers
- Use ANT for building your projects -- it can easily assemble classpaths for the compiler. (This is how Struts itself is built, along with Tomcat and most other Java-based projects).
- Use an IDE where you can configure the "class path" used for compilation independent of the CLASSPATH environment variable.
- Use a shell script that temporarily adds struts.jar to the classpath just for compilation, for example
javac -classpath /path/to/struts.jar:$CLASSPATH $@
| struts.jar on my CLASSPATH
Author: Stjepan Brbot (http://www.jguru.com/guru/viewbio.jsp?EID=1161395), Apr 8, 2004 I need a better explanation why struts.jar must not be in my CLASSPATH and in compiler's classpath in the same time. I work with JBuilderX+JBoss and I had some troubles configuring all these paths. Now I have struts libs in JBuilder's CLASSPATH and also have it in JBoss containers lib directory (it's classpath for compilation). When I define in JBuilder that I want all struts components to be included in my WAR (/WEB-INF/lib) I get an error message! |
How do I authenticate users with Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471934
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
You can use either container-based security or form-based security to authenticate users. With container-based security, the Web browser will track the logins for you, and "replay" the credentials to the server whenever they are required. If a browser hasn't been authenticated yet, it will automatically display a simple login form. If the login passes, the user's original request will proceed. This will also work properly if a user tried to POST from a form to an action URI in a protected area. Once the browser is authenticated, the POST proceeds normally. For applications that manage their own logins, it is probably easier to insist that every single page test for an authenticated user first, and redirect to the login page if not. The Struts example application does this -- partially by use of an application-specific custom tag (app:checkLogon) that performs this check at the top of every page. The tag is application-specific, because the notion of what constitutes a "logged on user" is application specific as well.Comments and alternative answers
| more info on container-based security
Author: Randy Pond (http://www.jguru.com/guru/viewbio.jsp?EID=487474), Aug 30, 2001 Can someone provide more information about container based security? <- noobie alert thanks! |
| Another authentication option is Servlet 2.3 Filters
Author: Ryan Hoegg (http://www.jguru.com/guru/viewbio.jsp?EID=1027426), Nov 19, 2002 If you find that container based authentication is too restrictive and you don't want to check for authentication credentials in each and every servlet, you can use Filters and RequestDispatcher forwarding to accomplish any custom authentication goals. |
| Container authentication
Author: Stjepan Brbot (http://www.jguru.com/guru/viewbio.jsp?EID=1161395), Apr 8, 2004 There's stated that in container-based security model web browser tracks the logins - is that correct?
As far as I know in container-based security one have the oportunity to define realms/principals and users belongig to these principals. Also in configuration file of your web application you can define restrictions which part of your application can used by particular principal. When you try to access this restricted area of application container will ask for authentication, upon sending right credentials (checked by container according to defined rules in configuration files) it will create SESSION with these credentials. Since your browser is connected with this SESSION (residing on server) through cookies or URLrewriting every following try to access restricted area will be successfull since container looking at user's session knows that this user (browser) has been already authenticated. So, is this security managed by browser or by container? |
| More info please on this topic. can you suggest links where this topic is described in detail
Author: Lakshmi Mohan (http://www.jguru.com/guru/viewbio.jsp?EID=1225552), Feb 7, 2005 More info please on this topic. can you suggest links where this topic is described in detail |
| Re: More info please on this topic. can you suggest links where this topic is described in detail
Author: Sujith M. Nair (http://www.jguru.com/guru/viewbio.jsp?EID=1296444), May 11, 2006 struts using JAAS http://www.mooreds.com/jaas.html |
Can I use precompiled JSPs with Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471935
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
There is nothing about Struts that would care about precompiled versus not precompiled JSP pages, but the details of how you set them up depends on the servlet container you are using. With Tomcat, for example, running the "jspc" command line tool will compile all your pages, but it will also create a bunch of lt;servlet> and <servlet-mapping> tags that need to go into your web.xml file. In particular (at least for Tomcat), though, the path of a JSP page does not change when you use precompiled pages. The reason this works is that the compiler generates a servlet mapping for "/jsp/awsMain.jsp" for you -- and, because this is an exact match, it has higher priority than extension mapping on "*.jsp", which would send the page back to the JSP servlet. Try leaving the path for the compiled case the same as the path for the uncompiled case, and make sure that you've included the necessary stuff in web.xml.
Can Struts be used in a commercial product?
Location: http://www.jguru.com/faq/view.jsp?EID=471936
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Yes. The only requirements you must meet are those listed in the Apache Software Foundation license, which is included at the top of each source file and in the file LICENSE in the top-level directory of the distribution. In addition, contributions of patches, improved code, new features, or even just requests for features are also welcome.
How can I contribute to the development of Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471937
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Struts is distributed by the Apache Software Foundation. These are the same people who distribute the Apache Web server. Like all ASF projects, Struts is managed as a "meritocracy", where everyone's contribution is welcome. Users can help other users on the mailing lists, report bugs, and request new features. Developers can contribute patches, new code, and documentation. The most active Developers may become Committers, who make the actual decisions about the Strut's codebase. You can start by joining the Struts User list. If you enjoy participating there, then sign up for the Struts Developer list too. If you find any problems with Struts, or find a missing feature, you can enter a record to our Bugzilla database.
What's the difference between Jakarta Struts and Jakarta Turbine?
Location: http://www.jguru.com/faq/view.jsp?EID=471938
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
See:
Is there a large degree of XML in Struts? Can you swap a stylesheet and switch form HTML to WML?
Location: http://www.jguru.com/faq/view.jsp?EID=471939
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
The Struts form tags are very much HTML oriented, because they only know how to generate HTML-style forms. One of the major focuses of 1.1 will be better integration with XML in many directions, including an investigation of using things like XPath, XForms, and so on. For integrating XSLT transformations, I would suggest utilizing the "xsl" tag library in the Jakarta Taglibs project <http://jakarta.apache.org/taglibs>. The <xsl:apply> tag is very powerful and flexible, and can interoperate with Struts cleanly.Comments and alternative answers
| Is there a large degree of XML in Struts? Can you swap a stylesheet and switch form HTML to WML?
Author: Raffi Sarkissian (http://www.jguru.com/guru/viewbio.jsp?EID=1109935), Aug 20, 2003 We just recently implemented a system where we did not bother in using the Struts supplied tags. Instead we opted on using the xtags xsl tag library. In a nutshell, we took advantage of the struts framework, complemented it with XML and rendered all in XSL using xtags. The performance is better then expected, JSP logic was minimal and this allowed us to use the concept of skins. The output is adoptable not only to various clients (ASP model), but also to various devices (WML e all). |
>Why aren't the Struts tags maintained as part of the Jakarta Taglibs project?
Location: http://www.jguru.com/faq/view.jsp?EID=471940
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
At first, it was to make it easier to develop the tags as the rest of the framework was developed. Placing the tags in another repository would mean that we would have to be more careful about changes and deprecations as people would be using them in other environment. Once the set of standard tags is published (this is in progress now), we will refactor the Struts tag libraries, and offer the remaining multi-use tags to Jakarta taglibs.
How can I set the locale for each individual user session before the first page displays? I've tried putting the
session.setAtttribute(Action.Locale_key,<locale>) but it always displays in the default locale of the machine? Changing the
machine locale causes the correct properties file to be used so I know that
is not the problem.
Location: http://www.jguru.com/faq/view.jsp?EID=471941
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersIn the Struts example app, this is done by including the following tag on the index.jsp page (actually, on every page):
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html:html locale="true">
... page content ...
</html:html>This causes that <html:html> tag to consult the "Accept-Language" header sent by the browser, and set up a Locale in the user's session if it is not already there -- exactly the same way that the controller servlet does this if you configure it to. NOTE: There are currently problems with this on servlet containers that do not correctly implement the JSP 1.1 requirements for converting custom tag attribute values. We have heard problem reports about JRun 3.0 and ATG in this regard.
| Curiosly!
Author: Rajesh Kini (http://www.jguru.com/guru/viewbio.jsp?EID=1008998), Nov 11, 2002 I am using the <html:html locale=true> tag. My IE browser is set with the language en-us, but all my pages show <html lang="en"> I tried it out with Netscape 7.0, with en-us set first and en set second, still, the same result from the page. I wonder why that is so! |
| Re: Curiosly!
Author: Jothibasu Ramachandran (http://www.jguru.com/guru/viewbio.jsp?EID=1083851), May 12, 2003 The language is selected using the Locale value that is conforming to the ISO list for country codes. As per that the country/Locale is specified with a "2 char" code. That could be the reason why it is taken so. Please check with the Locale code listing in the web to find the code for en-us. |
| the answer
Author: Aleksey Skorokhodov (http://www.jguru.com/guru/viewbio.jsp?EID=965496), Jun 20, 2003 I had the very same problem. the solution is VERY simple :) you need to restart our browser after changing your locale. it helped me |
| Re: Curiosly!
Author: Stjepan Brbot (http://www.jguru.com/guru/viewbio.jsp?EID=1161395), Apr 8, 2004 According to Ted Husted's book "STRUTS in Action" STRUTS framework uses only country code (first two letters in Locale string) meaning that for STRUTS "en", "en_gb" and "en_us" are the same thing, the same Locale "en". |
I have a simple question about localisation: If there is multiple users using the same localisation parameters : do
they share a common ResourceBundle instance or do they have their own one. It seems to me that each user has his own
ResourceBundle instance but does that affect the performance of the application.
Location: http://www.jguru.com/faq/view.jsp?EID=471942
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
The application's message resource bundles are shared across all of the users of a particular Struts-based web application. The only thing that is unique to a particular user is the java.util.Locale object (stored in the user's session) that represents his or her current Locale preferences.Comments and alternative answers
| SubQuestion
Author: Stjepan Brbot (http://www.jguru.com/guru/viewbio.jsp?EID=1161395), Apr 8, 2004 So if I have ResourceBoundle.properties and ResourceBoundle_hr.properties, container creates two objects in memory (one for each properties file) and shares these two object among many users. Is that correct? |
| Re: SubQuestion
Author: Esteve Olm (http://www.jguru.com/guru/viewbio.jsp?EID=1171236), Jan 28, 2005 Yes, it is |
Why can't the Struts tags access the properties of my beans?
Location: http://www.jguru.com/faq/view.jsp?EID=471943
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersStruts uses JavaBeans Introspector to discover properties of beans. Introspector is pretty picky in the way it decides whether something is a property or not. Specifically, it requires that
- Both getter and setter be declared public and non-static
- The return type of the getter be the same as the type of the argument of the setter.
So, first check if your property breaks one of these rules.
| More requirements
Author: Giri M (http://www.jguru.com/guru/viewbio.jsp?EID=971868), Nov 19, 2002 If the property name in Struts tag is called "password", then according to the Java bean spec, the getter/setter should look like getPassword and setPassword. if u define it as getpassword, it will not work!1 |
| Another reason
Author: Jean-Carl AMSLER (http://www.jguru.com/guru/viewbio.jsp?EID=1065682), Mar 13, 2003 If Struts debugger tell you that the property of a tag is unreachable and even if the property exists (with a get method), it may the property get method returns "null" value...
|
I usually need 'wrap="virtual"' as an attribute for my textareas. It isn't part of the HTML spec, but it's supported in
both Netscape and IE, and it's pretty useful.
Location: http://www.jguru.com/faq/view.jsp?EID=471944
Created: Aug 8, 2001
Modified: 2001-10-27 01:52:10.919
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThe Struts Action works through introspection. It doesn't know (or care) whether the value in a form was rendered by a Struts custom tag or not. This means if you use a standard textarea tag in your form, and give it a name that matches a property in your form bean, Struts will use that attribute just as if it had been rendered by a html:textarea tag. After all, this is all the Struts html:textarea tag does. To seed the textarea from the form bean, you could code something like:
<textarea name="article" rows="15" cols="60" wrap="soft"></textarea>
And everything else will be automagical again.
| jsp pass-through tag attributes
Author: Marco Leprai (http://www.jguru.com/guru/viewbio.jsp?EID=1195295), Mar 20, 2007 This is a big limit of tag libraries, there should be this role in the jsp parser: if doesnt recognize an attributes is treated as a pass-through and rendered as is in html |
| My action class doesn't recieve form values from inputs
Author: Tomas Novellino (http://www.jguru.com/guru/viewbio.jsp?EID=1340047), Jun 18, 2007 I have <html:text name="myForm" property="someProp" /> but i had a javascript error when I used myForm.someProp.value = "anything"; before submitting the form. So I changed it to <input type="text" name="someProp" id="someProp" /> and before submiting the form I changed it to document.getElementById("someProb").value = "anything"; Therefore my javascript problem was solved. However, in my actionform execute method when I do: FormClass subform = (FormClass) form; String some = subform.getSomeProb().trim(); I get a null pointer exception.... I noticed that the var named some fills with no data... Can anyone help me.. thxs BTW my problems were only in IE... in mozilla it woerked just fine before my changes |
How do I use Javascript with my Struts forms?
Location: http://www.jguru.com/faq/view.jsp?EID=471945
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThe relevant HTML tags provide support for the Javascript event handlers onblur, onchange, onclick, ondblclick, onfocus, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup.
For more about Javascript events, see the Netscape Javascript Reference guide.
For more about HTML tags, see the Struts HTML Tag Guide.
As usual, the Javascript itself can then be placed:
- Inline, if it is simple enough, like onclick="history.go(-1)"
- As a <SCRIPT> within your JSP
- As an included <SCRIPT src="my.js"> to your JSP
Note that the Struts Javascript properties use all lowercase identifiers, for XML compatibility.
| Struts and javascript
Author: Candice Lohe (http://www.jguru.com/guru/viewbio.jsp?EID=793077), Mar 12, 2002 The <SCRIPT src="myfile.jsp" ></SCRIPT> works fine for regular jsps; however, there doesn't seem to be a way of using it with templates. Any suggestions? |
| Re: Struts and javascript
Author: nicolas lavielle (http://www.jguru.com/guru/viewbio.jsp?EID=1125585), Nov 11, 2003 If I want to use Javascript files in different languages, how can I do that ? I can't use <SCRIPT srckey="mypath.inresourcebundle"></SCRIPT> Any suggestions ? |
| javascript on struts
Author: Ravindra Reddy (http://www.jguru.com/guru/viewbio.jsp?EID=1284736), Feb 20, 2006 1.You have Javascript tag in "struts-html.tld" i.e <html:javascipt> using this u can solve u r problem. |
| Re: javascript on struts
Author: WarnerJan Veldhuis (http://www.jguru.com/guru/viewbio.jsp?EID=854798), Feb 20, 2006 <html:javascript/> is for client side validation, and has nothing to do with other sources of javascript. Please provide an example where you show us how you think it should work. |
| internationalization of javascript with struts.
Author: Rajitha Yedla (http://www.jguru.com/guru/viewbio.jsp?EID=1338227), May 28, 2007 This is how to internationalize javascript with strts. This display msgs from the properties file based on the browser language.
// sample code block
<@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" >
<html>
<head>
<script language="JavaScript">
function m() {
alert("<bean:message key='msg'>");
}
</script>
</head>
</body>
<input type="button" name="click" onlick = "m()">
</body>
</html>
|
| This is how to internationalize javascript with strts. This display msgs from the properties file based on the browser language.
Author: Rajitha Yedla (http://www.jguru.com/guru/viewbio.jsp?EID=1338227), May 28, 2007
// sample code block
<@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" >
<html>
<head>
<script language="JavaScript">
function m() {
alert("<bean:message key='msg'>");
}
</script>
</head>
</body>
<input type="button" name="click" onlick = "m()">
</body>
</html>
|
How do I use Javascript to perform validation in Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471946
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThe best way is using David Winderfeldt's Struts validator servlet. This provides seamless client-side and server-side validation using regular expressions.
Other than that, you can also attach other Javascript validation to the Struts form fields using the provided properties for Javascript event handling. Of course, these types of validations cannot be guaranteed if a browser has Javascript turned off.
Why doesn't Struts provide it's own facility for regex or Javascript validations?
David Winterfeldt's Validator is being integrated with Struts 1.1.
| how to perform validations in struts.
Author: vidhya shanmugam (http://www.jguru.com/guru/viewbio.jsp?EID=1326733), Feb 1, 2007 I am new to struts. Could You help how to perform validation in struts. |
| Re: how to perform validations in struts.
Author: aruna kudupudi (http://www.jguru.com/guru/viewbio.jsp?EID=1349953), Oct 29, 2007 Dear sir/madam, please send the book to my mail |
Is it possible to combine dynamic Javascript menu systems with Struts?
Location: http://www.jguru.com/faq/view.jsp?EID=471947
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
The challenge with doing this is that the JSP tags run on the server (as the page is being generated), while the JavaScript runs on the client side. To integrate the two, you need your tags (and other JSP code) to dynamically generate the JavaScript functions themselves -- sort of having a program write a program -- so that the JavaScript is customized to your particular need on this particular page. A very trivial example is the way that the <html:form> tag deals with the "focus" attribute. If you specify it, a dynamically generated bit of JavaScript is created to set the input focus, which includes the name of the field you want initial focus assigned to. For a more comprehensive scenario, consider that for most menuing systems you will need to configure the list of available options into a JavaScript array or something. You could use the <logic:iterate> tag to render the elements that get set in the array's initialization expression.Comments and alternative answers
| struts rollover example
Author: dmitry amelchenko (http://www.jguru.com/guru/viewbio.jsp?EID=877173), Mar 11, 2003 The article explains things very well, it's just too high level though. If a simple example of how does a rollover javascript work with struts <html:image> can be provided, it would make life much easier. |
| Re: struts rollover example
Author: Deepak Singh (http://www.jguru.com/guru/viewbio.jsp?EID=1257670), Oct 21, 2005 dmitry, i totally agree with your views about the author of this article. |
Under Netscape 4.7 for Windows, the html:form focus feature doesn't work properly. Is there a work around?
Location: http://www.jguru.com/faq/view.jsp?EID=471948
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
The problem is that the focus feature works all right at first, but when you press tab, it proceeds to the address bar, rather than the next field. After you tab around once, it starts working as expected. One work around is to use the "onblur" event on the initial field to select the second. After that, Bob's your uncle!
Example:
<html:form action="/logon" focus="username">
<p>Username <html:text property="username"
onblur="this.form.password.focus();"/>
<p>Password <html:password property="password"/>
<p><html:submit property="submit" value="SIGN IN" />To focus the first field on the first form, you can also do this
<body onload="document.forms[0].elements[0].focus();">
in all your form pages rather than use the Struts html:form focus property.
Is the Struts object-orientated appropriate for small, heavily-loaded servers?
Location: http://www.jguru.com/faq/view.jsp?EID=471949
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Compared to embedding the application logic in your servlet, Struts doesn't cost very much in terms of object creation. Struts only creates an instance of an Action class once, and then reuses it continually. You will also find that, with more recent JVMs, object creation overhead has been dramatically reduced -- it may not longer be the dominant factor in performance. ActionForm beans in Struts can be stored in the user's session (this was the original design), but also as request attributes. This is particularly useful when the entire form is displayed on one page, and the page contains every property as either a hidden field or a visible field. In such cases, there is no need to keep the form bean instance around in between requests. At the end of the day, though, you have to have an incredibly small server for the performance issues like single object versus lots of objects matter very much.
Does anyone know the performance difference between a direct method call andintrospection like Struts uses?
Location: http://www.jguru.com/faq/view.jsp?EID=471950
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Independant performance engineers have benchmarked JDK 1.3 and the difference is now insignificant.Comments and alternative answers
| Are benchmarking results available on-line?
Author: Roman Pozlevich (http://www.jguru.com/guru/viewbio.jsp?EID=225725), Aug 24, 2001 I'm curious about the benchmarking results. Can somebody provide links where I can see them? |
Can we configure a separate log for each application?
Location: http://www.jguru.com/faq/view.jsp?EID=471951
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
There is a restriction in Tomcat 3.2 related to how you declare log files. In Tomcat 4.0 this has been enhanced, letting you declare a separate destination for the servlet log per application, instead of globally. If you need to run under Tomcat 3.2, I suggest that you add some sort of application identifier to the log messages being created. A common pattern creates log files like this:
[Application1] This event happened
[Application2] That other event happened
Is there is some kind of "j2ee compliant" way of doing user authentication and role-assignment - are there any
standards one is supposed to use?
Location: http://www.jguru.com/faq/view.jsp?EID=471952
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThe J2EE recommendation for this is to use container-managed security (i.e. the <security-constraint> elements defined in web.xml) for user authentication and access control. Doing so means that the container is taking care of these issues for you, and (perhaps more importantly) that user identities are shared between the web layer and the EJB layer, because the server will be using the same underlying "database" of users and roles.
The only downside to this approach is that there is not yet a standardized API for portably accessing and maintaining a "database" of users and roles ("database" is in quotes because the actual implementation could be anything, including static text files or directory servers).
Instead, most servers provide a server-specific API to do this kind of thing. For example, in Tomcat you can implement an API called a Realm that talks to your existing database of users, and then tell Tomcat to use this Realm implementation for user authentication. In that way, new users added to the database (by whatever means) become instantly authorized for web use also. If you were to switch to a different engine, you would need to re-implement this function according to the APIs provided by the new server, but you would not need to update your applications.
| Container-managed security
Author: Mitch Dresdner (http://www.jguru.com/guru/viewbio.jsp?EID=390316), Feb 14, 2002 When using container managed security (in Catalina), is there anyway to logoff? |
| Re: Container-managed security
Author: Matt Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=141820), Feb 26, 2002 Invalidate the session |
| Re[2]: Container-managed security
Author: Mitch Dresdner (http://www.jguru.com/guru/viewbio.jsp?EID=390316), Feb 27, 2002 Matt, I was using Basic Authentication and invalidating the session wouldn't work. Works fine for forms. I found the following in one of the Tomcat specs: "Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. (For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser). Any changes to the database information for an already authenticated user will not be reflected until the next time that user logs on again." Thanks for taking time to reply. Regards,
Mitch
|
| Re[3]: Container-managed security
Author: Matt Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=141820), Feb 27, 2002 RFC2616 states that If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. Although this is kind of open to interpretation, IE5 for one sees an additional 401 Unauthorized response, after credentials have been presented, as an indication that the credentials have expired, and the user is presented with a new prompt. If you use the Jakarta response taglib, the following will work:
Obviously, this should only be returned until the user has been re-authorised. In the end, this removes some of the power of the deployer by hardcoding a Realm name, etc. There may be other ways to ensure expiry in the Container-Managed Security method you use, returning similar HTTP return code and header as described above. HTH - Matt J. |
How can you prevent users from accessing a JSP directly that is designed to be used from an Action?
Location: http://www.jguru.com/faq/view.jsp?EID=471953
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersPut those JSP pages in a directory under WEB-INF; for example, WEB-INF/jsp. Files under the WEB-INF directory cannot be directly accessed. Another approach is supported by the servlet API if you are using container-managed security for your application. You can define a security constraint that lists no roles as being allowed, which the servlet container will interpret as not allowing access to anyone directly from a request. You can forward to (or include) such a page -- just not request it directly.
Note that this behavior was not clearly specified in the 2.2 servlet spec, so your mileage might vary there -- but all 2.3 containers are required to act this way.
Consider the following security constraint:<security-constraint>
<web-resource-collection>
<web-resource-name>All JSP Pages</web-resource-name>
<url-pattern>/pages/*</url-pattern>
</web-resource-collection>In a servlet 2.3 container (such as Tomcat 4.0), this is interpreted to mean that there is no direct access at all to any URL like:
http://localhost:8080/myapp/pages/menu.jsp
but you are allowed to use a request dispatcher to access them. This is because security constraints are to be checked only on the *original* URL, not on the forward/include. Thus, if you want to ensure that a page is accessed only via the controller servlet, you can give it a URL path within the "pages" subdirectory, and the container will take care of this for you.
| How do you address JSPs under WEB-INF/jsp? I thougt this wasn't possible?
Author: frank prumbaum (http://www.jguru.com/guru/viewbio.jsp?EID=578394), Dec 10, 2001 ? |
| Re: How do you address JSPs under WEB-INF/jsp? I thougt this wasn't possible?
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042), Dec 30, 2001 Most containers allow servlets to forward to a JSP under WEB-INF, and I have it from good authority that this is the intended behavior. Some containers, notably WebLogic, choose not to implement this feature. -T. |
| Re[2]: How do you address JSPs under WEB-INF/jsp? I thougt this wasn't possible?
Author: Sken Malkowitch (http://www.jguru.com/guru/viewbio.jsp?EID=898662), May 31, 2002 Hi Ted, I'm using WebLogic Ver 5.1.0 and now I want to develope some applications with Struts. Can you tell me if this or some newer versions of WebLogic implement this great feature? If so, can you tell me which versions are implementing it. TNX |
| Re[3]: How do you address JSPs under WEB-INF/jsp? I thougt this wasn't possible?
Author: Matt Cox (http://www.jguru.com/guru/viewbio.jsp?EID=885298), Jun 3, 2002
<security-constraint>
<web-resource-collection>
<web-resource-name>All JSP direct access</web-resource-name>
<url-pattern>private/*</url-pattern>
<http-method>POST</http-method>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description>
No Access
</description>
<role-name>restricted</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>error.html</form-login-page>
<form-error-page>error.html</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description>NO Access</description>
<role-name>restricted</role-name>
</security-role>
My error.html simply has one word: DENIED. It's a bit of a hack but it works. I dont' see why there couldn't be another auth-method added that simply refused access with a 403 response.
After moving my private jsp pages to the private path (all but the logon.jsp) I needed to modify the struts-config.xml to correct map the action for inputs and forwards to the new location. |
| Hello
Author: Waseem Daboul (http://www.jguru.com/guru/viewbio.jsp?EID=1383429), May 27, 2009 I am really new to the JDeveloper and most of these things. I really need some more explanation on how to prevent accessing the jsp pages directly from the web browser. In addition, when I logout and press back it goes back. I want it to prevent that too!! Thanks a lot |
| while using this i face problem
Author: gomathi nayagam (http://www.jguru.com/guru/viewbio.jsp?EID=1341425), Jul 4, 2007 i have jsp pages that include multiple jsp pages the parent jsp alone loading all other childs are not loaded |
| Re: while using this i face problem
Author: praveen og (http://www.jguru.com/guru/viewbio.jsp?EID=1343853), Aug 1, 2007 R u mad ? Where u had put these things ,keep these things inside web .xml it will work. concentrate on your work other than snacks.tell to tsunami team also |
| How do you implement the security constraint to allow no JSP direct access?
Author: Bobby Lewis (http://www.jguru.com/guru/viewbio.jsp?EID=715163), Jan 9, 2002 How do you implement: <security-constraint> <web-resource-collection> <web-resource-name>All JSP Pages</web-resource-name> <url-pattern>/pages/*</url-pattern> </web-resource-collection> This means that noone (no logins) can access any files under /pages/. Where is this code placed? In the web.xml or the struts-config.xml file? Or elsewhere? Thanks. Bobby Lewis |
| Re: How do you implement the security constraint to allow no JSP direct access?
Author: Bobby Lewis (http://www.jguru.com/guru/viewbio.jsp?EID=715163), Jan 9, 2002 Actually, I'm working with the struts-examples application in Tomcat 4.0 on Windows 2000. I put this: <security-constraint> <web-resource-collection> <web-resource-name>placeorder</web-resource-name> <url-pattern>/*.jsp</url-pattern> <http-method>POST</http-method> <http-method>GET</http-method> </web-resource-collection> </security-constraint>in the web.xml in the WEB-INF subdir of the struts-examples app. When I restart Tomcat, I get: PARSE error at line 92 column 11 org.xml.sax.SAXParseException: The content of element type "web-app" must match "(icon?,display-name?,description?,distributable?,context-param*,servlet*,servl t-mapping*,session-config?,mime-mapping*,welcome-file-list?,error-page*,taglib* resource-ref*,security-constraint*,login-config?,security-role*,env-entry*,ejb- ef*)".Everything seems right. Any ideas? |
| Re[2]: How do you implement the security constraint to allow no JSP direct access?
Author: Devinder Singh (http://www.jguru.com/guru/viewbio.jsp?EID=141755), Mar 12, 2002 The elements you choose to include in your web.xml should |
| Re[2]: How do you implement the security constraint to allow no JSP direct access?
Author: Prasad Javdekar (http://www.jguru.com/guru/viewbio.jsp?EID=1189769), Jul 31, 2004 Hi Bobby, Your <security-constraint> element looks fine, true, but check the sequence of all the web.xml elements. The error you got indicates that you might have wronged the "sequence".
regards. |
| Security of JSP Pages
Author: Robert Nicholls (http://www.jguru.com/guru/viewbio.jsp?EID=527915), Jan 24, 2005 This is a little off the topic but it is the reverse problem. I an using container managed security under Tomcat. It works well except when I pop up a new window for "help". This is an active page (JSP). It seems that Tomcat sees a new session for the window and insists that the application log in again for the popup. Short of fiddling with the security signature (<url-pattern> ) is there some way to keep the new windows within the same session and thus obviate the need for a new login on the popup? Thanks, Bob N- |
Using action classes as adapters and session EJBs for business logic sounds like a good way to go. Is also using EJBs as
actionforms is a good idea because they are a good target for object reuse/
Location: http://www.jguru.com/faq/view.jsp?EID=471954
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
ActionForms are not designed for reuse with an EJB. In fact, early on, the ActionForm was changed from an interface to an abstract class to discourage this idea.
The reasoning goes like this:
- An ActionForm is part of the view layer of MVC, not the model layer like an EJB (or a regular JavaBean that represents persistent data).
- The sole purpose of an ActionForm is to maintain the state of all the input variables on a particular form, so that you can reproduce the form pre-filled-in if the user made an error that they need to fix. This matches the expectations of users who are used to GUI-based client server apps, that never make you retype any input except the stuff you did wrong.
- Because of the above, the "domain" of an ActionForm does not necessarily match any existing EJBs or model layer JavaBeans. It is not uncommon to have inputs from a single form that will ultimately cause updates to more than one undelrying EJB or model bean.
- Using a separate class for the ActionForm means you can change the underlying organization of your model beans or EJBs without impacting the view layer (although there might be modest impacts on the Action classes that copy things back and forth).
- In addition, most EJBs and model beans have validation rules internally that prevent them from accepting semantically invalid data. Such rules would prevent you from accomplishing the primary purpose of an ActionForm -- storing all of the user's input fields, so that you can reproduce the input screen.
- Also, if your form is multiple pages and you were using the real EJB, let's say you start updating properties based on receiving the first page. Now, you've potentially started locking resources in the underlying database -- and you have to deal with the fact that the user may never come back and finish this transaction.
So, the bottom line recommendation is that you plan on building simple JavaBeans for your ActionForms. Most of the time, an ActionForm will have just getters and setters, with no error checking (other than a validate() method if you want to use it, plus the reset() method). PropertyUtils also has a convenience function that can copy properties with like names from your EJB to the ActionForm bean (or vice versa), to reduce the amount of tedious code that this approach implies. And, at some future point, it's reasonable to expect a development tool to be able to auto-generate ActionForm beans for you.
Using an EJB as a bean that provides data values used in the presentation, on the other hand, is pretty easy. Just store the client-side instance you get back from the EJB server as a request attribute or session attribute -- from the perspective of the Struts custom tags, this EJB just looks like a JavaBean with getter methods, so they don't care that it is really an EJB. NOTE: If the EJBs are really on a remote server this could have some performance impact -- you might be better served to copy data into local beans in that case.
Why is the form bean automatically created by both servlet and form tag?
Location: http://www.jguru.com/faq/view.jsp?EID=471955
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
It is valid for a user to enter the system either through the servlet or through the JSP form, and so the bean must be created in either place.
How can you tell if a form bean was automatically created?
Location: http://www.jguru.com/faq/view.jsp?EID=471956
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
In general, you can define a special member variable in the bean that indicates that it has just been created. On a manual create you would reset that yourself, but on an auto create it would remain set, and the validate method would detect it (or you could check manually).
Reset for validation
Location: http://www.jguru.com/faq/view.jsp?EID=471957
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThere is a reset() method on ActionForm that is called *before* Struts does the auto-populate trick. The contract is that this method should reset all relevant attributes for this particular form to default values. For checkboxes, you would want to set the corresponding boolean to false. It will be set to true by the auto-populate method *if and only if* the checkbox was checked (and therefore included in the POST).
For integers, it is technically feasible to distinguish an empty field ("") versus a zero ("0"). If we decide not to call the setter in this scenario, then the ActionForm property will remain at it's default value, so you can distinguish whether it was entered or not.
On the other hand, we could take the approach that the form should have displayed the default value in the first place, and the user would have had to erase the existing value to cause an empty string to be posted -- and that the bean should want to know about that. Because we have to generate a legal integer value, the decision is what value to use for indicating "no input". Zero is the current mechanism for this, but it's not the only choice.
| Checkbox resetting in general...
Author: Jeff Hamilton (http://www.jguru.com/guru/viewbio.jsp?EID=791422), Mar 13, 2002 I've got a question regarding the best way to handle checkboxes and resetting them. My requirement is that the form is in the session (so it can be returned to easily) and that the checkboxes maintain their appropriate values. If I include code to set them to false in the reset() method of the form, the form behaves properly while I am posting on that page. But, when I return to that page from another page, Struts has reset all my checkboxes to false (off). If I don't include the reset() code, then the values are maintained properly between pages but not within posts on that page. What's the best way to solve this problem? |
| Re: Checkbox resetting in general...
Author: Alice Howell (http://www.jguru.com/guru/viewbio.jsp?EID=910261), Jun 11, 2002 At http://jakarta.apache.org/struts/newbie.html there is a question "Why are my checkboxes not being set from ON to OFF?"
The answer states:
"If the value of the checkbox is being persisted, either in a session bean or in the model, a checked box can never unchecked by a HTML form -- because the form can never send a signal to uncheck the box. The application must somehow ascertain that since the element was not sent that the corresponding value is unchecked."
It also states to possibly use a radio button. I am in the process of trying to make this work because I am keeping my form in the session. I am going to try to see if I can check for the element being sent.
|
| Re[2]: Checkbox resetting in general...
Author: Chris Felaco (http://www.jguru.com/guru/viewbio.jsp?EID=281872), Jun 8, 2004 There is a very simple solution to the checkbox problem. The trick is to always add a hidden field AFTER the checkbox with the same parameter name but with the value set to "false": <html:checkbox property="booleanProperty" value="true" /> <input type="hidden" name="booleanProperty" value="false"> Basically, the hidden parameter ensures that there is some request parameter submitted, which will always set the corresponding ActionForm property. If the checkbox is checked, the 2 parameters will be passed: "booleanProperty=true&booleanProperty=false". But the beanutils code only uses the first parameter to set the value. If the checkbox is left unchecked, then there will be only 1 parameter "booleanProperty=false" which will ensure the property is set. The HTML spec says that form elements must be submitted in the GET or POST in the order that they are specified in the HTML, and all browsers I have used obey this rule. There is no risk that the hidden parameter will obscure the form field as long as you always put it after the checkbox. The beauty of this solution is that it places the burden in the hands of the page author where there can be more flexibility. It also allows the page author to invert the meaning of the checkbox without bothering the application developer. All the page author needs to do is reword the caption, and switch the ordering of the values used in the checkbox and hidden fields. Also, it works with string or numeric properties just as easily. |
| Re[3]: Checkbox resetting in general...
Author: Aaron Mapes (http://www.jguru.com/guru/viewbio.jsp?EID=1202934), Oct 1, 2004 Brilliant solution, very simple indeed, and I scoured the net for hours on ways to do this that didn't involve subclassing the DynaValidatorForm class. This work around really should be easier to find, or added to a Struts FAQ somewhere... |
| Re[4]: Checkbox resetting in general...
Author: Miles Daffin (http://www.jguru.com/guru/viewbio.jsp?EID=1213072), Nov 25, 2004 Hear hear! Me too. For hours.... What a relief! Thanks Chris. |
| Re[3]: Checkbox resetting in general...
Author: Emory Smith (http://www.jguru.com/guru/viewbio.jsp?EID=1213312), Nov 27, 2004 thank you chris!! |
| Re[3]: Checkbox resetting in general...
Author: Nishi Shah (http://www.jguru.com/guru/viewbio.jsp?EID=1221411), Jan 16, 2005 This is not a good solution at all. It is just a work around. This solution will fail when you want to call javascript function on clicking of the checkbox. The correct solution is :- override the "reset" method in the form bean and set the checkbox value false to correctly identify the checkbox value from request. If your bean is in session scope and if you don't want to identify the correct value everytime then get the action from request object and set/reset the checkbox value. |
| Re[4]: Checkbox resetting in general...
Author: Justin Galzic (http://www.jguru.com/guru/viewbio.jsp?EID=1221739), Jan 17, 2005 A way to accomplish what you want without any "hacks" to your jsp/ui is by extending the DynaValidatorForm and creating your own reset method (you don't need to override anything else). In addition to calling super.reset, you need to change the property value of your checkbox used by the DynaValidatorForm's map. reset looks like this:super.reset(actionMapping, httpServletRequest); Map map = getMap(); if (map.containsKey("checkbox_prop_name") { map.put("checkbox_prop_name", Boolean.FALSE); } This works well for me without having to make any changes to my presentation layer. Justin |
| Re[4]: Checkbox resetting in general...
Author: hal taylor (http://www.jguru.com/guru/viewbio.jsp?EID=1230843), Mar 4, 2005 What do you do if you want the checkbox to default to true/checked? You can have it set true in the FormBean's constructor, but then how do you register the change to false if the user de-selects the checkbox? How does reset() help with this? How do you tell if no value was submitted? If you have defaulted the bean value to true, and the checkbox is then deselected, the value for this field will not be submitted, and therefore not get updated to false, right? How does one get around this problem when checkboxes should be true by default? In my case, javascript is not an option.... |
| Re[5]: Checkbox resetting in general...
Author: Assaf Berg (http://www.jguru.com/guru/viewbio.jsp?EID=1234912), Mar 27, 2005 I've had this problem as well. You can't set the checkbox value to true in reset() because then it will stay on for ever. What I did is added a method called setup() to the form, that applies default values to fields (such as checkboxes that need to be checked). The setup method is called only when the form is initialized, so if the user changes the checkbox value it is not overridden by anything in reset(). In order to only call setup() in initialization i've added a hidden field to the JSP with a certain predefined value (doesn't matter which, i used the string 'true' because I called that field initialized). When the Action that prepares the form is called first, 'initialized' won't be set. Only after submitting the form its value will change to true. in the validate() method of the form I call setup() only if initialized != true. |
| Re[4]: Checkbox resetting in general...
Author: Mark Salamon (http://www.jguru.com/guru/viewbio.jsp?EID=589110), May 23, 2005 You can get this to work. B/c you have two elements with the same name, you can get an array of those values (http://docs.sun.com/source/816-6408-10/form.htm), then just pick the element you want and work with that. I did it like this, where the first time elementX is listed on the page it's the checkbox and the 2nd time it's the hidden field:
// get array of items with the same name |
| Re[3]: Checkbox resetting in general...
Author: deep sekhar (http://www.jguru.com/guru/viewbio.jsp?EID=1224723), Feb 2, 2005 Thanks Chris, I was trying for the same and was fighting a lot for the solution, Thanks for solution i was relieved |
| Re[3]: Checkbox resetting in general...
Author: stephen hartley (http://www.jguru.com/guru/viewbio.jsp?EID=1263841), Sep 23, 2005 This is very useful, solved my problem of correctly resetting checkboxes in session scope. Thanks very much for contributing it. Steve |
| Re[3]: Checkbox resetting in general...
Author: Patrick Choi (http://www.jguru.com/guru/viewbio.jsp?EID=1278514), Jan 15, 2006 Wonderful solution, I was half way through subclassing the DynaActionForm when I found your page. Added ONE line of code and the whole thing is just working now. Thanks a lot! |
| Re[3]: Checkbox resetting in general...
Author: Johan Hörting (http://www.jguru.com/guru/viewbio.jsp?EID=1289797), Mar 23, 2006 Tank you Chris. Now I can get ride of my nasty solution in my form-bean code. |
| Re[3]: Checkbox resetting in general...
Author: Stefan K (http://www.jguru.com/guru/viewbio.jsp?EID=1298171), May 24, 2006 GENIOUS!!!!!! |
| Re[3]: Checkbox resetting in general...
Author: Ingo Jobling (http://www.jguru.com/guru/viewbio.jsp?EID=1199343), Nov 29, 2007 Using the hidden field is an excellent workaround, thanks for sharing it! It should be in the Struts FAQ. It would be nice if the <html:checkbox> tag inserted the hidden field. |
| Re[3]: Checkbox resetting in general...
Author: William Edwards (http://www.jguru.com/guru/viewbio.jsp?EID=1361776), May 7, 2008 I had this problem just now. Where I had a session scoped form, containing checkboxes, that need to be reset ONLY when doing a POST to the next page. There is another elegant technique, without hacking the page with hidden fields. This requires overriding the RequestProcessor (or the TilesRequestProcessor if you are using tiles).
(1) Create a your custom class:
(2) Place this CustomTilesRequestProcessor class in your struts-config.xml as the Controller. e.g <controller processorClass="full.package.name.CustomTilesRequestProcessor" bufferSize="4096" /> (3) In the struts-config.xml, the action that requires the checkBoxes to be reset immediately before the form is posted should have the extra attribute:
Finally, write your own resetCheckBoxes() method in your form. In my case, I subclassed the DynaActionForm, and wrote the method in my class. Works a treat.
The only critisism, is that the Id of the action is hard coded into the processPopulate() method. But that is a limitation of the struts-config.xml.
|
| Re[4]: Checkbox resetting in general...
Author: William Edwards (http://www.jguru.com/guru/viewbio.jsp?EID=1361776), May 7, 2008 You will need struts 1.3.9 or greater to use the id, otherwise, use the path. |
| Re[3]: Checkbox resetting in general...
Author: an uj (http://www.jguru.com/guru/viewbio.jsp?EID=1367050), Jul 18, 2008 Hi Chris, |
| « previous | beginning | next » |
Does an Action have to return an ActionForwarding?
Location: http://www.jguru.com/faq/view.jsp?EID=471958
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
No. Sometimes, it might be better for an Action to handle the request itself. For example, you might need to return dynamic content that would be impossible or impractical to create with a JavaServer Page. Or, you might need to return content using a special MIME type.
If the Action handles the request itself, and presents an appropriate view to the client, it can return null to the controller.
How can Struts check for a set of global conditions before processing an action?
Location: http://www.jguru.com/faq/view.jsp?EID=471959
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThis often comes up in the context of authenticating users or with other control flow issues.
The direct approach would be to subclass the ActionServlet controller servlet, and override a method like processActionPerform (which actually calls the selected Action) or processActionForward (which forwards control to the returned logical page name). You could then inspect the current state of the world, and inject flow-of-control changes like this still utilizing the superclass's basic functionality.
To make the types of things you inject somewhat configurable, you might also want to use your own custom ActionMapping subclass, with extra bean properties that describe (to your override method) what exceptional things to do and when to do them -- the selected ActionMapping instance is made available to most of the processing calls, so this information would be easily accessible.
If, as part of injecting control follow changes, you need to track where the user was in your application, you might have your ActionServlet subclass maintain a request-scope attribute with a well-known name, containing the value returned by request.getServletPath(). This would act something like the "referer" header in an HTTP request, and provide some history tracking.
| Generic example of this?
Author: D parker (http://www.jguru.com/guru/viewbio.jsp?EID=871708), May 8, 2002 very interested in something like this in order to accomplish a work flow. E.g., I would like to show a collection of database info on a splash page. This means I have to check for the existance of the cached objects holding the db info and print them. This means routing the request to already existing Actions and then back to the index.jsp. Unless there is an easier way to accomplish this, please provide an example of subclassing the ActionServlet controller servlet to achieve a url sequence. Thank you.
David |
| Other alternatives: 1) base Action class, 2) RequestProcessor (Struts 1.1)
Author: Jerome Jacobsen (http://www.jguru.com/guru/viewbio.jsp?EID=65688), Oct 3, 2002 Two alternatives to subclassing ActionServlet are: 1) providing a base Action class and 2) subclassing RequestProcessor (new in Struts 1.1). 1) Base Action class: Provide a base Action class that all of your Action classes subclass. Do your "global conditions" checking in the base Action's execute() method. In the subclass Actions' execute() methods, first call the base Actions' execute(). Or use a "method template" technique. Force all of the base Action subclasses to implement an execute() "like" method, let's call it perform(). Then the base Action's execute() would call perform() after doing it's custom stuff. And the subclass Actions would not implement execute(), just perform().
2) Subclass RequestProcessor in a similar way as Ted described for subclassing the ActionServlet. But must be Struts 1.1 or greater. |
| Re: Other alternatives: 1) base Action class, 2) RequestProcessor (Struts 1.1)
Author: Bill Newsom (http://www.jguru.com/guru/viewbio.jsp?EID=1169641), May 10, 2004 The base action class technique is interesting, and I would like to use it. The problem is the mapping of this base action so that it can handle ANY of the forms that could be submitted to it. How would that be done? |
How can I initialize custom "application scope" objects for use in a Struts application?
Location: http://www.jguru.com/faq/view.jsp?EID=471960
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersOne way would be to subclass the ActionServlet, to to initialize whatever application scope objects you might need. Just remember to call the super.init() method!
A better approach would be to write another servlet, and auto-load both the Struts controller and your own servlet through the web.xml file. The Example application does this to load a "database" servlet, which is then accessed throughout the application. This way you can initialize application-specific things through your specialized servlet, and leave the normal Struts controller servlet alone.
In a servlet 2.3 environment (such as Tomcat 4.0), you will also be able to use the new application event listener APIs to catch the contextInitialized() and contextDestroyed() events. This will become the preferred method, once servlet 2.3 containers are widely available.
| Best practice to access data source config?
Author: Niko Schmuck (http://www.jguru.com/guru/viewbio.jsp?EID=408882), Jan 28, 2002 The problem i found with the struts-example web application and the DatabaseServlet (extends HttpServlet) is:
Thanks,
Niko. |
| how do I give an object 'application scope'?
Author: Dave Sag (http://www.jguru.com/guru/viewbio.jsp?EID=1043334), Jan 6, 2003 I have gone the first route with my project and can't find any docs that would show me how I actually make my application scope objects visible to my actions? as my shared data structure is about 50megs of read only data held in RAM for speed I don't want every action to have it's own copy. hence the use of application scope vars. your plan b is quite an interesting one. would you care to elaborate a bit or point me to some docs I can read on this technique? dave
|
| Re: how do I give an object 'application scope'?
Author: Durga Rani (http://www.jguru.com/guru/viewbio.jsp?EID=1198025), Sep 8, 2004 Write a plugin which implements 'org.apache.struts.action.PlugIn' . Override the init method to load the object in the application scope using servletcontext.setAttribute API. |
| Re[2]: how do I give an object 'application scope'?
Author: John Green (http://www.jguru.com/guru/viewbio.jsp?EID=1258450), Aug 17, 2005 I found setting app scope variable is most easily accomplished by writing a struts plug in. Its very easy, just create a new class that implements org.apache.struts.action.PlugIn and put as many of the following as you need in the init(...) method: actionServlet.getServletContext().setAttribute("key", value);
Then just add the following to your struts-config.xml file:
<plug-in className="path.to.class"></plug-in>Done! |
| Re[3]: how do I give an object 'application scope'?
Author: shital patil (http://www.jguru.com/guru/viewbio.jsp?EID=1287784), Mar 10, 2006 please tell me how to access it in action class |
| Re[4]: how do I give an object 'application scope'?
Author: Michael McLawhorn (http://www.jguru.com/guru/viewbio.jsp?EID=1288576), Mar 15, 2006 I think you're looking for this: getServlet().getServletContext().getAttribute( key ) |
| Re[5]: how do I give an object 'application scope'?
Author: stan stan (http://www.jguru.com/guru/viewbio.jsp?EID=1269133), May 5, 2007 Hi .. I have a small doubt in scopes of any web application(Session, Application , Request) 1. what is the best way to find out the memory occupied by each scope 2. i mean.. i just want to know that session memory has this much data.. and application memory.. has this much data 3. and difference of a same data in difference scopes ? Regards Stan |
| Re[6]: how do I give an object 'application scope'?
Author: Prabhakara Thunga (http://www.jguru.com/guru/viewbio.jsp?EID=1343560), Jul 28, 2007 memory requirements for app.scope/session scope/request scope depend on the design stratagy if am not wrong.. Common objects for all users/browsers can be put in app.scope where the same copy of data will be available for all users. users specific data during a transaction should be put in session scope (copy of data will be for that particular user only. a separate stack for that user will be maintained for the user. if things starting and ending in a page itself then request sope is enough. If by mistake, if you don't sort out the commn data for all users and everything if you put in session scope, separate copies will be maintained for each user eventhough the a portion of data required is common for all users. for ex. 450 KB (common) +50 KB (user specific) if another user enters into the application, again 450+50 kb needed if all data are session scoped otherwise 50 kb user spec. is enough if common data maintained in app. scope that is 450 kb. In simple, 500 kb for each user will be required if session scoped all the data. otherwise for first time 450 KB, thereon 50 kb enough for each user coming into the application.. |
In my Action subclass, rather than returning the results of mapping.findForward(...) I need to forward to a page
determined at runtime. What is the *proper* way to forward to xxx.jsp? Should I construct an ActionForward? (tried that
unsuccessfully).
Location: http://www.jguru.com/faq/view.jsp?EID=471961
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
You can create a new ActionForward dynamically:Comments and alternative answersString path = ... create context-relative path to new page ...
return (new ActionForward(path));The path you calculate must be context relative and start with a slash, exactly like the "path" attributes to your standard <forward> elements.
| How did i do that from within a servlet ??
Author: sulfura c (http://www.jguru.com/guru/viewbio.jsp?EID=823463), Apr 23, 2002 Iam calling the ActionForward from the servlet. I dont want to forward it from the Action class. My servlet inherits ActionServlet. Iam doing ActionMapping mapping = new mapping; mapping.findForward("test"); I have defined the uri test in my config file. Please reply asap. Thanks |
| Re: How did i do that from within a servlet ??
Author: Kevin Cowan (http://www.jguru.com/guru/viewbio.jsp?EID=1224506), Feb 1, 2005 If you don't want to use the ActionForward class you can use the response to redirect... response.sendRedirect(path); hope this helps. |
Does Struts work with a secure SSL connection?
Location: http://www.jguru.com/faq/view.jsp?EID=471962
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Yes. Once SSL is installed for your container, the Struts custom tags and Action Mappings will automatically insert the correct references so that all the page and image links operate in SSL mode.
How do I install SSL for my container?
Location: http://www.jguru.com/faq/view.jsp?EID=471963
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
See:
- installing the Sun Secure Socket extension
- keytool
- and the documentation for your container.
Here are some common configuration mistakes:
- When installing standard extensions, install them under $JAVAHOME\jre\lib\ext -- not under $JAVAHOME\lib\ext.
- If Struts links do not appear under SSL, see step 7 on the Secure Socket Extension page.
- You may need to add
-Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol
to the command line which loads your container.- If you have trouble importing your license key, be sure that your text file is saved in standard UNIX file format
Here's a bird's eye overview
1. Install JSSE
2. Create a new keystore for certificate requests, using template that ships with Java
cp cacerts MY_SERVER.keystore
3. Change the default password
keytool -storepasswd -storepass changeit -new MY_KEYSTORE_PASSWORD -keystore data.keystore
4. Generate a key, specifying an alias to use for this certificate
keytool -genkey -keyalg RSA -alias MY_SERVER_ALIAS -storepass MY_KEYSTORE_PASSWORD -keystore data.keystore
Answer the questions, using your machine's fully-qualified name (www.myserver.com) for "first and last name".
Use the same password for the key (using another password is not implemented).
5. Create a certificate request, based on the key created for the alias (step 2).
keytool -certreq -alias MY_SERVER_ALIAS -store pass MY_SERVER_PASSWORD -keystore MY_SERVER.keystore
Capture the output to a text file (MY_SERVER.crs), being sure to keep a backup copy in a safe place. This is your Certificate Request.
6. Generate a test certificate with Thawte, or another authority, to be sure everything works, and import the certificate returned (MY_SERVER.crt) for this alias.
keytool -import -alias MY_SERVER_ALAIS -storepass MY_SERVER_PASSWORD -keystore MY_SERVER.keystore -file MY_SERVER.crt
7. Repeat previous step to obtain a production certificate (unless you are self-signing for intranet use). When you import the production certificate, it will replace the test version.
How do I switch to SSL mode for logon, and then back again for the rest of the session?
Location: http://www.jguru.com/faq/view.jsp?EID=471964
Created: Aug 8, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThis is still harder than it should be, but here's the drill:
The bad news is that you need to hardcode the schema to switch from standard to SSL mode and back again. The good news is that you can mitigate the damage and do most of it it all in the Struts-config.
<forward name="standard" redirect="true"
path="http://data.wxxi.org/wxxi-gavel/register/logon.jsp"/>
<forward name="secure" redirect="true"
path="https://data.wxxi.org/wxxi-gavel/register/logon.jsp"/>which are called with code like this in the action
return mapping.findForward(secureMode ? "secure" : "standard");
where "secureMode" is tracked as a session attribute.
If they login or register in secure mode, you can end the process with a [[BIG LINK]] that routes them back to the http scheme.
Messy, but it gets you through the day.
I haven't had time to think about it, but it seems to me that we should be able to work this into the custom tags. Struts is very good about automagically converting the links when you switch schemes, so it seems to me we should be able to force the tags to one scheme or the other, when appropriate.
You could also calculate an absolute URL for this web app, based on things like request.getServerName(), request.getContextPath(), and so on. So, another way to do this would be to have an action that calculated the new absolute URL, wrapped it in a new ActionForward with the "redirect" property set, and return that to the controller servlet. It looks pretty much like what you quoted in the mail message.
NOTE: Because the controller servlet calls encodeRedirectURL() for you on redirections, sessions should survive across this transfer whether or not you are using cookies.
If you're running on ports other than the default (80 and 443), you will probably also want a configuration parameter to define what the corresponding SSL and non-SSL ports are.
| Doesn't work with non standard ports
Author: Frank Russo (http://www.jguru.com/guru/viewbio.jsp?EID=541303), Dec 19, 2001 I tried this approach, and it works great when using the standard ports as you mentioned. When I use other ports, the behavior is weird. When I switch back to http mode, it still tries building part of the page (mainly the images) from the ssl port. You mentioned using configuration parameters to define the non-ssl and ssl ports, but I'm not sure how to do this. Is it in the struts-config? What would be the syntax for doing that? Thanks... |
| How to send POST data to an absolute URL?
Author: Dave Chang (http://www.jguru.com/guru/viewbio.jsp?EID=947974), Jul 12, 2002 Hi, struts-config seems to restrict the path in <forward> to be relative URL if redirect="false" is used. If an absolute URL is used, an error will occur. Question: If I want to send POST data from a Form bean to an absolute URL via the ActionForward mechanism of struts, how do I do that? Thanks. Dave Chang |
Form validation errors in different frame? Possible? I'm writing my first Struts application and want to use one frame containing the input form and another frame to display the results.
If I use validation in the ActionForm (or populate ActionErrors in the Action object), I know I can use <html:errors/> to display errors in the input form (same frame).
But do I HAVE to display the errors in the same frame as the input form? Could I do a <html:errors/> in the results frame and get them to display there?
I can't use TARGET="resultsframe" because if an error occurs, the input form will be displayed in the results frame. I'd need to refresh the results frame from the input frame. But if the errors collection is only stored in the request, it'd be too late to retrieve the errors I think.
Is there a solution? Can I get to the errors collection from a different frame to the one containing the input form?
Thanks
Location: http://www.jguru.com/faq/view.jsp?EID=531007
Created: Oct 26, 2001
Author: Rob Breeds (http://www.jguru.com/guru/viewbio.jsp?EID=524998)
Question originally posed by Rob Breeds (http://www.jguru.com/guru/viewbio.jsp?EID=524998
The only thing I came up with was to do the input validation using JavaScript and dynamically set the TARGET if the validation succeeded.Comments and alternative answersI do have the error messages next to the corresponding input fields, but that only works if the TARGET is set to the same frame as the input. If the input validates OK, the response gets written to the input frame and not the results frame which is what I want.
If no errors I could ALWAYS return the input frame and check a session attribute to see if any results should be displayed, and if so change the results frame href so it loads the results from session.
I think the only way to do this is turn form validation off and have any error messages appear in the results frame. Not ideal, but it'll do for now!
Rob
| struts errors
Author: Frank Bowar (http://www.jguru.com/guru/viewbio.jsp?EID=1085481), May 16, 2003 I ran into the same issue. I turned the auto validation off in struts-config and then in my action did the following. ActionErrors errors = null; errors = unitAddForm.validate(mapping, request); if((errors != null) && (errors.size() > 0)) { session.setAttribute(Globals.ERROR_KEY, errors); . . forward to the appropriate page/frameset } I believe the problem occurs because the errors are placed into the request context, and when forwarding to a frameset, the request context is only valid for the frameset and none of the frames. It would be nice if struts would put the errors into the context based upon the scope of the associated action. |
| Re: struts errors
Author: daniel carter (http://www.jguru.com/guru/viewbio.jsp?EID=1137803), Jan 8, 2004 if you put the errors into the session, then they will appear on all forms as struts never clears them from the session, even when doing subsequent validations. Better to put them into the request i found. |
| Re[2]: struts errors
Author: prasu prasanna (http://www.jguru.com/guru/viewbio.jsp?EID=1307110), Jul 29, 2006 I too got the same problem which got resolved with this but the values in the form were flushing after the validation is been triggered.how can i solve this? |
| Re[3]: struts errors
Author: dan mueller (http://www.jguru.com/guru/viewbio.jsp?EID=1343469), Jul 26, 2007 hier die Lösung --> struts tag html:errors funktioniert nicht korrekt mit Framesets und findet die Fehler einfach nicht. daher muss man sie manuel in die Session speichern dazu reicht der Befehl: request.getSession(false).setAttribute(Globals.ERROR_KEY, errors); jetzt werden die Fehler gefunden aber leider nie aus der Session gelöscht selbset wenn die Fehler nicht mehr zutreffen. also dashalb die Lösung dazu: am anfang der action oder wo auch immer man die Fehler ermittelt: request.getSession(false).removeAttribute(Globals.ERROR_KEY); ---------- danke nochmals an die vorherigen Beiträge, ohne die wäre ich wohl noch an framesets und strutsActionerrors verzweifelt ^^ |
Page caching by overriding the getOutputStream() and getWriter() methods.
Reading this( see second answer)
I wonder how I can do this in
struts. I want to save the response
to my own stream so I can save it.
Which class do I extend in strus do
get this to work?
Location: http://www.jguru.com/faq/view.jsp?EID=531024
Created: Oct 26, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by raffe paffe (http://www.jguru.com/guru/viewbio.jsp?EID=28822
In your Action, you can just return null instead of an ActionForward
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); response.getWriter().print("Hello World"); return (null); };HTH -Ted
war file and directories structure for struts applications
Could someone give me a sample structure
of a simple application (2 or 3 jsp, 2 or 3
Action classes ...) including:
All the sample "build.xml" struts applications i've found don't indeed show how to write this war tag
Thanks,
Location: http://www.jguru.com/faq/view.jsp?EID=531027
Created: Oct 26, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Oops PRz (http://www.jguru.com/guru/viewbio.jsp?EID=527561
Comments and alternative answersIn open source arenas, it's become a popular practice to put the source below WEB-INF/src/java but that's a matter of preference. Most people tend to keep the build.xml under WEB-INF where it's easy to find.
The build.xml was written with that assumption, but you could change it to run from or get the source from anywhere you like.
Likewise, where you put (or name) the struts-config.xml " and the tld's can be configured in the web.xml, and is also a matter a preference.
The ApplicationResource.properties file has to be on the classpath, and since classes is always on the classpath putting it there makes it easy for the container to find.
Putting the JSPs below WEB-INF can provide an extra layer of security, but can also make it harder to reference stylesheets and the like.
HTH - Ted.
| Here's a simple directory structure that worked for me...
Author: John Munsch (http://www.jguru.com/guru/viewbio.jsp?EID=236478), Dec 16, 2002
base directory/ (this is the name of your war file)
JSP files
image files
HTML files
CSS files
any subdirectories containing additional JSP, HTML, images, and CSS
WEB-INF/
struts-config.xml
web.xml
TLD files for various tag libraries
lib/ (various .jar files for libraries you used)
classes/ (compiled .class files for your actions and action forms)
META-INF/ (this is part of the .war file)
MANIFEST.MF (the manifest file from the .war file)
Underneath the classes directory you would have compiled code for forms and actions. For example:
com/
johnmunsch/
strutstest/
actions/
LoginAction.class
SearchAction.class
forms/
LoginForm.class
SearchForm.class
|
Indexed Properties
Can we access members of an array like <form:select property="array[i]"> in a for loop... It works if I use constants but not expressions.. property="array[0]" is fine but not array[i] or array[<%=i>] for the property attribute of form:select. Any clues???
Comments and alternative answersThe property accessor syntax in Struts 1.0 supports only constants as array subscripts.
You might consider using some sort of runtime expression instead, to dynamically calculate the property to be retrieved. Assume that "i" is an integer variable, and you are inside a loop:
<form:select property='<%= "array[" + i + "]" %>'/>
In the Struts nightly build, indexed properties are supported directly, so that scriptlets like this are not needed
| error in submission
Author: Susan Cai (http://www.jguru.com/guru/viewbio.jsp?EID=1107860), Aug 11, 2003 When user click "submit", form reset will be called, and get a empty array. How to settle this problem? |
| Re: error in submission
Author: Ritu kumar (http://www.jguru.com/guru/viewbio.jsp?EID=314981), Sep 26, 2003 The problem I am having is that when I submit this form the form validation is not being called and the form fields are not being set |
Has anyone had luck using radio buttons?
Comments and alternative answersThe idea behind a radio button is that you have a String field that has one of a fixed set of values, and you want to render one radio button for each of them.
Let's assume that your bean property "gender" can have property values "Male" or "Female". You might display them like this:
<html:radio property="gender" value="Male">
<bean:message key="gender.male"/>
</html:radio>
<html:radio property="gender" value="Female">
<bean:message key="gender.female"/>
</html:radio>
A particular radio button will be selected if the value returned for this property matches the "value" attribute of that button's <html:radio> element.
In the example above, we're also looking up the actual text of the strings displayed on the HTML page in a message resources bundle, so that it is suitably internationalized.
[Craig McClanahan]
| "Grouping of radio buttons in struts framework"
Author: V.V.Narasimha Raju S.R.K. (http://www.jguru.com/guru/viewbio.jsp?EID=985024), Aug 19, 2002 Hi, This answer is informative but I want to know "Grouping of radio buttons in struts framework" for example: I want to display the user information with Status field ('Active' and 'InActive') for N number of users with radio buttons. How can i handle this situation. Right now I am unable to select the status of individual user, because it is taking all radio buttons as one control. thanks in advance. Raju. |
| Radio buttons are grouped by name.
Author: Artur de Sousa Rocha (http://www.jguru.com/guru/viewbio.jsp?EID=70489), Jan 10, 2003 Radio buttons are grouped by their names, so if you need separate radio button group for each user, they must have the same name for a single user, but different for different users. For example: "user" + userID. Thus, if you display users with IDs 3, 5, and 11, you will have: <input type="radio" name="user3" value="Active"> <input type="radio" name="user3" value="InActive"> <input type="radio" name="user5" value="Active"> <input type="radio" name="user5" value="InActive"> <input type="radio" name="user11" value="Active"> <input type="radio" name="user11" value="InActive">Unfortunately, as of Struts 1.0.2 you will have to handle this naming scheme "manually". |
| Re: Radio buttons are grouped by name.
Author: h p (http://www.jguru.com/guru/viewbio.jsp?EID=1094323), Jul 10, 2003 your answer was really helpfull but where do you give the name to the Radio Button. Suppose I am dynamically generating Radio Buttons so where in the <html:radio> should I specify the name of the button so that it each are identified. could you please write the above code using struts tags. Thank you very much in advance. |
| Re[2]: Radio buttons are grouped by name.
Author: Niraj Jain (http://www.jguru.com/guru/viewbio.jsp?EID=1262136), Sep 13, 2005 you want to set the radio button for each individual user and want to generate the user name dynamically. you can try i did it long time back <%int i=0;%> <% while(i!=10){%>
|
| grouping of html:radio buttons
Author: prashanth prashanth (http://www.jguru.com/guru/viewbio.jsp?EID=1299023), May 31, 2006 Its very nice to have the solution from u. and i got the exception that the fields active and inactive options doesn't have their respective getter/setter methods Is it needed to provide seperate getter/setter methods to each and every option note: using DynaActionForm |
| Re: grouping of html:radio buttons
Author: Varsha Gawari (http://www.jguru.com/guru/viewbio.jsp?EID=1301113), Jun 22, 2006 Instead of <html:radio property="fuspId" value='<bean:write name="verificationResultBean" property="fuspId"/>' /> Use expression scriplets, <html:radio property="verRequestId" value='<%=((VerificationSearchResult)verificationResultBean).getVerRequestId()%>' /> I did not get any exception for getter/serrer and got the correct value in Action.
- varsha.
|
ActionErrors,ActionError
about display the error message.
In the strut example, we should
new ActionError("error.password.mismatch")
"error.password.mismatch" define in the config file, if the property does not exit, then I can see nothing in the browser , I wanna to know whether I can display the property name even I does not define the property.
thanks
Location: http://www.jguru.com/faq/view.jsp?EID=531811
Created: Oct 27, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Yang Liu (http://www.jguru.com/guru/viewbio.jsp?EID=527494
Comments and alternative answersActually, there is an ActionServlet property that governs this. In your web.xml, include this:
<init-param> <param-name>null</param-name> <param-value>false</param-value> </init-param>with the other settings for your ActionServlet.
See the Struts Javadoc for other ActionServlet settings
HTH - Ted
| Struts 1.1 addition
Author: scott carlson (http://www.jguru.com/guru/viewbio.jsp?EID=428708), Jun 20, 2002 And in Struts 1.1, you can add a null="false" to your <message-resources > tag in your struts-config.xml . For example : <message-resources parameter="ApplicationResources" key="org.apache.struts.action.MESSAGE" null="false" /> |
Should we be chaining action servlets?
We're putting together a series of screens where we would say... logon (to main menu), list parties (to list result screen), then add party (to party detail screen), submit add (back to list result screen).
The notion of actions makes perfect sense to perform the business logic as a result of the various submits. However, we're currently questioning the use of actions in setting up the resultant page.
It appears that the actions themselves are logically dependant on the page (JSP) about to be rendered. As a side; surely this degrades application maintainability somewhat because it reduces the ease at which page flow can be altered, i.e simply by changing struts-config.xml
In the case above, our 'submit add' needs to perform a list again in preparation for the redisplay of the result screen.
Would we be correct in splitting this functionality between multiple action classes and chaining them. I've seen on the forum somewhere this idea refered to as 'the path to madness'!
Otherwise, in the case above, should we simply not return post-add to the list result screen, or is there (or should there be) in struts a mechanism for pre-processing a particular page, i.e. not leaving it all up to action objects? Have I missed a third/forth option that would decouple actions in some way?
Eagerly awaiting any feedback.
Steve Crowe.
Comments and alternative answersAn Action is intended as an adapter between the HTTP layer and the rest of your application. Generally, the rest of your application should be represented by business objects that have no dependancies on HTTP or Struts.
So, the business logic should not be *in* the Action, but something that the Action *calls*.
This makes it easier for Actions to handle more than one task. Since the logic is encapsulated elsewhere, each task is simpy a method call.
This also makes it easier for logic to be accessed by more than one Action (or from more than one application).
In this case, there could be a business method for the listResult page, that an Action could call before forwarding to that page.
If the correct prerequesites are still in the request, simply forwarding to another Action can also be a clean solution, so long as this is documented in the struts-config.
Where it gets iffy is when people start building dynamic query strings so they can call another Action. This is a retreat to Model 1, and smells like a kludge, since it implies that the business logic is not available outside the Action, where it could be cleanly called with a method (rather than a query string).
For an example of using business objects with Struts, see the early release of Artimus at http://husted.com/struts/resources.htm#new.
HTH -Ted
| Similar problem chaining actions
Author: Ken Bernstein (http://www.jguru.com/guru/viewbio.jsp?EID=1233524), Mar 18, 2005 Hi, I am running into a similar issue, except with a twist. I want to chain actions together, however the ActionForm gets reset between the 2 actions. So, I am setting some fields in the ActionForm in the first action, but by the time the second action (the one that implements the the "presentation logic" (populating dropdowns, setting defaults, etc.) gets invoked, all the fields in the form are gone. The only solution I can think of is to use request.setAttributes, however it seems wasteful to have to copy the attributes of the request into the form.
Any help would be appreciated,
Ken |
Struts post-1.0 and Tomcat 3.2.x
My post-1.0 version of Struts crashes on tomcat 3.2.x. What can I do about this?
Location: http://www.jguru.com/faq/view.jsp?EID=533533
Created: Oct 30, 2001
Author: Tom Klaasen (http://www.jguru.com/guru/viewbio.jsp?EID=532427)
Question originally posed by Tom Klaasen (http://www.jguru.com/guru/viewbio.jsp?EID=532427
Put xerces.jar in your TOMCAT_HOME/lib directory, and rename the files parser.jar and jaxp.jar in that same directory to zparser.jar and zjaxp.jar, respectively.
Multiple button support
How should multiple button support be handled in Struts? Each button gets submitted with different text, but in order to separate the view from the controller that text should not appear in the Action. I'm curious how others have dealt with this situation.
Location: http://www.jguru.com/faq/view.jsp?EID=543699
Created: Nov 9, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Erik Hatcher PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=405274
Comments and alternative answersWithout Javascript, I don't think there is another solution, since that is all the information that HTTP provides.
With Javascript, you can have the button set a hidden property on the form, and then key on that.
This example uses the property "forward", which could also be a property on the ActionForm.
<html:hidden property="forward" value="error"/>
<html:submit onclick="set('update');">UPDATE</html:submit>
<html:submit onclick="set('copy');">COPY</html:submit>
<html:cancel onclick="set('cancel');">CANCEL</html:cancel>
function set(target) { document.forms[0].forward.value=target; };A good trick here is to use a generic "routing" or "relay" action, so you don't have to hardcode some type of switch into the Action. It's just one line in the perform method:
return mapping.findForward(request.getParameter("forward"));This can be used any number of times in a Struts application, just by changing the form bean and the local forwards in its mapping.
<action path="/prospect/Submit" type="org.apache.scaffold.http.RelayAction" name="prospectForm" scope="request" validate="false"> <forward name="update" path="/do/prospect/Store"/> <forward name="cancel" path="/do/prospect/Current"/>HTH - Ted
| Additional alternatives
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042), Jan 8, 2002 There is now a new standard Action in the nightly build, that is useful for calling different Actions from the same form. See org.apache.struts.actions.LookupDispatchAction in the nightly build. Also in the contrib folder of the nightly build, there is a package called "scaffold" with another standard Action, org.apache.scaffold.http.FindForwardAction (my personal favorite). -Ted |
| Multiple submit buttons
Author: Greg Hess (http://www.jguru.com/guru/viewbio.jsp?EID=733724), Jan 24, 2002 Without Javascript I have been able to support multiple submit buttons on the same form by setting the property of the submit tag. <html:submit property="add" value="Add"/> <html:submit property="edit" value="Edit"/> Add these new properties to your ActionForm and in the Action class you can determine what button has been clicked by evaluating if(getAdd()== null). |
| Re: Multiple submit buttons
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042), Jan 24, 2002 Yes, but what you are really doing is keying on the value of the buttons label. This is fine for single language applications, but the other solutions would also work in an internationalized application. -Ted |
| Re[2]: Multiple submit buttons
Author: Greg Hess (http://www.jguru.com/guru/viewbio.jsp?EID=733724), Jan 25, 2002 Sorry, I didnt actually provide my internationalized code for simplicity. <html:submit property="add"> <bean:message key="page.form.add.label"/> </html:submit> In my code I am not using the value of the property rather just the (propery != null). Is this considered bad form or unreliable? I know this is not possible with all html inputs like text inputs as the value is always inserted into the http request. But with radio buttons, check boxes and the submit the key value pair will only be placed into the request if it is selected or clicked so I have found it nessessary at times to evaluate the (!= null). I am also restricted by the fact that I can't use JavaScript. Thanks for your prompt response. |
| Re[3]: Multiple submit buttons
Author: Emre Akbas (http://www.jguru.com/guru/viewbio.jsp?EID=1247327), Jun 6, 2005 Ted (the contributor of LookUpDispatchAction to Struts) may have forgotten to answer your question. Here is my experience: When you implement multiple buttons as you described above, you should reset the actionform on each submit if you want to stay at the same page. An example for "staying at the same page" is a form that couldn't pass validation. When a field of a submitted form is not valid, you should print all of the form, with its content of course, to the client who has just filled the form, and this unfortunately means previously-pressed-button information would persist. To prevent this, you can reset the actionform, but then the info filled-in by the client would be lost, which is of course an undesired situation. In short, using LookUpDispatchAction is the best way. |
| Re: Multiple submit buttons
Author: Richard Wan (http://www.jguru.com/guru/viewbio.jsp?EID=953512), Jul 17, 2002
A similar solution would be to implement the form bean as follows:
public void setAdd(String) {setForward("add");}
public void setEdit(String) {setForard("edit");}
and then as the final line in the Action:
return mapping.findForward(formBean.getForward());
|
| Re[2]: Multiple submit buttons
Author: shibani belsare (http://www.jguru.com/guru/viewbio.jsp?EID=1221086), Feb 3, 2005 could me send the sample code you have done here? |
| Non JavaScript Alternative?
Author: Pieter Hertogh (http://www.jguru.com/guru/viewbio.jsp?EID=782813), Mar 5, 2002 If you name your property tags different you can distinguish the button pressed form the http request. Just get the parameter named submit.* and retrieve the * to get the button pressed. Should work fine i think. <html:submit property="submit.update" value="Update document"> <html:submit property="submit.delete" value="Remove document"> |
| Re: Non JavaScript Alternative?
Author: Rod Madden (http://www.jguru.com/guru/viewbio.jsp?EID=1139442), Feb 16, 2004 Can you show me an example of what the ActionForm would look like for this ? |
| Don't forget about the property parameter.
Author: Artur de Sousa Rocha (http://www.jguru.com/guru/viewbio.jsp?EID=70489), Dec 20, 2002 The <html:submit> tag has a property parameter. You can "attach" each of the submit buttons to a different property. Then, after submitting only one of these properties will be non-null. You can use this information to find out the user's choice. |
| Re: Don't forget about the property parameter.
Author: TirumalaRao Chamalla (http://www.jguru.com/guru/viewbio.jsp?EID=1077243), Apr 17, 2003 The best way to do it is using LookUpDispatchAction class which is a new feature in the ver 1.1, U have to override the getKeyMethodMap()(may not be the xact syntax). put the key here in the HashMap and and method name as the value return the hashmap. in the <html:submit property="action"><bean:message key"somekey.mykey">, the key should b there in the Properties file, and in the StrutsConfig.xml file <action mapping> we have to set the <parameter='action'>... THis works fine I want to implement the same on click of an image instead of the submit button can any one help me in this regard |
| Re[2]: Don't forget about the property parameter.
Author: Narendhran Kannappan (http://www.jguru.com/guru/viewbio.jsp?EID=1112079), Sep 1, 2003 could u send me the code for this one... |
| Re: Don't forget about the property parameter.
Author: rajesh bonepalli (http://www.jguru.com/guru/viewbio.jsp?EID=1322381), Dec 15, 2006 with out using property attribute in the form we cant get the value given in the form to the struts config.xml <html:html> <body>
<html:form action="/srv.do" method="post">
Here in the above form we will take the Username,password and we will submit. If we click on Submit the control goes to strutsconfig.xml and it will see the formbean name and the control goes to that formbean and it will see for the same "property" given in the form.if it matches only it will do sets gets i meant it using Dyanavalidator form.
<Form-bean>
<form name="frm">
<action-mapping> |
| LookUpDispatchAction limitation ...
Author: prashant jani (http://www.jguru.com/guru/viewbio.jsp?EID=100991), Sep 17, 2003
Hi,
There are a few limitations. Consider the following:
in the jsp, the <html:form ...> needs an action form to be defined.
what if i dont have an action form for the action mapping.
this is more of struts limitation towards form submission.
-----------------struts-config.xml--------------
<!-- Test Action -->
<action path="/testLookupAction"
type="org.apache.struts.webapp.validator.AppLookupDispatchAction"
scope="request"
parameter="submit">
<forward name="success" path="/index.jsp"/>
</action>
This action does not have a form mapping.
The basic purpose of the action is to differentially fwd the request using the Action class methods.
i am assuming the parameter plays a role in getting the parameter just like the DispatchAction.
-------- jsp page ---------------------------------------
<form action="/validator/testLookupAction.do">
<html:submit property="submit">
<bean:message key="action.add"/>
</html:submit>
<html:submit property="submit">
<bean:message key="action.delete"/>
</html:submit>
<html:submit property="submit">
<bean:message key="action.edit"/>
</html:submit>
</form>
---------- .properties file --------------
action.add=executeAdd
action.delete=executeDelete
action.edit=executeEdit
---------------AppLookupDispatchAction.java--------------
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("action.add", "executeAdd");
map.put("action.delete", "executeDelete");
map.put("action.edit", "executeEdit");
System.out.println("getKeyMethodMap");
return map;
}
public ActionForward execute
-------
other business methods
public ActionForward executeAdd ....
....
=========
however when i run the following:
http://localhost:8080/validator/testLookupAction.do?submit=executeDelete
the execute method is called. the getKeyMethodMap is never executed ...
can u help me on this. i cannot figure where the problem is.
regards
Jani
|
| Re: LookUpDispatchAction limitation ...
Author: Tim Meredith (http://www.jguru.com/guru/viewbio.jsp?EID=1159135), Mar 31, 2004 You are overriding the execute() therefore the getKeyMethodMap() is not called to use your methods. Remove the execute() method from your action (AppLookupDispatchAction in this case) |
| Re[2]: LookUpDispatchAction limitation ...
Author: charles rad (http://www.jguru.com/guru/viewbio.jsp?EID=1242325), May 12, 2005 This is true. However, and I can't seem to get past this, when you simply click on the enter button , and specially if you have a text field with a value in it, then program doesn't know what to do. any thoughts? |
| Re[3]: LookUpDispatchAction limitation ...
Author: Chris Middlemiss (http://www.jguru.com/guru/viewbio.jsp?EID=1265629), Oct 3, 2005 Hi there, the problem I have to solve is that I have an arbitrary number of submit buttons to include on the one form. Our customer does not want to see any radio boxes etc, so we are limited to submit buttons. From what I have read here, I can see how to deal with a set number of buttons, but I'm having to include a table of information on my form, with the user able to select any one of the rows displayed (which will then result in some action taken on the underlying object for that row), by clicking the submit button next to that row. Now, I don't know how many rows will be displayed from one case to the next. How can I deal with this? Any help greatly appreciated Chris |
| Re[4]: LookUpDispatchAction limitation ...
Author: Scott Lohr (http://www.jguru.com/guru/viewbio.jsp?EID=1270016), Nov 2, 2005 Since it's been a while since your post you probably figured out a solution but I thought I'd suggest what I did to solve a similar problem. Basically for each dynamically generated row I encapsulated it with a form and a hidden field that uniquely identified it. That way when the submit button in that row was clicked it would identify which record the user wanted to act on. Here's a snippet of one of my pages that does this. Basically it allows removal of a record that has been added to a collection in the DTO. HTH scott
< table title="Contacts" >
< thead >
< tr >
< td > Name < /td >
< td > Email < /td >
< td > Role < /td >
< td > < /td >
< /tr >
< /thead >
< c:forEach items="${study.contacts}" var="contact" >
< html:form action="confirm" >
< tr >
< td >
< c:out value="${contact.first} ${contact.last}"/ >
< /td >
< td >
< a href=' < c:out value="mailto:${contact.emailId}@predicant.com"/ > ' >
< c:out value="${contact.emailId}@predicant.com"/ >
< /a >
< /td >
< td >
< c:out value="${contact.roleName}"/ >
< /td >
< td >
< input type="hidden" name="contactToRemove"
value=' < c:out value="${contact.emailId}"/ > '/ >
< html:cancel property="method" onclick="document.mainForm.submit()" >
< bean:message key="button.confirm.contact.remove"/ >
< /html:cancel >
< /td >
< /tr >
< /html:form >
< /c:forEach >
< /table >
|
Multiple form beans per Action class
Can I have multiple form beans per action class? If YES how would the struts config file look like?
Location: http://www.jguru.com/faq/view.jsp?EID=543700
Created: Nov 9, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Ranjiith Selvarjan (http://www.jguru.com/guru/viewbio.jsp?EID=421879
Comments and alternative answersNot as such. The Action.perform() method only takes a single form bean as a parameter.
You can nest beans. See the Bean Developers guide for details, and Struts-simple for an example.
Of course, you can always create and populate whatever other beans you need in the Action. Typically, the ActionForm is just used to get the data into the Action, and then it is transferred to more capable beans, with typed data.
HTH - Ted
| It is possible by extendig ActionServlet
Author: frank prumbaum (http://www.jguru.com/guru/viewbio.jsp?EID=578394), Dec 10, 2001 You can do so by extending ActionServlet to implement this new behavior. We have done this by overriding processActionForm to just get the name of the bean to fill from an input type=hidden name=serviceName parameter from the request. All what's left to be done is declaring these beans in the form-beans section of struts-config and providing a forward-mapping for the action. You can then link many forms with each different beans to one action-class Here our implementation of processActionForm which uses Beans of type serviceName+"Form" and names (what you put in form-tags) serviceName+"bean" <xmp> protected ActionForm processActionForm(ActionMapping mapping,
HttpServletRequest request) {
HttpSession session = request.getSession();
// Is there a form bean associated with this mapping?
String formBeanName = mapping.getAttribute();
if (formBeanName == null || formBeanName.equals("nullbean")) {
formBeanName = request.getParameter("serviceName")+"bean";
if(formBeanName==null) {
return null;
}
}
// Look up the existing form bean, if any
if (debug >= 1)
log(" Looking for ActionForm bean under attribute '" + formBeanName + "'");
ActionForm instance = null;
if ("request".equals(mapping.getScope())) {
instance = (ActionForm) request.getAttribute(formBeanName);
} else {
instance = (ActionForm) session.getAttribute(formBeanName);
}
// Bestimmung der erwarteten Formbeanklasse;
// wenn das mapping keinen Namen führt, dann nehme den Namen der Form
String name = mapping.getName();
if(name==null) {
name=formBeanName;
}
String className = null;
ActionFormBean formBean = findFormBean(name);
if (formBean != null)
className = formBean.getType();
else
return (null);
// Can we recycle the existing form bean instance?
if ((instance != null) &&
className.equals(instance.getClass().getName())) {
if (debug >= 1)
log(" Recycling existing ActionForm bean instance of class '"
+ className + "'");
return (instance);
}
// Create a new form bean if we need to
if (debug >= 1)
log(" Creating new ActionForm instance of class '"
+ className + "'");
try {
instance = null;
Class clazz = Class.forName(className);
instance = (ActionForm) clazz.newInstance();
} catch (Throwable t) {
log("Error creating ActionForm instance of class '" +
className + "'", t);
}
if (instance == null)
return (null);
// Store the newly created bean in the appropriate scope
if (debug >= 1)
log(" Storing instance under attribute '" + formBeanName + "' in scope '" + mapping.getScope() + "'");
if ("request".equals(mapping.getScope()))
request.setAttribute(formBeanName, instance);
else
session.setAttribute(formBeanName, instance);
return (instance);
}</xmp> |
| Re: It is possible by extendig ActionServlet
Author: Pawan Kumar Shrivastava (http://www.jguru.com/guru/viewbio.jsp?EID=1162795), Apr 14, 2004 I think with DispatchAction also we can do the same. In struts-config.xml we can have our Multiple Action Mappings which will point to same Action Class but will be having different Form Beans associated with it. And we can specify the function to call in parameter in struts-config.xml. So for every form bean argument in method of Action Class we can cast it to appropriate form beans. |
| Re[2]: It is possible by extendig ActionServlet
Author: Adam Strickland (http://www.jguru.com/guru/viewbio.jsp?EID=1162842), Apr 14, 2004 Pawan- Could you provide a sample struts-config.xml illustrating what you mean? Perhaps it's container-specific, but I'm running into a problem where, if the name attribute of the action tag for a given subclass of DispatchAction isn't supplied in the struts-config.xml, then the form parameter inside the method is null. This is causing a problem as I would like to use a variety of forms to be processed by the same DispatchAction subclass. In case it is container-specific, I'm using JBoss 3.2.1 with Tomcat 4.1.24 embedded.
a |
| problem in validation by client side javascript generated from validation.xml file in struts.
Author: hemali petare (http://www.jguru.com/guru/viewbio.jsp?EID=1177749), Jun 22, 2004 I have two forms on one jsp pages both forms are having two input fields and one submit button. I am not able to invoke respective javascript on submit event. although javascripts functions are avalilable on that page. it works for one form's validation. not for both. |
| Re: problem in validation by client side javascript generated from validation.xml file in struts.
Author: hans guberg (http://www.jguru.com/guru/viewbio.jsp?EID=1190189), Aug 3, 2004 Hi i have this exact same problem... has anyone got a solution to this? |
| Re[2]: problem in validation by client side javascript generated from validation.xml file in struts.
Author: ahmet mutlu (http://www.jguru.com/guru/viewbio.jsp?EID=1250927), Jun 29, 2005 struts generates , required javascript class for each form, however, with same name. if you have multiple forms, then you have multiple requred class,like: <script> function required () { ..... } </script> <script> function required () { ..... } </script> when validation is invoked, it goes insane. i handled validation manually for 2nd form. |
| Re[2]: It is possible by extendig ActionServlet
Author: Madhu Raj Soudathikar (http://www.jguru.com/guru/viewbio.jsp?EID=1235385), Mar 29, 2005 In the case of DispatchAction, We can have more than one form per action class but for a Single request/parameter in case of dispatchAction, there exists only one form bean. If i want to use more than one form beanfor each submit/ request, how should i go about it? |
| Re: It is possible by extendig ActionServlet
Author: Lennarth Anaya (http://www.jguru.com/guru/viewbio.jsp?EID=1189596), Jul 30, 2004 I'm trying to do some thing like your example. In my case, if current FormBean isn't in session scope, I must create the corresponding Transfer Objects in a nested hirearchy collection. I don't want to parse struts-config.xml. How do you implement your findFormBean() method ? |
| Re[2]: It is possible by extendig ActionServlet
Author: Lennarth Anaya (http://www.jguru.com/guru/viewbio.jsp?EID=1189596), Jul 30, 2004 I got it, I found the findFormBeanConfig() method provide by Struts ApplicationConfig. Thanks for bounch of answers... |
| Re[3]: It is possible by extendig ActionServlet
Author: Fahad Khan (http://www.jguru.com/guru/viewbio.jsp?EID=1226900), Feb 13, 2005 Would you kindly elaborate a little on how did you find ApplicationConfig useful in your particular situation? I'd appreciate if you describe the proceedure that made possible to use single action class for multiple forms. Thanks, Fahad. |
| Re[4]: It is possible by extendig ActionServlet and RequestProcessor
Author: Prashanth Veldhi (http://www.jguru.com/guru/viewbio.jsp?EID=1245874), May 26, 2005 Consider a example where you have one action class TestAction, two form beans TestForm and TestForm1 two JSP's test.jsp and test1.jsp. test1.jsp uses TestForm1 and test.jsp uses TestForm. Both the JSP's fire action to Single Action Class TestAction. The Action class has to get the appropriate form bean. Solution: As per the struts framework 1.1 you can do it by overriding ActionServlet and RequestProcessor class as follows
public class MyRequestProcessor extends RequestProcessor
{
protected ActionMapping processMapping(HttpServletRequest request, HttpServletResponse response, String path)
throws IOException
{
System.out.println("ProcessMapping of MyRequestProcessor called...");
ActionMapping mapping = (ActionMapping)moduleConfig.findActionConfig(path);
if(mapping != null)
{
request.setAttribute("org.apache.struts.action.mapping.instance", mapping);
System.out.println("Set The Form bean from the request...if available");
String myBean = request.getParameter("myBean")==null?"":request.getParameter("myBean");
System.out.println("Bean You Mentioned..." + myBean);
if(myBean != "")
{
System.out.println("Bean metioned earlier is..." + mapping.getName());
mapping.setName(myBean);
System.out.println("After setting the bean..." + mapping.getName());
}
return mapping;
}
ActionConfig configs[] = moduleConfig.findActionConfigs();
for(int i = 0; i < configs.length; i++)
if(configs[i].getUnknown())
{
mapping = (ActionMapping)configs[i];
request.setAttribute("org.apache.struts.action.mapping.instance", mapping);
return mapping;
}
response.sendError(400, getInternal().getMessage("processInvalid", path));
return null;
}
}
get the hidden parameter (myBean) value from the jsp page with the form bean value and set the particular form bean.
public class MyActionServlet extends ActionServlet
{
public void init()
throws ServletException
{
System.out.println("Init Method Called....");
initInternal();
initOther();
initServlet();
getServletContext().setAttribute("org.apache.struts.action.ACTION_SERVLET", this);
ModuleConfig moduleConfig = initModuleConfig("", config);
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
//moduleConfig.freeze();
for(Enumeration names = getServletConfig().getInitParameterNames(); names.hasMoreElements();)
{
String name = (String)names.nextElement();
if(name.startsWith("config/"))
{
String prefix = name.substring(6);
moduleConfig = initModuleConfig(prefix, getServletConfig().getInitParameter(name));
initModuleMessageResources(moduleConfig);
initModuleDataSources(moduleConfig);
initModulePlugIns(moduleConfig);
//moduleConfig.freeze();
}
}
destroyConfigDigester();
}
}
Look at the lines commented...this allows to create the Form bean. Jsp pages test1.jsp <%@ taglib uri="struts/html" prefix="html"%> <html> <html:form action="\test.do" name="testForm1" type="com.cognizant.form.TestForm1">
the hidden form field myBean takes the appropriate form bean name. In this case it is testForm1. test.jsp has testForm as hidden field value... Make changes To Struts-config file with <controller processorClass="com.cognizant.processor.MyRequestProcessor" />Your WEB.XML should look like this
<servlet-name>action</servlet-name>
<servlet-class>com.cognizant.servlet.MyActionServlet</servlet-class>
|
| Re[5]: It is possible by extendig ActionServlet and RequestProcessor
Author: william edwards (http://www.jguru.com/guru/viewbio.jsp?EID=1245886), May 26, 2005 Just one question, what do I write in the //moduleConfig.freeze(); bit - what should it look like? |
| Re[5]: It is possible by extendig ActionServlet and RequestProcessor
Author: william edwards (http://www.jguru.com/guru/viewbio.jsp?EID=1245886), May 26, 2005 The "MyRequestProcessor" also clashes with the tiles request processor in my struts-config. An error occurs when loading up because tiles says "MyRequestProcessor" is incopatable with its TilesRequestProcessor. |
| Re[6]: It is possible by extendig ActionServlet and RequestProcessor
Author: william edwards (http://www.jguru.com/guru/viewbio.jsp?EID=1245886), May 26, 2005 I found the solution to this problem. The "MyRequestProcessor" must subclass the TilesRequestProcessor instead of the normal RequestProcessor. |
| Re[6]: It is possible by extendig ActionServlet and RequestProcessor
Author: Prashanth Veldhi (http://www.jguru.com/guru/viewbio.jsp?EID=1245874), May 26, 2005 Nothing required...for that bit. Remove the commented code. For tilesrequestprocessor... MyRequestProcessor has to extend the related tiles RequestProcessor class and override the appropriate method. At present MyRequestProcessor extends org.apache.struts.action.RequestProcessor Reason: When you look at ActionServlet init() method, it calls moduleConfig.freeze() method when you call mapping.setName("formbean")in RequestProcessor's processMapping method ,it inturn calls freeze() method of ApplicationConfig class. There is a boolean variable called "configured" in the above class which is initialized as false. The variable is set to true when freeze method is called. So, when ever you call mapping.setName() the method checks for "configure" variable and if it is true, the method throws IllegalStateException and does not allow to set our form bean. |
| Re[5]: It is possible by extendig ActionServlet and RequestProcessor
Author: atul jain (http://www.jguru.com/guru/viewbio.jsp?EID=1255962), Aug 4, 2005 it is not possible extending actionservlet but possible extending requestprosser class |
| Re[5]: It is possible by extendig ActionServlet and RequestProcessor
Author: geetanjali Patil (http://www.jguru.com/guru/viewbio.jsp?EID=1277798), Jan 6, 2006 But what if I have one jsp with one Action class, which is changing two ActionForm classes. e.g. I have one jsp file test.jsp it contains input box for myName, myAddress and companyName, companyAddress. if I I have 2 form classes MyInformationForm and CompanyInformationForm. myName, myAddress properties are in MyInformationForm and companyName, companyAddress properties are in CompanyInformationForm. But there is one action class TestAction. |
Dynamic Form Elements
I posted this earlier but I received no comments on specific current solutions that will address this problem. I was also wondering if the nightly build has the following ability within it.
Let me give an idea of what I am trying to accomplish and then see if you can feedback.
Using struts (obviously) I am creating a reusable contact form. It is configured through an xml-config file that defines where the contact form goes and the smtp server it is to use, etc.. I want to set it up so that it does not have to be recompiled upon alternate use. This is one part of a set of components that make it easy for web designers to add functionality to websites they are building using the struts framework (whether they know it or not). i.e. most web designers to not have ide for compiling java classes. So, with those design goals in mind let me share with you my issue.
The contact form by default captures the Name, Address, City, State, Phone Number, and any other basic contact form info needed. It has an ActionForm bean that captures the input of these predefined items and the data is then passed on to the Action and sent as an email to the recipient. My hangup is... I need to allow the flexibility of adding form elements to the form that are not defined in the ActionForm bean. I would also need to be able to pass the values back to the form in the event that a validation error occurs with the form. With the model the way it is I would have to specifically define the setters and getters in the ActionForm so that the Action could retrive the values of each form element and use them or route them back to the input form for errors or to another Action.
Is there a way to have a generic getter/setter that can capture any non defined data? For example say a company cleans linen and they want to add a form element that asks for the type of detergent the contactee prefers. The added form element is called "preferredDetergent" yet it is not specifically defined in my ActionForm bean. First, how would I avoid getting an error that says preferredDetergent is not defined in xxxForm? Next, how would I then capture that value in the ActionForm for use in error checking and/or usage in the Action class?
Brandon GoodinComments and alternative answersThe ActionForms extend the html:form tags so that they can be populated, and repopulated, from the request.
The ActionForm properties and the tags are tightly coupled, and neither are designed to be used dynamically.
Of course, not every property has to be populated. So there could be the old trick of adding several "UserDefined" properties to form. In the JSP, the properties might be labled user1, user2, et cetera, but the external user labels could be anything at all.
Using the validator form, error checking can be performed by updating the validate.xml and Application resources and restarting the application.
In the Action itself, you would need to add some type of handler to check if the user defined fields were not null. To label them in your email message, you could do some type of "reverse lookup" on the application resources, to get the field labels from the validation messages.
HTH - Ted
| ActionForm to handle dynamically generated fields
Author: Chan Mike (http://www.jguru.com/guru/viewbio.jsp?EID=1032363), Nov 30, 2002 I'm working on an application which need to render html objects dynamic The objects to render will depend on data read from database table prior to construction (by action method) of jsp form. In my jsp form, each row from db table will rendered as a table row. However there is no way to determine the no of rows in advance. Also, in each row, there will be a status colomn which in turn decide whether a checkbox will be rendered in each row. Thus, I cannot pre-assign fields in the ActionForm as what is rendered by jsp is completely unpredictable. Right now, i am completating on creating a 'collection' variable inside the jsp. This variable will have to updated whenever any of checkboxes is selected. On the ActionForm, i will predefined the same collection variable.Would welcome any1 with experience in this area. |
| Re: ActionForm to handle dynamically generated fields
Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Dec 5, 2002 I am in a similar situation. Were you able to find a solution to this dilemma? |
| Re[2]: ActionForm to handle dynamically generated fields
Author: Oswin Ondarza (http://www.jguru.com/guru/viewbio.jsp?EID=1057273), Feb 16, 2003 in struts 1.1 you can use DynaActionForm. please refer to this link: http://www.onjava.com/pub/a/onjava/2002/10/30/jakarta.html?page=last |
| Re[3]: ActionForm to handle dynamically generated fields
Author: Glen Whitbeck (http://www.jguru.com/guru/viewbio.jsp?EID=1060827), Feb 26, 2003 The above referenced link discusses the use of DynaActionForm. While the DynaActionForm appears to help by allowing attributes to be defined in an xml file (instead of on a Java object - forcing an application restart after any change), it still seems to fall short by forcing three duplicate definitions (once on the page, once in the xml file, and once in the (String)form.get("mySpecialHardCodedPropertyName") code on the ultimate business/service object). Which, by the way, still appears to cause an application restart since the ulimate business/service object will have to change what it uses in the __form.get("xxx") code. |
| Re[3]: ActionForm to handle dynamically generated fields
Author: Balaji Chakilam (http://www.jguru.com/guru/viewbio.jsp?EID=1237045), May 11, 2005 Cant we do the same with out using the DynaActionForms... i am in urgent need. please help me out. |
| Re: ActionForm to handle dynamically generated fields
Author: ashu tosh (http://www.jguru.com/guru/viewbio.jsp?EID=1157815), Mar 26, 2004 Chan I am in the same difficult situation need help. How was the problem solved. How did you capture the generic field values, when there is no corresponding field in the Action Form. If any one knows the solution please do reply As soon as possible |
| Not certain why this is difficult
Author: S Edwards (http://www.jguru.com/guru/viewbio.jsp?EID=1210822), Nov 12, 2004 I have managed to solve this problem a couple of times, starting in Struts 1.0.2. One mechanism for "open-ended" forms is to simply have the bean properties defined that are always going to be present, and then have Lists, or Maps, for the properties that might be variable. You will not be able to rely on the "input" attribute of the struts-config file for repopulating your form unless you point your input at a Struts Action that will repopulate the form select lists etc. Another mechanism to handle is to have your mapped backed form, but pass in meta data that defines which properties on the form are going to be rendered in as which type of control. The JSP can then have an iterator and test in it to determine for this element of the meta data, how does it need to be rendered. The Action would need to take care of supplying the appropriate extra data (select lists) and repopulating that on a validation error (you might consider just doing the validation inside the action rather than leaving it up to the Struts Servlet). |
| Re: Not certain why this is difficult
Author: nith ps (http://www.jguru.com/guru/viewbio.jsp?EID=1211897), Nov 29, 2004 can U give sample code for this.. |
How can I use the "options" tag with a collection of options stored
in my ActionForm bean?
Location: http://www.jguru.com/faq/view.jsp?EID=549097
Created: Nov 16, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by kriss j (http://www.jguru.com/guru/viewbio.jsp?EID=531542
Comments and alternative answersThe properties for options are very confusing, and there's talk on DEV of an alternate tag, optimized to use something like the LabelValue beans.
Here's how to use the current options tag when the LabelValue collection (from the Example) has been stored as a property on the ActionForm. If you want to provide the collection through an ActionForm method, you need to define a scripting variable first.
<bean:define id="myOptions" name="donorForm" property="myOptions" type="java.util.Collection"/>Then
<html:select property="image"> <html:options collection="myOptions" property="value" labelProperty="label"/> </html:select>If you wanted to build the list from a static method in your business layer, a simple one could look like this:
public static String getMyOptions(int image) { String text = null; switch (image) { case -5: text = "Photograph item"; break; case -4: text = "Clip from Website"; break; case -3: text = "Expect by email"; break; case -2: text = "Expect by mail"; break; case -1: text = "Do not use"; break; case 0: text = "No"; break; case 1: text = "Yes"; break; case 2: text = "Use icon"; break; } return text; } public static Collection getMyOptionss() { Collection list = (Collection) new ArrayList(); for (int i=-5; i<2; i++) { list.add(new LabelValueBean( getMyOptions(i), String.valueOf(i) )); } return list; }Then in the ActionForm, a wrapper method can be used:
public Collection getMyOptions() { return app.StaticClass.getMyOptions(); }HTH - Ted
| Typo?
Author: Chad Woolley (http://www.jguru.com/guru/viewbio.jsp?EID=759258), Mar 1, 2002 Is the following method supposed to be named ending with two letter "s's":
If so, shouldn't the following code be changed to use the "two-s" version:
Or maybe it's a typo, and you are intending to override the method? If this is the case, maybe you could give them different names to make the example a little clearer?
Thanks, |
| how would the setter in the form look like for a Collection attribute ?
Author: Cezar Balaita (http://www.jguru.com/guru/viewbio.jsp?EID=797949), Mar 15, 2002 I would assume it should be : public void setMyOptions(Collection coll) { this.coll = coll; }
If the validation of the form on submission fails, will this method be called automatically ? If yes, what values will it look for ?
Cezar |
| property="image" ?
Author: Dan Desch (http://www.jguru.com/guru/viewbio.jsp?EID=827173), May 31, 2002 Mr. Husted, in your example, you define a struts select tag thus: <html:select property="image"> What does the property="image" attribute setting do in this context? Also, can I infer from this example that your ActionForm bean is called "donorForm"? |
| Thank you
Author: Damon Torgerson (http://www.jguru.com/guru/viewbio.jsp?EID=912164), Jun 24, 2002 This example saved my bacon. Thanks!!!! |
| selected
Author: Paul Beccio (http://www.jguru.com/guru/viewbio.jsp?EID=983565), Sep 16, 2002 To add on that example - can you nest a logic:match or some other tag to use the selected option? Thanks! |
| Re: selected
Author: mickey barton (http://www.jguru.com/guru/viewbio.jsp?EID=1114085), Sep 9, 2003 How do you set multiple options as selected using "<html:select>" "<html:options />" "</html:select>" I've have it set up so that I can select multiple items from the list but I have not been able to find any documentation on how to preselect some of the items when I first display the page. Any idea on how to do this? Thanks in advance. Mickey |
| Re[2]: selected
Author: Priya Selva (http://www.jguru.com/guru/viewbio.jsp?EID=1109586), Oct 30, 2003 I have the similar problem described by Mickey. I have to pre-select multiple values in the <html:select> tag which is retrieved from the database. Can anyone help me please Thanks Selva |
| Here's the real deal:
Author: Mike O'Connor (http://www.jguru.com/guru/viewbio.jsp?EID=1037209), Dec 12, 2002 What a confusing answer! :o) If you've stumbled across this page hoping for an answer to the question posed - here it is:
Basics:
Here's what to do: here's an example of such a bean class:
=========================================================== OK, so now you have the bean class. Now you make the Collection of beans.. In the ClientForm class, for example, you could make the following static ArrayList of HtmlSelectOption beans:
private static final ArrayList SEX_LIST; Next, in the ClientForm class, you need to make a getter method for a Collection property that allows access to the SEX_LIST you just created: public Collection getSexList() { return (Collection) SEX_LIST; } OK so far - we're finished with the ClientForm class. Now in the JSP you need to declare the "sexList" property of the form class (which itself is a bean), with the following struts tag: <bean:define id='sexList' property='sexList' name='clientForm'/> Then finally there's the options tag itself:
<html:select size="10" property="sex">
A little explanation to finish off: Hopefully this clarifies things! I spent too long having to figure this out today myself..
Mike O'Connor |
| Re: Here's the real deal:
Author: Muralidhar Reddy (http://www.jguru.com/guru/viewbio.jsp?EID=1053754), Feb 25, 2003 Hi Mike, I've defined everything as u said and i have a loginForm(ClientForm) as in ur case.and thats defined in the struts-config.xml .and i displayed in the jsp as u said . <bean:define id='userList' property='myCollection' name='loginForm'/> and the options are decleared as follows <html:select size="10" property="loginName"> <html:options collection="myCollection" labelProperty="displayName" property="id"/> </html:select> . But on displaying in the browser i'm getting following exception Error Message: Cannot find bean loginForm in scope null Error Code: 500 Target Servlet: null Error Stack: javax.servlet.jsp.JspException: Cannot find bean loginForm in scope null. Can u tell where have i commited mistake .Your help is very much appreciated |
| Re[2]: Here's the real deal:
Author: Michael Glenn (http://www.jguru.com/guru/viewbio.jsp?EID=1060667), Feb 25, 2003 Muralidhar, I ran into the same error. It means that it can't find the bean logicForm, which probably means that your bean definition tag (bean:define) isn't within the associated form bean (form:bean) tag. At least, that's the problem I experienced. It's also possible that loginForm isn't properly defined in struts-config.xml. |
| Re[2]: Here's the real deal:
Author: Bill L (http://www.jguru.com/guru/viewbio.jsp?EID=1189464), Jul 29, 2004 I moved the bean tag and it worked for me. <html:form action="/clientSubmit" focus="user"> <bean:define id='sexList' name='clientForm' property='sexList'/> .. .. |
| Re: Here's the real deal:
Author: jyoti verma (http://www.jguru.com/guru/viewbio.jsp?EID=1085285), May 15, 2003 Mike, I did exactly what you said but I get an exception when I try to run my program saying: No getter method for property sexList of bean ClientForm Any suggestions? |
| Re[2]: Here's the real deal:
Author: Adam Gresh (http://www.jguru.com/guru/viewbio.jsp?EID=1061463), Jun 5, 2003 Jyoti, I had the same problem at first, but figured it out by creating a form bean first, then creating the collection bean. This showed me that the problem wasn't in the options tag, but something wrong with the way I was creating the bean. After some debugging it seems that I named the property incorrectly...? I'm actually not sure what I did exactly but in the end I wound up with code that looked like...
<bean:define id="singleSelectOptionsBean"
name="altControlsForm"
property="testSelectSingleOptions"/>
<html:select property="testSelectSingle"
fieldeditflag="editTestSelectSingle">
<html:options
collection="singleSelectOptionsBean"
property="key"
labelProperty="value"/>
</html:altselect>
...where altControlsForm is my action form and the method getTestSelectSingleOptions in AltControlsForm returns a Collection (an ArrayList actually).
HTH |
| Re: Here's the real deal:
Author: h p (http://www.jguru.com/guru/viewbio.jsp?EID=1094323), Jul 7, 2003 Hi I have a problem which is similar to the one you exaplained. I have a parent JSP in which I am getting a vector of questions dynamically, depending on the database results. I am iterating over the questions vector and finding the answertype of the question from the database and depending on the answertype of the question I am including the appropriate JSP(like select.jsp,radio.jsp etc..) here is the code snippet for the select.jsp | ||
<html:select name="ans" property="aSelect"> <% for (int j = 0, jSize = optns.size(); j < jSize; j++) { opt = (Option) optns.elementAt(j); out.println(" the options are :"+opt); %> <html:option value='<%=opt.getOptionNumber()%>'> <%=opt.getOptionText()%> </html:option> <% } %> </html:select> | ||
Can We Avoid JSP's in Struts FrameWork Hi,
Can We use Servlets to Paint Screen instead of JSP's in Struts Framework, if Yes What are its Disadvantages,Modifications needed etc...
The response object is passed to the Action perform method. You can use this to write your own response to the client, in the usual way. The standard Struts "reload" action does this to paint "OK" to screen after reloading the mappings.
For fancier pages, the best thing would be to have your servlet answer to it's own URI pattern. The Struts Action could then forward to that, the same as it does with JSPs.
Your serlvet can then look in the request context for the ActionForm, or whatever other objects you will use, and render the response from that. If your servlet just does what the HTML tag extensions do, then the rest of the framework will be none the wiser. And all they really do is populate the HTML control using the properties of an ActionForm found in the request context.
The other resources used by the tag extensions, like the mappings and messages, are available in application scope, so your servlet could use those too, if needed.
On an incoming request, the ActionServlet sets the values on the ActionForm bean via reflection. It doesn't now or care how the values got into the HTTP request. It's just looking for name=value pairs in the HTTP request that match the property names on the designated ActionForm.
The tag extensions know to look for the ActionForm in the request context, or instantiate one if it's missing. The latter part is so any default values can be given to the HTML controls. The tags also know how to look into the mappings to find out which ActionForm goes with which Action, but that's added value. You can always code that part by hand (and at one point, we did).
But so long as the names of the HTML controls match the ActionForm names, it doesn't matter who writes the HTML. HTTP is the great equalizer.
The JSPs are not tightly coupled with the framework, and anything they do could be done by another servlet. It is helpful, though, if your serlvet answers to its own URI pattern, as the JSP service does. Architecturally, this then makes it a drop-in replacement for JSPs.
I understand that there is a renewed interest on the Jakarta Velocity list about using their servlets with Struts. The strategies they use would probably work for you too.
HTH -Ted
Browsers reload button and url writing
Hello,
here is my problem :
JSP1 -> ActionClass1 -> ActionClass2 ->JSP2
When I'm on the JSP2, the url is that of the ActionClass1, so when I hit the reload button, the ActionClass1 is reloaded. (and I would like the ActionClass2 to be reloaded).
How can I do ?
Location: http://www.jguru.com/faq/view.jsp?EID=705837
Created: Dec 31, 2001
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by jn dl (http://www.jguru.com/guru/viewbio.jsp?EID=466056
The reload button, by definition, is suppose to resubmit the last request. In this case, you would not like the last request to be resubmitted and reprocessed the same way. You would like ActionClass1 to skip ahead and forward the request to ActionClass2.Comments and alternative answersA good strategy to tell if a request has already been submitted is to use "tokens". Struts supports this directly with various *token methods in the Action class. To implement this, you would go back to "ActionClass0" that lead to JSP1. In this Action, put
saveToken(request) ;Then in ActionClass1 put a call to
isTokenValid(request)If the token is not valid, you would want to forward to ActionClass2If it is valid, you would want to finish the usual processing in ActionClass1 and call
resetToken(request);to signal that the token has been used.-Ted.
| Auto-refresh in IE 5.5
Author: Nils Svensen (http://www.jguru.com/guru/viewbio.jsp?EID=796595), Mar 14, 2002
Is it possible to avoid the alert "The page cannot be refreshed without resending the information. Click retry..." in IE when using automatic periodic refresh and struts?
I am using the token mechanism to check if the page is refreshed, and do not perform the action (check isTokenValid in the action class) if it is a refresh.
JSP1->ActionClass1->JSP1
The first time the JSP is loaded, the action in ActionClass1 is performed and the JSP page is again loaded. When hitting the refresh button after this, though, the alert box appears (beacuse of the form values). I do not want this to happen, because I want a possibility to automatically refresh the page periodically (also after the action has been performed once). Is this possible? |
Submitting forms as a collection Using the <logic:iterate> tag i'de like to format several rows of recurring data for a user to change or add some values.
When the data is submitted back to the Action routine I see how it can arrive as an Action form.
Is there a way to submit the results as a collection of forms instead?
Thanks,
Mitch
Location: http://www.jguru.com/faq/view.jsp?EID=710844
Created: Jan 6, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Mitch Dresdner (http://www.jguru.com/guru/viewbio.jsp?EID=390316
Comments and alternative answersHTML browsers can only submit results pursuant to the HTTP protocol. So everything comes in a hashtable of Strings.
There is a nice nesting pacakge for Struts that might help you organize the collections so that they can be submit back as Strings and put back into your collection
See Nested Struts Extension for details.
HTH -Ted.
| Any plans to add this to Struts?
Author: Markus Neifer (http://www.jguru.com/guru/viewbio.jsp?EID=592820), Jan 8, 2002 This would be very useful to handle the display of a shopping card in a shop application. Currently i have no idea how to generate the name for the input field (quantity) in each row. Markus |
| Re: Any plans to add this to Struts?
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042), Jan 8, 2002 Since Struts is component-based, adding another taglib like this is an expected part of the development process. So, if you put it in your /web-inf/lib folder, bingo, it's part of Struts ;-) Meanwhile, the author has offered to donate the Nested Taglib to the Apache Software Foundation, and it is likely that it will be accepted into the Struts subproject. There is currently other development going on in the CVS right now which might affect this package, and so it has not been proposed to the nightly build quite yet. -Ted |
| Re[2]: Any plans to add this to Struts?
Author: Alex Lindgren (http://www.jguru.com/guru/viewbio.jsp?EID=293396), Aug 3, 2002 I've noticed that this is now in the 1.1 beta. http://jakarta.apache.org/struts/userGuide/dev_nested.html |
| One solution (for struts 1.1 beta?)
Author: Richard Wan (http://www.jguru.com/guru/viewbio.jsp?EID=953512), Jul 17, 2002 I was putting together a toy "shopping cart" app and ran into the "user updates a collection" problem and came up with the following solution:
on the form bean:
public QuoteFormLineItem[] getLineItems() {...}
public QuoteFormLineItem getLineItem(int index) {...}
on a the line item: int getQuantity() and setQuantity(int q)
on the jsp:
<logic:iterate id="lineItem" property="lineItems" name="quoteFormBean">
<tr>
<td>
<html:text name="lineItem" property="quantity" indexed="true"/>
</td>
<td>other stuff...</td>
</tr>
</logic:iterate>
the main drawback was that the id for the iterate tag had to match the name of the indexed getter on my form bean. I was under the impression that the id used in a .jsp page could be considered flexible and independent of the applicaiton code. |
| Re: One solution (for struts 1.1 beta?)
Author: Placid Sea (http://www.jguru.com/guru/viewbio.jsp?EID=1139814), Feb 16, 2004 I m still confused. Cud u plz explain how exactly this piece of code works? and "QuoteFormLineItem" is what? I wud appreciate if u elaborate more. |
| Re[2]: One solution (for struts 1.1 beta?)
Author: Ron Rossier (http://www.jguru.com/guru/viewbio.jsp?EID=1176099), Jun 3, 2004 I think I can help ... The example does work, once u understand that u have to create another bean class called QuoteFormLineItem public class QuoteFormLineItem implements Serializable { //Declarations private int quantity; public QuoteFormLineItem () { } //get/set public int getQuantity() { return quantity; } public void setQuantity(intquantity) { this.quantity= quantity; } |
| Re[3]: One solution (for struts 1.1 beta?)
Author: vs y (http://www.jguru.com/guru/viewbio.jsp?EID=1176496), Jun 5, 2004 In my Action class ,I added multiple form beans to collection and had set that collection on a method on the same form bean. quoteFormlineItems is an ArrayList
|
| Re[4]: One solution (for struts 1.1 beta?)
Author: Ashish Dave (http://www.jguru.com/guru/viewbio.jsp?EID=1191917), Aug 10, 2004 if possible send me code on nesting in struts... |
| Re[4]: One solution (for struts 1.1 beta?)
Author: Ed Coughlin (http://www.jguru.com/guru/viewbio.jsp?EID=1252163), Jul 6, 2005 Hi, I'd appreciate obtaining the example source as well. It is mostly there but I think i might be missing something. Thanks, Ed |
| Re[4]: One solution (for struts 1.1 beta?)
Author: Radhika Abhyankar (http://www.jguru.com/guru/viewbio.jsp?EID=1174546), Oct 22, 2006 Hi, Did you get this problem resolved? If so, please tell me the solution. I am facing the same issue on my action also. I am using logic:iterate on a collection which is an attribute of my form bean. When I populate the form bean's collection, it gets displayed properly. But, when I try to retrieve it back in my action, I get a null for the collection. Please help. Thanks |
| Re[5]: One solution (for struts 1.1 beta?)
Author: Ram weisz (http://www.jguru.com/guru/viewbio.jsp?EID=1319777), Nov 17, 2006 Hey one thing to remember. once the page is displayed using the form bean the request object dies. now any action on the page generates a new request object and all data from that page will be passed in request as strings and not as a collection object. if this is exaclty what you are trying to do then it is obviously not possible. send me your code if you need further help. |
| Re[5]: One solution (for struts 1.1 beta?)
Author: Ram weisz (http://www.jguru.com/guru/viewbio.jsp?EID=1319777), Nov 18, 2006 Its true the collection will always be null.This is because once the page loads the request object in which the form bean was stored dies. On the next action a new request object is generated which will have form data and hidden values if any in the form of strings (Note:only as strings). hence the collection you are trying to retrieve in action class is null. let me know if you have any queries.
|
| Re[3]: One solution (for struts 1.1 beta?)
Author: jagan mohan (http://www.jguru.com/guru/viewbio.jsp?EID=1271872), Nov 16, 2005 Hello, Can I also have the full sample code by email, please Thanks in advance Swami Ganesan jagan_peddada@yahoo.com |
| Re: One solution (for struts 1.1 beta?)
Author: Joe Nelson (http://www.jguru.com/guru/viewbio.jsp?EID=1207151), Oct 25, 2004 How would this be written if I'm using DynaActionForms? |
| Re[2]: One solution (for struts 1.1 beta?)
Author: swami ganesan (http://www.jguru.com/guru/viewbio.jsp?EID=1241602), Apr 28, 2005 Hello, Can I also have the full sample code by email, please Thanks in advance Swami Ganesan g_swaminathan@hotmail.com |
| Re: One solution (for struts 1.1 beta?)
Author: Kelly Ann Alvares (http://www.jguru.com/guru/viewbio.jsp?EID=1247397), Jun 6, 2005 Hi, I'm still using struts 1.0 (and can't upgrade at this moment) is there a way to implement your solution with struts 1.0 ? thanks, Kelly. |
| Re: One solution (for struts 1.1 beta?)
Author: ravi kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1326039), Jan 23, 2007 Hi, even i am facing the same problem.. can u please send me the complete code.. rdshiva4@yahoo.co.in, Thank you.. |
| Re[2]: One solution (for struts 1.1 beta?)
Author: Kostya Vish (http://www.jguru.com/guru/viewbio.jsp?EID=1338558), May 30, 2007 Hi, could anyone please provide me with a copy of the sample code or explane how to send collection from jsp to Action class. my email : kvishnev@gmail.com , Thanks |
| Re[3]: One solution (for struts 1.1 beta?)
Author: Dac Bao Phan (http://www.jguru.com/guru/viewbio.jsp?EID=1347235), Sep 16, 2007 Could u please send me the complete code of shopping cart with checkbox to remove? My email: dacbao2111@yahoo.com, Thank a lot.. |
| Re[4]: One solution (for struts 1.1 beta?)
Author: Mangirdas Vaina (http://www.jguru.com/guru/viewbio.jsp?EID=1350364), Nov 5, 2007 Hi, could anyone please provide also me with a copy of the sample code or explain how to send collection from jsp to Action class (I would like to know how to remove/modify only one row from a <logic:iterate> result). My email : mangirdas@poczta.onet.pl , Thanks in advance |
| « previous | beginning | next » |
What is URI?
Can anybody help me What is URI please?
Location: http://www.jguru.com/faq/view.jsp?EID=741075
Created: Jan 30, 2002
Author: Pierre Sirolli (http://www.jguru.com/guru/viewbio.jsp?EID=724553)
Question originally posed by Bhaskar Kommuru (http://www.jguru.com/guru/viewbio.jsp?EID=709748
A URI can be further classified as a locator, a name, or both. The
term "Uniform Resource Locator" (URL) refers to the subset of URI
that identify resources via a representation of their primary access
mechanism (e.g., their network "location"), rather than identifying
the resource by name or by some other attribute(s) of that resource.
The term "Uniform Resource Name" (URN) refers to the subset of URI
that are required to remain globally unique and persistent even when
the resource ceases to exist or becomes unavailable.
The following examples illustrate URI that are in common use.
ftp://ftp.is.co.za/rfc/rfc1808.txt
-- ftp scheme for File Transfer Protocol services
gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
-- gopher scheme for Gopher and Gopher+ Protocol services
http://www.math.uio.no/faq/compression-faq/part1.html
-- http scheme for Hypertext Transfer Protocol services
mailto:mduerst@ifi.unizh.ch
-- mailto scheme for electronic mail addresses
news:comp.infosystems.www.servers.unix
-- news scheme for USENET news groups and articles telnet://melvyl.ucop.edu/ -- telnet scheme for interactive services via the TELNET Protocol
how to use a href in struts JSP? hi all, i try to pass dynamic data using a href but it seems fail to work in struts.
original JSP:
<href="/callfile.do?action=w&filename=<%=bean.getFILENAME()%>">
Struts JSP:
<html:link page="/callfile.do?action=w&filename=<%=bean.getFILENAME()%></html:link>;
i can't get the <%=bean.getFILENAME()%> value when using struts.can anyone help?
regards,
CY
Location: http://www.jguru.com/faq/view.jsp?EID=741079
Created: Jan 30, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Ong CY (http://www.jguru.com/guru/viewbio.jsp?EID=447528
Comments and alternative answersThe html:link tag is designed so that you can do that without resorting to scriptlets. Try:
<html:link page="/callfile.do?action=w" paramName="bean" paramProperty="FILENAME" paramId="filename"/>(Though, you may have problems unless the accessor is named getFilename, per the conventions.)
{soapbox}
Personally, I discourage use of the page form of html:link, and always use global forwards instead. This way all the entry points to your application are documented, and you don't have to expose API features like "action=w" in the JSP. You can give the action=w forward a logical name, and use that instead.
In struts-config: <forward="callW" path="/callfile.do?action=w"/> In your JSP: <html:link forward="callW paramName="bean" paramId="filename"/>
In my own applications, the only place I expose the name of another Action is in the html:form tags (and I'm working on that;-)
{/soapbox}
HTH - Ted
| buttons?
Author: blinky bill (http://www.jguru.com/guru/viewbio.jsp?EID=863602), May 2, 2002 The forward looks neater. One other question though, is there a simple way in struts for the link to show as a html [button] rather than as a standard hyperlink. Or do I need to use javascript on a button to do this? eg. setting window.location or something? |
| using HREF with struts - case sensitive issues
Author: Aidan Coughlan (http://www.jguru.com/guru/viewbio.jsp?EID=990908), Aug 29, 2002 Hi, Ive just starting using struts and have struggled for I wont say how long with getting a href to work. I had a request parameter on the href something like: .. href="/AgentStatusDetail?AgentName=OMSAGENT002.... Struts correctly located and executed the AgentstatusDetailAction, but when debugging through this code the AgentName parameter simply wasnt there. After much frustration, taking a lead from the struts sample application, I tried making the parameter "AgentName" to lowercase "agentname" , changing the references throughout the application, and it worked ! I havent experimented further to prove it, but I wonder if there may be some case sensitive issues with struts ? I notice that FILENAME is spelt uppercase in one of the posts here - if you are reading this & experiencing similar problems, it may be worth trying lowercase parameter names. Note: the get/set methods on the ActionForm class will still be getAgentname, and setAgentname (capital A only). |
| Re: using HREF with struts - case sensitive issues
Author: marc foley (http://www.jguru.com/guru/viewbio.jsp?EID=1029250), Nov 22, 2002 I am trying to do something very similiar and I am not having any luck. <html:link page="/servlet/changeSearch?adv=N&tab=<%=request.getParameter("tab")%>"> any thoughts? |
| Re[2]: using HREF with struts - case sensitive issues
Author: sl Yong (http://www.jguru.com/guru/viewbio.jsp?EID=1024371), Jan 11, 2003 Hi I would like to know whether you have any luck with ur problem |
| Re[2]: using HREF with struts - case sensitive issues
Author: Claudiu Dobre (http://www.jguru.com/guru/viewbio.jsp?EID=957289), May 20, 2003 It's a bit late to answer this :) but I'l try. Personally I like more the HTH - Ted's solution. I had a similar problem and one solution could be that <html:link page='<%= "/servlet/changeSearch?adv=N&tab=" + request.getParameter("tab") %>' > which acctually is not very nice.. :(
|
| here is the solution in my style
Author: Ajay Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1205911), Oct 18, 2004 I have couple of values displayed by the bean when I iterate and I need hyperlinks to all of them which are dynamic and each hyperlink has a unique value. And I need to pass two parameters when the user clicks on it. So the following way I am able to capture both the parameters from the action form. try this it works. I have spend alot of time on it. And I got 2 other ways of doing it. Let me know if you need further assistance. <form name="selectForm" action="/sv/jsp/client.do" method="post"> <input type="hidden" name="svId" value="Bill"> <input type="hidden" name="request" value="0"> <logic:iterate id="searchDetails" name="sv_container" property="searchResults"> <bean:define id="param1" name="searchDetails" property="svId"/> <a href="/sv/jsp/client.do?request=0&svId=<%=param1 %>"> <bean:write name="searchDetails" property="name"/> </a> </logic:iterate> -Ajay Kumar |
| Re: here is the solution in my style
Author: Ravijeet Das (http://www.jguru.com/guru/viewbio.jsp?EID=1276904), Dec 30, 2005 I am using Struts and jboss.I am having a main page with dynamic tab buttons. To display the tabs I need to iterate and get values from the database.On clicking each tab it expands to maximum 3 subtabs whose value is fetced from database.On clicking any sub tabs I need to pass the parameters tab and subtab ID for displaying some values on that JSP from the database corresponding to that tab and subtab id. |
| Re: here is the solution in my style
Author: Sumita Mukherjee (http://www.jguru.com/guru/viewbio.jsp?EID=1345988), Aug 28, 2007 Hi, I tried the above solution and when I click on the link it gives error 404-acton /topiclink not available. Here is what I tried: <form name="SearchForm" action="/TopicLink.do" method="post"> <input type="hidden" name="link" value="test"> <logic:present name="resultList" scope="session"> <logic:iterate id="showResult" name="resultList"> <bean:define id="param1" name="showResult"/> <%= showResult %> </logic:iterate> </logic:present> </form> In my struts-config I have this mapping: <action path="/TopicLink" type="symc.simple.ui.actions.LinkAction" name="searchForm" scope="session"> <forward name="showSearchData" path="/pages/details.jsp"/> </action> Please help me further. I am trying to dynamically pass the value of the iterate:id parameter(i.e. showResult) in the action. Thanks, ~S |
| A small follow up to Ted's answer.
Author: John Munsch (http://www.jguru.com/guru/viewbio.jsp?EID=236478), Dec 17, 2002 I just wanted to comment that the <forward> Ted refers to creating in the struts-config.xml file is in the global forwards section. I had thought that the forward would be within one of my action mappings because the link I was creating on the page was inside of one of the forms on that page. In fact, the location of the link on the page didn't matter, the forward it referred to had to be listed in the global forwards. |
| Any update on using Global Forward in Form Action?
Author: Anthony Law (http://www.jguru.com/guru/viewbio.jsp?EID=882127), Dec 23, 2002 Guru Ted Husted wrote: "In my own applications, the only place I expose the name of another Action is in the html:form tags (and I'm working on that;-)" Hi all I'm just curious if this is implemented yet? I tried using a recent nightly build & got: Cannot retrieve mapping for action /myGlobalForward' |
| multiple dynamic values to global forwards
Author: Bapi Reddy (http://www.jguru.com/guru/viewbio.jsp?EID=1165380), Apr 23, 2004
How do i send multiple dynamic values to the global forward
|
| Re: multiple dynamic values to global forwards
Author: Himabindhu Kunz (http://www.jguru.com/guru/viewbio.jsp?EID=1247742), Jun 8, 2005 Hi Here is the solution. you can pass multiple query string parameter properties by specifying a map with the name attribute demonstrated as follows: <% java.util.HashMap newValues = new java.util.HashMap(); newValues.put("floatProperty", new Float(444.0)); newValues.put("intProperty", new Integer(555)); newValues.put("stringArray", new String[] { "Value 1", "Value 2", "Value 3" }); pageContext.setAttribute("newValues", newValues); %> ... and then passing this to the link tag <html:link action="/html-link" name="newValues"> Float, int, and stringArray via name (Map) </html:link> the Java scriptlet creates a HashMap and sticks the HashMap into page scope under the attribute newValues. The link tag links to an action and specifies the HashMap as its list of query string parameters with the name attribute. Cheers Bindhu |
| Re[2]: multiple dynamic values to global forwards
Author: Sumita Mukherjee (http://www.jguru.com/guru/viewbio.jsp?EID=1345988), Aug 29, 2007 Hi, I tried the above solution but the problem is I need to set the values of the Hashmap dynamically with the logic:Iterate's ID value. But it gives me a syntax error. here is my code: <% String contextPath = "testing"; java.util.HashMap newValues = new java.util.HashMap(); newValues.put("link",<%=contextPath%>);pageContext.setAttribute("newValues", newValues);%> <html:link action="/TopicLink" name="newValues" target="basefrm"> stringArray via name (Map) </html:link> I want to put a variable value in: newValues.put("link",<<the value of contextpath set above>>). Please help. Thanks a lot for this. ~S |
| Problem same different scenario
Author: Suresh Atmakuru (http://www.jguru.com/guru/viewbio.jsp?EID=1356961), Feb 21, 2008 | <html:link action="/Reports.do">[Reports]</html:link> | In this link i need to remove Reports.do and need to point to some other outside [assume mail.gmail.com which accepts userid and password in the form of query strings when it is a GET request]. I need to make the POST request with userID and password. Ex: http://mail.google.com/mail?userId=jguru+password=jguru if it is a GET . but how i can pass a POST request using html:link
| href in Struts html:link page="/myPage.do"/
Author: Java World (http://www.jguru.com/guru/viewbio.jsp?EID=1364910), Jun 26, 2008 Hi all, I also had same problem. You can try like this <bean:define id="dVar" type="java.lang.String"> <%=RequestVariableName%> </bean:define> <html:link page="/goToAction.do?pageID=${dVar}" >Link Text to print</html:link> in a same page |
Maintaining form data across pages... I am trying to setup a series of jsp pages (jsp1, jsp2, jsp3). Each of these adds or modifies properties (or collections) of object customerForm(supply name/address, add contacts, etc.) This is an "experimental" app I'm putting together to try out struts.
In struts-config.xml, I have the choice of setting the scope parameter for each action mapping. If I set scope to "request", then customerForm is instantiated each time the form is presented - data is lost across forms.
If I set to "session" then I can maintain the data across the various forms, but customerForm.reset() is still called.
My questions:
Jeff.
Location: http://www.jguru.com/faq/view.jsp?EID=749741
Created: Feb 6, 2002
Author: Jason Rosenblum (http://www.jguru.com/guru/viewbio.jsp?EID=740621)
Question originally posed by Jeff Sprenger (http://www.jguru.com/guru/viewbio.jsp?EID=740521
here's an example: you have an HTML form. after it is filled out the user previews the results on a second JSP and then chooses to submit or edit the HTML form again. If the user submits, then he is forwarded to a confirmation page. In order to process this you do: 1) cache ActionForm in session after form submission. 2) I pass my Customer bean to the preview page via request. I was able to construct a Customer bean by calling a toXXXX() method in my ActionForm (e.g. toCustomer). 3) on the confirmation page i query the database and return the results as a Customer bean passed via request. I also clean out session using removeAttribute(). I hope that helps...Comments and alternative answers
| Not so clear!
Author: Reza Naqshbendi (http://www.jguru.com/guru/viewbio.jsp?EID=806149), Mar 21, 2002 I mean for me! I've been tearing my hair out about this and I've supposed there should a way whithin Struts itself to pass the data from pages without me saving them here and there and pass them around. The official doco recommends to use 'one big form for many pages, actions'. In this case there should be way to avoid that reset() being triggered on session forms and clearing up the data already populated. |
| Need a better way
Author: Howard Frost (http://www.jguru.com/guru/viewbio.jsp?EID=891608), May 24, 2002 I've also had this problem in a different scenario. My ActionForms (DynaActionForms actually) contain all the fields necessary to paint the page and collect the results. Not all the information used to paint the page is submitted (e.g. population of a dropdown list). When the form is submitted and the Action detects a validation error it is overly difficult to repaint the page. If the Action forwards back to the JSP page, the JSP tag which paints the dropdown errors out because reset() cleared this data. If the Action forwards to the Action which originally painted the page, the User's submitted information needs to be carefully overlayed on the initial screen paint data.
It should be possible to specify DynaActionForm properties to be left un-reset. This way, Action can safely forward back to the JSP page.
|
| Re: Not so clear!
Author: Mike Melia (http://www.jguru.com/guru/viewbio.jsp?EID=122959), May 29, 2002 Make reset() check if the data has been completed (i.e. all attributes not null) before resetting them to null. That way the data is not reset until it is necessary. |
| Re[2]: Not so clear!
Author: Dean Chen (http://www.jguru.com/guru/viewbio.jsp?EID=899352), May 31, 2002 I don't think you can change the behavior of reset in a DynaActionForm. |
| Re[3]: Not so clear!
Author: Mike Melia (http://www.jguru.com/guru/viewbio.jsp?EID=122959), Jun 2, 2002 Maybe so, but I wasn't replying to the message that mentioned the DynaActionForm ;) |
| Re[4]: Not so clear!
Author: scott naef (http://www.jguru.com/guru/viewbio.jsp?EID=1242955), May 6, 2005 You can extend the DynaActionForm and overide the reset method as needed... |
| Use html:hidden tags to re-populate the form.
Author: Artur de Sousa Rocha (http://www.jguru.com/guru/viewbio.jsp?EID=70489), Dec 20, 2002 If you don't have an outrageous number of fields or special data (like passwords), you can use <html:hidden> tags to keep the data across pages. The only multi-page feature you will have to implement will be smart validation that knows which data to check on a given page. Regarding passwords, just use separate single-page forms for password entry. The same applies to file upload. |
| You can cheat and make the fields static.
Author: Brian Grant (http://www.jguru.com/guru/viewbio.jsp?EID=1052551), Jan 31, 2003 This will allow all forms to see only the fields you want to be accessible accross you forms. |
| Re: You can cheat and make the fields static.
Author: Danilo Gurovich (http://www.jguru.com/guru/viewbio.jsp?EID=1061840), Feb 28, 2003 Doesn't this violate thread safety? |
| Re[2]: You can cheat and make the fields static.
Author: yayo yayez (http://www.jguru.com/guru/viewbio.jsp?EID=1222082), Mar 9, 2005 Yes I think it breaks thread safety because they're different beans but same class... I Use html:hidden to store data among several pages and the reset tricky I think that could be solved extending dynaforms |
| Handling multi page form beans
Author: ravi kalidindi (http://www.jguru.com/guru/viewbio.jsp?EID=1232513), Mar 14, 2005 I had a similar situation where I needed to share the same form bean across multiple pages - similar to a wizard like page flow. The basic concepts for this are:
All the best! - Ravi |
| Re: Handling multi page form beans
Author: Kiran Chandra (http://www.jguru.com/guru/viewbio.jsp?EID=1233000), Mar 16, 2005 I have a question regarding uploading a file using DynaActionForm. I am not sure if the form value is getting reset but it just doesn't seem to work. Here's the code for reference. It is an extension to the example by James Turner at http://www.developer.com/java/ent/article.php/3321521 with an additional field called fileone of the type FormFile in the bean. Everything works fine except the upload feature. The fileone property is set to null somehow and cannot be retreived in the action instance. I would highly appreciate any feedback on the same. Sorry to send you the link since I think that it better explains what I am doing than pasting all the code myself. Please reply if you get a chance. Kiran |
Switching the locale(language) of an application via a button on a page.
How can you change the locale of an application via a button on a web page. I am using struts and don't want the user to have to change their language from the browser (e.g. Tools-Internet Options-Languages in IE).
I want the user to be able to toggle languages from a button! This toggling only needs to be held throughout the lifecycle of the user's session. When the session ends the application will automatically use the browsers default language when a page is requested.
Comments and alternative answersStruts places a locale object in the application scope, and it's just a matter of changing that.
David has a nice example in his sample Validator application.
HTH - Ted
| Locale in Session
Author: Thomas Qvarnstrom (http://www.jguru.com/guru/viewbio.jsp?EID=761801), Feb 17, 2002 I should change the Locale in the application scope since that may effect other user. Instead use this piece of code in your ActionForm:
session.setAttribute(org.apache.struts.action.Action.LOCALE_KEY, new java.util.Locale("","") );
|
| Re: Locale in Session
Author: Steve Leung (http://www.jguru.com/guru/viewbio.jsp?EID=939919), Jul 6, 2002 I have tested on the David's sample Validator application. http://home.earthlink.net/~dwinterfeldt/archive/validator20020114.zip. I try to add new Locale of "zh". First time, I type some chinese characters in property file and save as ApplicationResources_zh.properties without use native2ascii.exe. The JSP parser fail to compile it in run time. Second time, after I use native2ascii on the properties file. It success compile but only display ?? instead of chinese characters. Is this a bug ? I suspect that struts read the correct properties file but use the wrong encoding methods on String. Remarks: my browser use [en-us] encoding. I press the link to change locale to zh. Anyone know the problem ? |
| Re[2]: Locale in Session
Author: John Jiang (http://www.jguru.com/guru/viewbio.jsp?EID=1017744), Nov 6, 2002 Hi steve, Since you already converted the resource file with native2ascii, I guess you need to set the encoding of the jsp page to UTF-8. <%@page language="Java" contentType="text/html; charset=UTF-8"%>. |
| Re[2]: Locale in Session
Author: candra gunawan (http://www.jguru.com/guru/viewbio.jsp?EID=1279903), Jan 21, 2006 hi steve, can u tell me how to use native2ascii.exe, and what kind language that is supported by this program ?? thank u candra |
| get downloaded struts-validator.war
Author: Abhishek Shrivastava (http://www.jguru.com/guru/viewbio.jsp?EID=1219583), Jan 25, 2005 hi........ get the struts-validator.war and go to the examples... it will surely help u... the same thing implemented here.. Good luck... Abhishek |
select tag and options tag. How do I use the same info, but different variables?
I followed the example previously given by Ted, allowing me to fill an options tag from a database, use helper classes. I have a situation where two select/option tags are filled from the same bean call.
The following code is just under my <html:Form>
<bean:define id="titles" name="DocRegForm" property="title"
type="java.util.Collection"/>
<bean:define id="specs" name="DocRegForm" property="spec"
type="java.util.Collection"/>
below I have the following:
Specialty #1
<html:select property="spec">
<html:options collection="specs" property="value"
labelProperty="label"/>
</html:select>
Specialty #2
<html:select property="spec">
<html:options collection="specs" property="value"
labelProperty="label"/>
</html:select>
I need to differentiate between Specialty#1 and Specialty#2. How can I do this? If I change the select property it tells me it cannot find the getter method. Must I have two different methods simply to allow me to pass two different pieces of information? If I leave it the way it is, I get two "spec" variables in my "GET".
Location: http://www.jguru.com/faq/view.jsp?EID=756521
Created: Feb 12, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by josef richberg (http://www.jguru.com/guru/viewbio.jsp?EID=715417
HTML does allow parameters with duplicate name, and Struts will captures those like any other property if an array is used.
private String[] spec = {"",""}; public String[] getSpec() { return this.spec; } public void setSpec(String spec[]) { this.spec = spec; }HTH -Ted
More control with <html:errors/>
I know you can specify header and footer in the prop file, but what if different pages have different needs in terms of displaying errors. E.g., In some cases its a list and in others I want sentences strung together with no header.
What if I want to list out errors but don't want to user <ul>...</ul>
?
Are there code examples of how to use the <html:errors/>
more extensively than currently described in the documentation?
Location: http://www.jguru.com/faq/view.jsp?EID=756562
Created: Feb 12, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by John Crossman (http://www.jguru.com/guru/viewbio.jsp?EID=12222
Comments and alternative answersThe message tag in the nightly build offers more flexibility
This might also be available in the Struts Validator library
The other alternative is leave the errors header and footer blank, so you can add the HTML yourself.
To test for the presence of error messages in Struts 1.0.x, you can use
<logic:present name="org.apache.struts.action.ERROR">And then wrap (or not wrap) the messages with markup
To retrieve individual messages, you can specify the property in the html:error tag.
But, the new messages tag really does a much better job of this.
HTH -Ted
| See html:messages, not bean:message
Author: Jerome Jacobsen (http://www.jguru.com/guru/viewbio.jsp?EID=65688), Oct 3, 2002 To clarify, Ted is referring to the new html:messages tag, not the bean:message tag.
The html:messages tag is more flexible and generic than the html:errors tag. It can display messages "stored as an ActionMessages object, ActionErrors object, a String, or a String array". |
| Displaying information about the field in error
Author: Krishna Kumar (http://www.jguru.com/guru/viewbio.jsp?EID=1025653), Nov 16, 2002 Using html:messages or logic tags, is it possible to output a header for each property which has errors attached to it, without explicitly coding a html:messages block for each property? I have a form which has several fields, which are validated in the Action class. These errors are added to the ActionErrors collection with the field's property name, for example,
errors.add("myFirstField", new Action Error(...);
Now, in the jsp, it is possible to produce an output such as Errors for My First Field <error1 text> <error2 text> Errors for My Third Field <error1 text> I would like to do this without repeating a <bean:message key="myfirstfield.error.header" /> <html:messages id="error" property="myFirstField"> <bean:write name="error" /> </html:messages> block for each property in the form as (a) this would be error prone, programmers may miss to put this block for all the properties in the form and (b) if this can be done without reference to specific form's properties, then this generic code can be pulled into each page via some kind of include or template mechanism. Thanks in advance for any hints. |
| Answer for More control with html:errors/ I know you can specify header and footer in the prop file, but what if ....
Author: pahiappan singaravel (http://www.jguru.com/guru/viewbio.jsp?EID=1238466), Apr 14, 2005 In the properties file you can simply remove the headers and footers and add the html tags wherever you want. like errors.Login.use=<b>username required<b> |
Any html:multibox samples out there?
Hi, can anybody please point me to a working sample using html:multibox?
Retrieving the values out of my form bean works well using a getter method which returns an array of String. However, having a setter method which takes an array (Collection) doesn't work.
Thanks in advance.
Markus
Comments and alternative answersActionForm:
private String[] selectedItems = {}; private String[] items = {"UPS","FedEx","Airborne"}; public String[] getSelectedItems() { return this.selectedItems; } public void setSelectedItems(String[] selectedItems) { this.selectedItems = selectedItems; }JSP:
<logic:iterate id="item" property="items"> <html:multibox property="selectedItems"> <bean:write name="item"/> </html:multibox> <bean:write name="item"/> </logic:iterate>HTH -Ted
| It works!
Author: Markus Neifer (http://www.jguru.com/guru/viewbio.jsp?EID=592820), Feb 15, 2002 Yes, this works. But one should not forget to add the 'name' attribute to the logic:iterate start tag. Well, just copy and paste is never a good idea, right?! ;-) Thanks, Ted. Markus |
| Re: It works!
Author: Eduardo Troncoso (http://www.jguru.com/guru/viewbio.jsp?EID=1027323), Nov 19, 2002 To me, don't work. Weblogic (6.1) show this exception message: javax.servlet.jsp.JspException: No getter method for property selectedItems of bean org.apache.struts.taglib.html.BEAN at org.apache.struts.util.RequestUtils.lookup(RequestUtils.java:517) at org.apache.struts.taglib.html.CheckboxTag.doStartTag(CheckboxTag.java:205) at jsp_servlet.__eliminar_usuario._jspService(__eliminar_usuario.java:167) at weblogic.servlet.jsp.JspBase.service(JspBase.java:27) at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:265) . . . What wrong !? |
| Re[2]: It works!
Author: samaria camarena (http://www.jguru.com/guru/viewbio.jsp?EID=1101903), Jul 16, 2003 Hi, I got a similar error. Did you get a solution for your error? Regards!!! 500 Internal Server Error javax.servlet.jsp.JspException: No getter method for property value of bean item java.lang.Object org.apache.struts.util.RequestUtils.lookup(javax.servlet.jsp.PageContext, java.lang.String, java.lang.String, java.lang.String) |
| Re[3]: It works!
Author: rehnesh k (http://www.jguru.com/guru/viewbio.jsp?EID=1284772), Feb 20, 2006 i think some came in betwen Two action, Better idea is to put the collection object into session |
| Re: It works!
Author: paul mclachlan (http://www.jguru.com/guru/viewbio.jsp?EID=1049850), Jan 27, 2003 I have defined the "name" in the iterate Tag but I get the following exception. What have I failed to do? As I see it I add the code into the ActionForm defined to be associated with the jsp in the appropriate action-mapping struts-config.xml javax.servlet.jsp.JspException: Cannot find bean null in any scope java.lang.Object org.apache.struts.util.RequestUtils.lookup(javax.servlet.jsp.PageContext, java.lang.String, java.lang.String, java.lang.String) int org.apache.struts.taglib.logic.IterateTag.doStartTag() void _Landowner._jspService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) |
| Re[2]: It works!
Author: srinivas reddy (http://www.jguru.com/guru/viewbio.jsp?EID=1249961), Jun 23, 2005 did u ensure that the name is the same one that you used in your struts config file, or else it is going to fail ex: <action path="/xxxForm" type="xxxxAction" name="test" input="/jsp/test.jsp" validate="true"> <forward name="valid" path="/jsp/xxx.jsp" /> </action> The name that you use for iterate should be "test" |
| Re: It works!
Author: eric lee (http://www.jguru.com/guru/viewbio.jsp?EID=947775), Mar 5, 2003 Was this works even without defining public String[] getItems() in your Action Form? Anyway, I am having item bean not found in any scope error. and idea? Eric |
| Can this use collections instead of arrays?
Author: Mike Park (http://www.jguru.com/guru/viewbio.jsp?EID=849301), Apr 22, 2002 can I have an ArrayList of objects instead of an array? ActionForn -> private ArrayList ethnicity=new ArrayList(); + getter and setter jsp -> <logic:iterate id="item" property="items"> <html:multibox property="ethnicity"> <bean:write name="item"/> </html:multibox> <bean:write name="item"/> </logic:iterate> What if my arrayList contained non-string objects (KeyNamePair, a key-value mapper that is less than a hash map entry, that maps string -> string, boolean->string or int->string), will the array list be populated with only the selected items? Mike |
| Re: Can this use collections instead of arrays?
Author: Lim BH (http://www.jguru.com/guru/viewbio.jsp?EID=920254), Jul 8, 2002 Hi Mike, I have the same question as you. Did you get any answer for the question you posted? Can you share them with me? Thanks, Lim |
| Re[2]: Check all / Uncheck all
Author: HELIGON Sandra (http://www.jguru.com/guru/viewbio.jsp?EID=823885), Apr 1, 2003 Has someone the solution to allow the user to check all the elements of the table in only one order ? Is the treatment made only side client by a Javascript or one requests from the web server? |
| Re[2]: Can this use collections instead of arrays?
Author: Murali Vasudevan (http://www.jguru.com/guru/viewbio.jsp?EID=1104105), Jul 25, 2003 I have used a collection of LabelValueBean to generate checkboxes with values different from the labels. It is very important that you specify the name attribute (the ActionForm name) in the iterate tag. org.apache.struts.util.LabelValueBean is available from STRUTS 1.1. If anyone is interested, I can give you the code. The same approach may work for a group of radio buttons too. |
| Re[3]: Can this use collections instead of arrays?
Author: Roberto Silva (http://www.jguru.com/guru/viewbio.jsp?EID=1118009), Sep 25, 2003 Hi Murali, I´d like to receive your example code. I´m trying to do that using a Vector and your code may be helpfull. Thanks. |
| Re[3]: Can this use collections instead of arrays?
Author: Rajesh H (http://www.jguru.com/guru/viewbio.jsp?EID=1135662), Dec 24, 2003 I am using dynaactionform for our application and the jsp page has multibox which is being dynamically generated, i need to know how to set the multibox marked when the user retrives the previously avilable record from the database. Please pass me your code for the above said functionality. Regards H.Rajesh hrajesh3@ford.com |
| Re[4]: Can this use collections instead of arrays?
Author: Rohini Rayi (http://www.jguru.com/guru/viewbio.jsp?EID=1357485), Feb 27, 2008 hi Rajesh, Did you find a solution for your problem, can you send me the code. Thank you in advance!! |
| Re[3]: Can this use collections instead of arrays?
Author: Seema Bhujbal (http://www.jguru.com/guru/viewbio.jsp?EID=1179365), Jul 7, 2004 hi i would like to receive your code.Thanking in advance. |
| Re[3]: Can this use collections instead of arrays?
Author: Awadh Pandey (http://www.jguru.com/guru/viewbio.jsp?EID=1189916), Nov 4, 2004 Hi Murali, I am new to Struts and I am finding it hard to follow all recomendation. I would very much appreciate if you could share your jsp code and associated java code. I have been able get the multibox example running with the static array text in the form bean class. I would like to generate the array dynamically in the jsp code itself. and it does not work. cheers and thanks in advance, Awadh awadh@pmdashboard.com.au |
| Initialization
Author: Juliane Scheider (http://www.jguru.com/guru/viewbio.jsp?EID=1107989), Aug 12, 2003 How can I initialize a Multibox, that it will be marked? |
| Multibox
Author: Latha Rao (http://www.jguru.com/guru/viewbio.jsp?EID=1157483), Mar 25, 2004 Did you find a solution to this problem? I am trying to display a page with all of the Multiboxes checked. The Multibox is generated dynamically and so I cannot determine ahead of time what the size or the values will be. |
| Example...
Author: A O (http://www.jguru.com/guru/viewbio.jsp?EID=1156324), Mar 22, 2004 all is there : http://j2ee.lagnada.com/struts/multibox-example1.htm a very good example |
| another example using LabelValueBeans
Author: A O (http://www.jguru.com/guru/viewbio.jsp?EID=1156324), Mar 22, 2004 Another interesting example using an existing struts Bean : LabelValueBeans http://www.johntopley.com/kb/java/0027.html |
| « previous | beginning | next » |
In order to run Struts, do I need to install a servlet container such as Tomcat?
Location: http://www.jguru.com/faq/view.jsp?EID=771298
Created: Feb 25, 2002
Author: Aron Tunzi (http://www.jguru.com/guru/viewbio.jsp?EID=446077)
Question originally posed by Nguyen van Tin (http://www.jguru.com/guru/viewbio.jsp?EID=761500
Yes, you must!Comments and alternative answersSee the installation requirement for Struts: http://jakarta.apache.org/struts/userGuide/installation.html
| Struts
Author: Rahima Shaik (http://www.jguru.com/guru/viewbio.jsp?EID=1293019), Apr 13, 2006 Is it must to install Tomcat to run struts or is it enough to have application server like weblogic or websphere? |
| Re: Struts
Author: amit B (http://www.jguru.com/guru/viewbio.jsp?EID=1305487), Jul 17, 2006 any application server should do |
I found the following methods in Action.java which I think may help to control the session ID. That means if the user submits the page and press the back button and submit the page again it will throw an error.
generateToken(HttpServletRequest request)
saveToken(HttpServletRequest request)
isTokenValid(HttpServletRequest request)
If anybody has used these methods let me know how to use these methods .
Thanks,
Subhendu
Comments and alternative answersBefore going to a page you want to protect, route to an Action first and call SaveToken. This stores a token with a unique value in the user's session.
If the page uses the html:form tag, it will automatically include a hidden field with the token if it finds one in the session.
In the Action that receives the page, use isTokenValue to see if the token in the session matches the one from the form. Call resetToken to clear the token, so it can't be used again.
HTH -Ted.
| Tokens for Transaction Control : How do you gracefully handle the error case?
Author: Jerome Jacobsen (http://www.jguru.com/guru/viewbio.jsp?EID=65688), Oct 3, 2002 I've seen the Struts 1.1b2 example's use of the Token for transaction control technique. This is in EditRegistrationAction and SaveRegistrationAction. However, I'd like to know if there is a more robost solution to this problem. I'd like the ability to ignore the second posting and still return the results from the first. That is, act as if the second posting never occurred. Is there a way to do this?
The problem with the Example's approach is that the user doesn't really know what to do next after the error is displayed. They don't get their display results from the first posting. How do they know it succeeded? |
| Re: Tokens for Transaction Control : How do you gracefully handle the error case?
Author: René Vangsgaard (http://www.jguru.com/guru/viewbio.jsp?EID=585009), Mar 19, 2003 I know this is an old question, but have you checked the recent article on JavaWorld on this issue? Note: JavaWorld is unavailable at the moment, so I cannot supply the link. |
| Re[2]: Tokens for Transaction Control : How do you gracefully handle the error case?
Author: Glen Blanchard (http://www.jguru.com/guru/viewbio.jsp?EID=1090702), Jun 3, 2003 The JavaWorld article you are referring to is this I think http://www.javaworld.com/javaworld/javatips/jw-javatip136.html |
| Re[3]: Tokens for Transaction Control : How do you gracefully handle the error case?
Author: Xiaolong Hao (http://www.jguru.com/guru/viewbio.jsp?EID=1087550), Aug 13, 2003 I am not sure the solution provided in this tip solves the problem. I looked at the source code (by the way, the source code is quite different from the segment of code in the article), I cannot find the logic to handle the case of the following sequenct: 1) the first request is sent to server 2) the execut() is invoked 3) before the execut() finishes, the same request is sent to server again. It seems to that it only handle the case that the same request is sent after the first request finishes. |
| Token concurrency issue
Author: René Vangsgaard (http://www.jguru.com/guru/viewbio.jsp?EID=585009), Mar 19, 2003 Assume that the execute() method of a Struts action contains the following:
if (isTokenValid(request)) {
resetToken(request);
// Guarded code, must only be executed once for the current token.
}
What happens, if two requests from the same client (that is, the requests belongs to the same session) enters the action at the same time, and...
|
| Re: Token concurrency issue
Author: Scott Carlson (http://www.jguru.com/guru/viewbio.jsp?EID=1085622), May 17, 2003 use isTokenValid(request,true), which synchronizes on the Session before it does the reset. |
| Re[2]: Token concurrency issue
Author: Joaquin Almansa (http://www.jguru.com/guru/viewbio.jsp?EID=1171714), May 20, 2004 Hi, One question about isTokenValid(..., true). I suppose token is only resetted if token is valid. Is it so? If not, we may be loosing a valid submit which happens later. For instance: 1. Form1 is marked ok with the current token, token1. 2. User bookmarks an old form, Form0, marked with token0. When evaluating Form0 submit, if we reset token (I understand there's only one per session at a time), when Form1 is submitted we will think it is invalid. Does token mechanism works like this? Thanks in advanced, Joaquin. |
| Re[3]: Token concurrency issue
Author: George Thomas (http://www.jguru.com/guru/viewbio.jsp?EID=1261012), Sep 5, 2005 When multiple requests come to server they will be managed by different threads. For request1 it will call a add/edit page where we will save a token and on save action we check whether the token is there then save the values and reset the token.So that if the user clicks on back button and again try to save,multiple records with same values will not be generated. Even if Request2 comes at same time it will proceed independent of request1 since each are different threads and proceed independently. When we save a token it gets stored in a request scope (and not session scope),so it will be for the particular request that token will be having a value till that request ends.So when it submits it checks for that token and resets it if already present and saves the data.All this process must be inside if(isTokenValid)loop. If the token has been destroyed just forward to next page without any save operation |
| Re[4]: Token concurrency issue
Author: Juergen Schmitt (http://www.jguru.com/guru/viewbio.jsp?EID=1270911), Nov 9, 2005 Hi there! I think this is not correct. The token will be saved in the session. See the Struts Source code:
public synchronized void saveToken(HttpServletRequest request) { |
| do we have a jsp tag doing the same thing as Action's saveToken?
Author: Amit Rana (http://www.jguru.com/guru/viewbio.jsp?EID=1116177), Sep 18, 2003 Ted said -- Before going to a page you want to protect, route to an Action first Is it possible to start from a JSP? does any of the available tags provide the same functionality? Regards. |
| Struts Token to prevent concurent update
Author: satya das (http://www.jguru.com/guru/viewbio.jsp?EID=1362471), Jun 19, 2008 here is the code with Example Struts Token |
How works the "/admin/reload.do" in struts?
Hi!
Looking in the struts documentation i found the class ReloadAction, I though
that this class reload the struts-config.xml and the application resources without restart the appserver (in my case Tomcat 4.0)...
I want do this because i want modify the MessagesResources file, but when i modify the file and call /admin/reload.do, it updates everything except the MessagesResources file!!
I`m doing something wrong or what?
Please help Me!
PS: There is another way to do it? I mean, update the MessagesResources file?
Location: http://www.jguru.com/faq/view.jsp?EID=779194
Created: Mar 2, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Adolfo De Unanue (http://www.jguru.com/guru/viewbio.jsp?EID=765312
Comments and alternative answersThe ReloadAction reloads and reparses the Struts configuration files. The resource bundle used by the MessageResource file is not actually part of the configuration, so it is not reloaded. Some containers do automatically reload property files, but this is not a Struts specific features. It would apply to any Web application using standard resource bundles.
A question to ask in the Tomcat circles might then be "How to configure Tomcat to reload resource bundles when they change.".
HTH -Ted
| There apparently is no support for reload in 1.1b. Are there plans to add it?
Author: Dean Chen (http://www.jguru.com/guru/viewbio.jsp?EID=899352), May 31, 2002 There apparently is no support for reload in 1.1b. Are there plans to add it? |
| Re: There apparently is no support for reload in 1.1b. Are there plans to add it?
Author: Mohammad Rizwan (http://www.jguru.com/guru/viewbio.jsp?EID=989793), Feb 5, 2003 Can u tell me how to configure tomcat , so that it loads properties file everytime it changes? |
| ...forcing reload of resource bundles
Author: Andrew Hart (http://www.jguru.com/guru/viewbio.jsp?EID=1063965), Mar 6, 2003 see also: http://www.jguru.com/faq/printablefaq.jsp?topic=I18N Author: Kevin Schaaf (http://www.jguru.com/guru/viewbio.jsp?EID=466729), Sep 10, 2001 You can implement this non-standard way of refreshing all resource bundles in the VM as follows: Class klass = ResourceBundle.getBundle [...] |
| Re: ...forcing reload of resource bundles
Author: Axl Kaross (http://www.jguru.com/guru/viewbio.jsp?EID=1153725), Mar 12, 2004 does this still work? I couldn't get any bundle for resources.framework (Can't find bundle for base name resources.framework, locale de_DE) if i'm using fully qualified classname of my application properties, the bundle is found. but that doesn't seem to work either for reloading |
| Re[2]: ...forcing reload of resource bundles
Author: Ed Kusnitz (http://www.jguru.com/guru/viewbio.jsp?EID=1208990), Nov 3, 2004 It didn't work for me either. The code found the SoftCache but nothing got refreshed. But there is an easier way. Just create your MessageResources from a new MessageResourcesFactory. That's where the cache apparently is. HTH --Ed |
| Re: ...forcing reload of resource bundles
Author: V. Ananth (http://www.jguru.com/guru/viewbio.jsp?EID=952581), Oct 20, 2004 I tried this in my application it is showing the errors, is that the code u tried in your application |
The Life of An ActionForm
Hi,
I'm trying to setup a form that will populate with the information about a user (their name, address, etc.) I'm having trouble with this because I don't really understand how the ActionFormBeans work.
When are they created and destroyed? When is the reset() method called? Should I call it myself or does Struts do it for me? What about the validate() method? Is it only triggered when I call it in my code?
I have seen some forms that create the ActionForm bean in one action that creates the populated form page, and then uses another action to store the data in the model. How do I set this up? Will the reset() method not be called before I want it to?
If someone could please clear up the life cycle of an ActionForm bean I would appreciate it. Thanks!
Comments and alternative answersStruts uses ActionForms to both populate a HTML form, and then to capture the parameters when a form is submitted.
When a request is submitted, the ActionServlet matches the URI for the request against the path of an action-mapping. If there is a form-bean for that action-mapping, it looks for an ActionForm under the form-bean name. If it doesn't find one, a new one is created. The ActionServlet then calls reset() on the new or pre-existing ActionForm and populates it from the request. If the action-mapping has validate set to true, the ActionServlet calls the validate method. If this returns any error messages, the ActionServlet forwards to the URI indicated by the action-mappings error property. This is often a JSP, but it can also be another action-mapping. The latter being needed when there are drop-down controls to populate and so forth. If there are no errors, the ActionServlet passes the (populated and validated) ActionForm to the Action indicated by the action-mapping element.
When a JSP with an html:form tag is rendered, the html:form tag uses its action path to look-up its action-mapping. Like the ActionServlet, it uses the form-bean to check for a ActionForm in the appropriate servlet context. If it doesn't find one, it creates one. The new or pre-existing ActionForm is then used by the other html:tags to populate their elements.
It's important to note that the form-bean name is used as the default attribute name. Another attribute name can be specified in the action-mapping if needed. Likewise, the html tags default to using the ActionForm related to the html:form tag, but any bean can be specified for any html tag element (ActionForm or not).
When passing ActionForm beans between Actions it is important to note that the ActionServlet will try to populate it again between Actions. If you modify a value, you must be sure to protect it from autopopulate or reset. One way to do that is to add a mutable switch to your ActionForm bean. See SuperForm for an example
HTH, Ted
| Lifetime of an ActionForm (continued...)
Author: Keshav Deshpande (http://www.jguru.com/guru/viewbio.jsp?EID=243878), Apr 14, 2002 Ted: From what I gather from your comments as well as the SuperForm implementation, it allows me to make the form mutable/immutable but ONCE and only ONCE within a user session. But what if I need to make the form mutable dynamically within a single session, given that I have only one instance of the ActionForm?
Consider the following example: In the second scenario the idea that an ActionForm maintains the form state works quite well in that, I can go back to the form and find that the form values are all maintained between requests (but within a session). But the problem arises when I want a user to start over within the same session, i.e. I want to clean out any and all priorly entered values on the ActionForm. How do I accomplish this? Any ideas/suggestions would be deeply appreciated... |
| Example of Implementing Superform
Author: Anand Jayaraman (http://www.jguru.com/guru/viewbio.jsp?EID=854980), Apr 25, 2002 Ted: I just started on struts and was looking @ your superform. I have a code in my JSP <html:text property="programName" size="40" maxlength="40"/> How will have the "programName" go after the getter method in the SuperForm getProperty with a Parameter as "programName" Thanks, |
| ActionForm Lifecycle.
Author: Rick Small (http://www.jguru.com/guru/viewbio.jsp?EID=1054935), May 28, 2003 Ted, when you state: "When a JSP with an html:form tag is rendered, the html:form tag uses its action path to look-up its action-mapping. Like the ActionServlet, it uses the form-bean to check for a ActionForm in the appropriate servlet context. If it doesn't find one, it creates one. The new or pre-existing ActionForm is then used by the other html:tags to populate their elements. " Isn't there a call to reset() in this sequence? I'd just like to confirm that the reset() method is supposed to be called on a 'new' ActionForm before it is used to populate the html:form?
Rick |
| Re: ActionForm Lifecycle.
Author: Abhishek Shrivastava (http://www.jguru.com/guru/viewbio.jsp?EID=1219583), Jan 6, 2005 hi..., ya ...reset method is called automatically everytime by the ActionServlet before populating the ActionForm bean properties.so u need not to call it explicitly.... good luck.. Abhishek |
| SuperForm has been moved to CVS attic
Author: Patterson Waltz (http://www.jguru.com/guru/viewbio.jsp?EID=1147262), Aug 5, 2004 Find it here http://cvs.apache.org/viewcvs.cgi/jakarta-struts/contrib/scaffold/src/framework/main/org/apache/scaffold/http/Attic/SuperForm.java |
| Re: SuperForm has been moved to CVS attic
Author: Bala Paranj (http://www.jguru.com/guru/viewbio.jsp?EID=505521), Jan 12, 2005 Why not just over-ride the reset method with a empty method? |
| Confused
Author: Saritha V (http://www.jguru.com/guru/viewbio.jsp?EID=1055612), Jan 27, 2005 Confused with the what I have been observing while working with Action Forms and with its strange behavior and after reading all the posts abt action forms and reset behavior. I would like to know how data is populated into ActionForms? From all above posts, I understand that ActionServlet populates the ActionForm when it process new request or when it renders JSP page. I wanted to know what is the source for the ActionServlet to populate ActionForm?. I think it is request. Can some one please explain me how this works in a pictorial format? JSP to Action JSP to action to Action Thank you Your input woiuld be a great help to me.. |
| Re: Confused
Author: Jyothi Rajesh (http://www.jguru.com/guru/viewbio.jsp?EID=1245093), May 20, 2005 Hi, Check out this site. http://rollerjm.free.fr/pro/Struts11.html#2 This gives a considerable UML diagrammatic view of the how struts works.
-Jyothi |
| Re[2]: Confused
Author: lakiraju raj (http://www.jguru.com/guru/viewbio.jsp?EID=1325765), Jan 21, 2007 HI Nice one Really a lot of thanks to you. |
Passing values from a Collection to Action class
Hello Friends,
getter and setter functions of form bean work properly. also using the iterator tag, i am able to show values on the jsp page. but when the user changes those values and the control goes to the action class, the values are not changed inside the list.
can any one explain why, or an alternative way of doing it, or struts does not support this and has to be done thru response object.
Thanks,
Suresh.
Location: http://www.jguru.com/faq/view.jsp?EID=827781
Created: Apr 6, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Suresh Bansal (http://www.jguru.com/guru/viewbio.jsp?EID=814148
Comments and alternative answersIf the list you are displaying is represented as an array, then it should be repopulated from the request. The usual way to go about handling duplicate parameters is
private String[] items = {"",""}; public String[] getItems() { return this.item; } public void setItem(String item[]) { this.item = item; }In the form, you can then write out the array out using the iterate tag
<logic:iterate name="logonForm" property="items" id="item"> <TR> <TD>Item:</TD> <TD> <input type='text' name="item" value='<bean:write name="item"/>'></TD> </TR> </logic:iterate>HTH, Ted
| solved my hidden multibox problem
Author: Nic Daniau (http://www.jguru.com/guru/viewbio.jsp?EID=881099), Aug 6, 2002 this answer helped me solve the question I had re' passing hidden data from page to page originally captured using a multibox. if the multibox storage array (held in the action form bean myForm) is String[] items, it can be passed from JSP to JSP using: <logic:iterate id="item" name="myForm" property="items"> <input type="hidden" name="items" value="<bean:write name="item" />"> </logic:iterate>
thanks Ted! |
| Re: solved my hidden multibox problem
Author: Mel N (http://www.jguru.com/guru/viewbio.jsp?EID=1183029), Jul 1, 2004 I want to do exactly what you did ie. pass hidden data from page to page that is captured as the user ticks checkboxes. But your snippet of code does not work for me. Instead i get this error: org.apache.jasper.JasperException: No collection found Is this because I'm trying to access an array and logic:iterator tag is looking for a collection? Please help! Thanks! |
| Re[2]: solved my hidden multibox problem
Author: Davy Kamerbeek (http://www.jguru.com/guru/viewbio.jsp?EID=1289544), Mar 22, 2006 can't you just use a ArrayList and cast it to a Collection? problem solved i guess... D.Kamerbeek |
| Setter methods not being called.
Author: Gayatri S (http://www.jguru.com/guru/viewbio.jsp?EID=988940), Aug 25, 2002 Yes i am also faing the same problem. I have an arraylist inside which is another arraylist which contains (driverWidget) objects. After the jsp is displayed and user puts in the values , the driverwidget objects are not being set. I am under the impression taht the struts framework would care of this setting or do we explictly have to call the set methods ? Thanks Gayatri |
| Displaying default values and returning changed values.
Author: Michael Cardon (http://www.jguru.com/guru/viewbio.jsp?EID=1018428), Oct 28, 2002
|
| cheers Ted!
Author: Andy Morris (http://www.jguru.com/guru/viewbio.jsp?EID=1173290), May 26, 2004 You're answer was extremely easy to use, I've only been using struts for a few days and you resolved one of my biggest worries! I used dyna action forms and so just doing the struts iterate tag bit was simple. Only prob is that the fields are pre-populated with some java array gobbledegoop, hopefully find a work around for this i want them to be blank. If any1 knows how feel free to post, cheers again, andy |
Struts with EJB
Hi All,
I have a set of EJBs written, I am planning to create a prototype based on struts/MVC concept and I need to use some of the Business Logic Beaans [entity/session beasn] in to prototype implementation, please ealaborate me on this like where exactly those ejb beans be implemented/plugged in to incorporate the business logic?
Please post to me @
mushtaqm@covansys.com
Thanks & Regards,
Mushtaq
Location: http://www.jguru.com/faq/view.jsp?EID=827784
Created: Apr 6, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Mushtaq Mathur (http://www.jguru.com/guru/viewbio.jsp?EID=812586
Comments and alternative answersGenerally, EJBs, or any type of business logic, would be called from the Action. Struts brings the input in via the ActionForm bean, where it can be passed to the business tier. When the business operation completes, the Action can react to the outcome and indicate to the ActionServlet where to go next.
HTH, Ted.
| Business Delegate
Author: Matt Smith (http://www.jguru.com/guru/viewbio.jsp?EID=838953), Apr 15, 2002 Look into the business delegate design pattern and have your actions talk to the business delegate. By providing different implementations of your business delegate, Provides a great way to test your web tier without hitting your ejbs. HTH Matt |
ActionForms and Value Objects - Repetition of Code? I was very excited to start using ActionForms and Struts' forms tag library in order to lower the amount of code needed to handle all the forms in the current project I am working on, but then someone came and told me that if we created one ActionForm object for each form we had in the project, we would be repeating code since all those fields in each ActionForm object already existed in the application model's Value Objects.
I know we would be repeating code, but, in my point of view, the ActionForm objects are more connected to the View than the Model, and are a way of grouping all required data in a single place, so the Actions can access them easily.
What do you think about this? Do you think they are correct by saying the ActionForms are just a waste of time, and that they only make the application bigger and more difficult to maintain? They are proposing a solution of integrating the Value Objects with the Action Forms in some manner... which sounds too much time-consuming to me, and might not come to be a good solution at all. Less code doesn't always mean a better solution!
Please state your opinions on this.
Location: http://www.jguru.com/faq/view.jsp?EID=827787
Created: Apr 6, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Frederico Ferro Schuh (http://www.jguru.com/guru/viewbio.jsp?EID=802994
Comments and alternative answersStruts doesn't really need an ActionForm for every form -- it needs a form-bean for every form. In most cases, you can simply define one master ActionForm for your application, with all the properties it uses, and then register it under different form-bean names. This will give each form its own attribute name in the servlet contexts, so that you can have more than one form on a page without anything colliding. The Struts-Validator also goes by the attribute name, so that you can have a different formset for each form-bean, even if they all share the same ActionForm type. Worst case, you can use a base "property bean" ActionForm and subclass it with different validate methods, if needed.
While ActionForms may resemble value objects, they fill a very different purpose. They are really buffers for the HTML controls, and give you a chance to validate untrusted input before passing it along to value objects. HTTP is a wild protoocol and exposing objects designed for another purpose to a Web browser may have unforseen results. Also, HTTP is string-based, everything comes in as a string and somebody has to cope with that.
See also
http://www.mail-archive.com/struts-user@jakarta.apache.org/msg19281.html
http://www.mail-archive.com/struts-user@jakarta.apache.org/msg19338.html
http://www.mail-archive.com/struts-user@jakarta.apache.org/msg20833.htmlIn Struts 1.1 beta, a Map can be used instead of individual properties on an ActionForm. In the future, I foresee Struts developers using the same base ActionForm in all their projects, without going through the hassle of defining all these String properites.
HTH, Ted
| Code Sample
Author: khien siow (http://www.jguru.com/guru/viewbio.jsp?EID=840887), Apr 16, 2002 Ted: Where can I find an example which is using a Map in ActionForm? Thanks. |
| Re: Code Sample
Author: shimon koifman (http://www.jguru.com/guru/viewbio.jsp?EID=755537), Apr 24, 2002 The struts framework is very good for actions but very bad 4 forms and tags. its to heavy for simpple tasks as tag libreries and request handling |
| Re: Code Sample
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042), May 24, 2002 Since 1.1b
...
HTH -Ted |
| Re[2]: Code Sample
Author: Ivan Filipino (http://www.jguru.com/guru/viewbio.jsp?EID=929600), Jun 26, 2002 Hi Ted, I am having problem running this part of my jsp: Am receiving the following exception message: Do I need to set up anything in my struts-config.xml? Thanks.
|
| Re[3]: Code Sample
Author: Michael Civello (http://www.jguru.com/guru/viewbio.jsp?EID=935119), Jul 2, 2002 I think he was implying that the JSP line would be inside a <nest> ref. Looks like it doesn't know what object to access for the getter/setter. Try setting the "name" too. |
| Re[3]: Code Sample
Author: Julio Peñuela (http://www.jguru.com/guru/viewbio.jsp?EID=1127448), Nov 14, 2003 I'm getting exactly the same error: No getter method for property value(nom) of bean org.apache.struts.taglib.html.BEAN How can I solve this problem ? Thanks in advance. |
| Need help with ActionForms.
Author: Shashi MN (http://www.jguru.com/guru/viewbio.jsp?EID=1072996), Apr 3, 2003 Is it possible that in a ActionForm I have another class(created by me) variable as a member? Basically the problem is that I have a HTML table in a form and the columns of this table are all input fields. I waould like to represent each row of this table by a class instance!! This would mean that each row is represented by an instance of a class which is a member of the ActionForm!! i.e. the ActionForm would have one member as an array of objects. Does such a thing work?? has anyone tried it before? Shashikant. |
| Re: Need help with ActionForms.
Author: Anthony Tobianski (http://www.jguru.com/guru/viewbio.jsp?EID=1226580), Feb 10, 2005 A little complex, but you could maybe use the value(property) type form and do something like...
int i =0;
while( ) {
Stuff stuff = new Stuff();
stuff.setName( name );
myActionForm.put(new Integer(i).toString(), stuff);
++i;
}
On JSP maybe...
<bean:define name="current" property"value(1)">
<c:out value="${current.name}" /> < %-- or --%>
<bean:write property="current.name" />
There are propably alternative shortcuts for looping on the JSP not even touched on here.
|
| ActionForm and Value Objects
Author: Anthony Tobianski (http://www.jguru.com/guru/viewbio.jsp?EID=1226580), Feb 10, 2005 We've started using the type of ActionForm spoken of here and it really keeps the code base down on large projects. However, there is a downside you have to deal with. If you need JavaScript to do some custom validation, you have to make sure to give the field an "ID", because JavaScript thinks "value(whatever)" is an attempt to call a function. <c:out> does not like the "value(whatever)" syntax as well. This leads to a problem I'm currently having. In the middle of my page I have data retrieved from a database, which actually represents a paper form. I have any number of "quantity" properties, so set them as "quant_1", "quant_2", etc. Now, I hard coded the whole page because I know there are only 36 rows, but after doing some research have found that the page is failing due to its compiled JSP size. I know how to loop via <c:forTokens>, but not sure if I'll be able to place the <c:out> inside a <bean:write> or any other tag, i.e....
<bean:write name="form"
property="value(quant_<c:out value=\"${row}\"/>)" />
So, I have to test the above and would appreciate any thoughts on how I might process this section of my page, even a different way of storing it that would correspond to an available collection iterator on the JSP. Your ideas would be greatly appreciated! |
| Re: ActionForm and Value Objects
Author: java guy (http://www.jguru.com/guru/viewbio.jsp?EID=1138494), Apr 8, 2005 did u figure out yet ? if theres a nicer way let me know...so far i've been doing the scriplet (i know....) way . <% String foo = "prop"+i ; %> <bean:write name="bar" property="<%foo%>"/> |
handling errors in file upload with struts
I am using struts and have an upload.jsp and its associated
UploadForm.java and UploadAction.java. The jsp's form has
an enctype=multipart/form-data and contains an html:file
field to upload a file as well as a bunch of text fields
for metadata associated with the file. If an error
occurs during validation, the struts controller servlet
forwards to the jsp with error messages. The problem is
that the filepath the user specified is no longer present.
Is there a way to restore this value so the user doesn't
have to complete this field again (the other text fields remain filled in).
Location: http://www.jguru.com/faq/view.jsp?EID=877085
Created: May 13, 2002
Author: Ramon Gonzalez (http://www.jguru.com/guru/viewbio.jsp?EID=728508)
Question originally posed by Pat Marsland (http://www.jguru.com/guru/viewbio.jsp?EID=296781
Not that I know of, but here is a simple solution using JavaScriptComments and alternative answers
When a file is typed or selected using the "BROWSE" button, as soon as the field is populated, a function populates a hidden input text field with the value of the file name that was just selected. Whe you submit your form, you will have the name of the file as part of your request.getParameters("file1name") in your UploadForm.java.
The problem is that the <INPUT TYPE-"file"> will not take a default value, even if you try to force it thru JavaScript. I think this is probably a security feature in JavaScript to avoid "hidden" file uploads from your PC, but you can display the path they entered so they can cut-n-pate it into the INPUT field.
<INPUT TYPE="file" NAME="file1" SIZE="60" MAXLENGTH="60" onchange='return file1Value(this)'> <INPUT TYPE="hidden" NAME="file1name" VALUE="">
<SCRIPT LANGUAGE="JavaScript1.2"> function file1Value(thisvalue) { thisvalue.form.file1name.value = thisvalue.form.file1.value.toString(); return true; } </SCRIPT>
| Excellent solution
Author: Nagaradjane Soundiramourthy (http://www.jguru.com/guru/viewbio.jsp?EID=909398), Jun 10, 2002 My problem was, when I process the submitted form of type multipart/form-data I got the servlet error stating that I can't mix methods of getParameter with servletInputStream... I spent nearly half-a-day to find out the reason on the enctype of multipart/form-data..ultimate outcome is no solution. But after I implemented your suggestion, it worked great.. Really you have given excellent solution.... |
| Anybody could Please provide : what are steps required to configure fileupload using Struts ? in JSP/HTML
Author: jamesd JamesJacob (http://www.jguru.com/guru/viewbio.jsp?EID=970036), Jul 30, 2002 Anybody could Please provide : what are steps required to configure fileupload using Struts ? in JSP/HTML |
| Re: Anybody could Please provide : what are steps required to configure fileupload using Struts ? in JSP/HTML
Author: Ramon Gonzalez (http://www.jguru.com/guru/viewbio.jsp?EID=728508), Aug 16, 2002 The default Struts package has an example calles "Struts-upload". It is a demo WAR package on how to upload files using Struts. Install and play with it. |
| Re: Anybody could Please provide : what are steps required to configure fileupload using Struts ? in JSP/HTML
Author: Vladimir Coutinho (http://www.jguru.com/guru/viewbio.jsp?EID=891959), Jul 27, 2003 There is a example in struts (struts-upload application). See it. |
| onchange event in IE5
Author: Polly Kidd (http://www.jguru.com/guru/viewbio.jsp?EID=1038223), Dec 16, 2002 This is a great idea, but i was a little flummoxed to find that the Javascript onchange event didn't work as expected in IE5. It was called when the text in the file field was altered by typing but not when another file was selected using the 'browse' button. I got round this problem by substituting the onblur event for the onchange one: this seems to work fine, i.e. <html:file property="imageFile" onblur="return filenameValue()"/> |
| user will still select the file again
Author: Little Bee (http://www.jguru.com/guru/viewbio.jsp?EID=1273317), Nov 27, 2005 yes, the program can upload the file from the hidden field. BUT to user, he will still see blank under "BROWSE" and he will thought he has to select the file again. is there better way ? |
| Re: user will still select the file again
Author: Ramon Gonzalez (http://www.jguru.com/guru/viewbio.jsp?EID=1317642), Oct 31, 2006 Actually, the program CANNOT upload the file from the hidden field. The hidden field is simply to carry the text of the input form so it can be used in a subsequent response (in session?) so it can be referenced and the user knows what he had entered. The user has no choice and MUST re-enter the filename in the text box or use the BROWSE button. The reason is because the HTML DOM does not allow the INPUT form of type "file" object "value" property to be set thru scripting (javascript, vscript etc). The "value" property is read-only. |
| File uploading problem
Author: Mohan Kumar Govindaswamy (http://www.jguru.com/guru/viewbio.jsp?EID=1284148), Feb 15, 2006 Do we have any other alternative to over come this problem. If so, can you please, post the same. Thanks in advance.. |
| Re: File uploading problem
Author: Aris Kumara (http://www.jguru.com/guru/viewbio.jsp?EID=1289638), Mar 22, 2006 After action is being forwarded, the scope request is no longer exists. I usually use a trick for it. I use a session first, then in the forwarded page, i copy the session into the request, then invalidate the session |
JUnit with singletons
What do people think about adding
the functionality into JUnit to
enable one to load and unload singletons
during tests. This can be very helpful,
if, for example, several possible states
of the singleton that cannot be achieved
in succession need to be tested. I've
come up against it recently.
Perhaps using something like this: http://developer.java.sun.com/developer/ TechTips/2000/tt1027.html#tip3
Location: http://www.jguru.com/faq/view.jsp?EID=877088
Created: May 13, 2002
Author: Janne Nykänen (http://www.jguru.com/guru/viewbio.jsp?EID=874437)
Question originally posed by Grisha Golberg (http://www.jguru.com/guru/viewbio.jsp?EID=868035
Well, one way to allow one JUnit testcase to test a singleton class with more that one initialization params is to use a custom classloader to load your singleton; every test-method needs to instantiate a new TestClassLoader instance (a class that extends the jdk ClassLoader).
I did it like this:
public class TestClassLoader extends ClassLoader
{
public Class findClass(String name) throws ClassNotFoundException
{
byte[] b = loadClassData(name);
return defineClass(name, b, 0, b.length);
}
private byte[] loadClassData(String name)
throws ClassNotFoundException
{
InputStream stream =
getClass().getClassLoader()
.getResourceAsStream(name + ".class");
String path = null;
try
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int i;
while ((i = stream.read()) != -1)
{
bOut.write(i);
}
return bOut.toByteArray();
}
catch (FileNotFoundException ex)
{
throw new ClassNotFoundException(
"Class " + name + " could not be found from " + path,
ex);
}
catch (IOException ex)
{
throw new ClassNotFoundException(
"Class " + name + " could not be found", ex);
}
}
}
Comments and alternative answers
| Unfortunatelly I did not understand the comment.
Author: Sergey Opanasets (http://www.jguru.com/guru/viewbio.jsp?EID=392845), May 23, 2002 What difference it makes if you use custom class loader versus standard class loader?
Thank you in advance. |
| Re: Unfortunatelly I did not understand the comment.
Author: James Radvan (http://www.jguru.com/guru/viewbio.jsp?EID=873937), May 12, 2004 You can always run it as a Cactus test instead, which gets around the classloading problem. |
| Re: Unfortunatelly I did not understand the comment.
Author: Janne Nykänen (http://www.jguru.com/guru/viewbio.jsp?EID=874437), Dec 22, 2004 In case you don't wanna use cactus; by using the custom classloader you can unload the class (by throwing away the classloader used to load the singleton class). So you instantiate a new TestClassLoader for each test. |
Multiple params with html:link tag?
How to code my Struts html:link tag such that I can apply multiple dynamic parameters?
For example, I want to achieve the following:
<a href="/DeptInfo/do/ViewDept?setID=<%=deptForm.getSetID()%>&<%=deptForm.getDeptID%>">
But I only know this much in terms of coding it with a Struts tags:
<html:link forward="ViewDept" paramName="deptForm" paramProperty="setID" paramId="setID" />
How do I get the deptID param into this tag as well? (And by the way, is my syntax above correct for the html:link tag??)
If you want to add multipe params in the html:link, you have to save these params into a Map object. The Map's key are paramid and Map's value is paramProperty. And then you can do : <html:link page="ViewDept" name="xxx"/> with xxx is The name of a JSP bean that contains a Map representing the query parameters. You can see in Struts HTML tags for detail. Hope that can solve your problem. good luck, NVTComments and alternative answers
| create a HashMap array and use name attribute of html:link tag
Author: sathish kumar (http://www.jguru.com/guru/viewbio.jsp?EID=884972), May 20, 2002 hi i have a solution to ur problem.For eg u have a company list which needs to be passed as dynamic params. U can create an array of HashMap, one HashMap for each company.Each HashMap containing 2 key value pairs(one for comapnyId, other for companyName). for instance companyInfo is ur HashMap companyInfo.put(companyId,"90"); companyInfo.put(companyName,"Cognizant"); add this to the hashmap array, put the hashmap array in session In ur jsp (companyList --> hashmap array get from session) <logic:iterate name="companyList" id="company"> (ur logic:iterate will have current hashmap ) <tr> <td> <html:link forward="viewCompany" name="company"> <bean:write name="company" property="name"/> </html:link> </td> </tr> </logic:iterate>Hope this solves ur problem.I too had the same problem and i found it by hardway(spent 3hrs). regards sathish |
| Re: create a HashMap array and use name attribute of html:link tag
Author: aiuto lee (http://www.jguru.com/guru/viewbio.jsp?EID=935029), Jul 2, 2002 I sovled the problem. I had spent a lot of time on sovling this problem. I except you not to spend your time for this problem. enjoy your life... :-)
------------------
One of Solutions |
========================================================
<html:html>
....
<bean:parameter id="param1" name="param1" value="0"/>
<%
java.util.HashMap params = new java.util.HashMap();
params.put("param1", param1);
params.put("param2","param2Value");
pageContext.setAttribute("paramsName", params);
%>
<html:link page="/show.do" name="paramsName" scope="page" >show.jsp</html:link>
.....
.....
</html:html>
========================================================
-fine- |
| Re[2]: create a HashMap array and use name attribute of html:link tag
Author: Jim Downing (http://www.jguru.com/guru/viewbio.jsp?EID=975661), Aug 4, 2002 Is there an elegant way of doing this without scriptlets? Something like: - <bean:define type="java.util.Map" id="tempParams> <param id="type" value="cabbages"/> <param id="sort" value="firmness"/> </bean:define> <html:link page="/blah" paramName="tempParams"> Find the firmest cabbages </html:link> jim |
| Re[3]: create a HashMap array and use name attribute of html:link tag
Author: aiuto lee (http://www.jguru.com/guru/viewbio.jsp?EID=935029), Aug 4, 2002 Body is supposed to be empty for bean:define. I know that it is not supported to use <param> tage inside <bean:define> tag. I can not find this way in Struts's manual. Where do you get this inforamtion? -fine- |
| Re[4]: create a HashMap array and use name attribute of html:link tag
Author: Jim Downing (http://www.jguru.com/guru/viewbio.jsp?EID=975661), Aug 5, 2002 Sorry, I wasn't clear. The code snippet I wrote was a made up example of what I was hoping existed. I can't find anything sensible to replace your scriptlet. jim |
| How to Create a Map object using <bean:define> tag or any other tag in Struts
Author: praveen kumar (http://www.jguru.com/guru/viewbio.jsp?EID=992887), Sep 2, 2002 This is my code snipplet, <bean:define id="param1" name="ele" property="score"/> <bean:define id="param2" name="ele" property="color" /> <% java.util.HashMap params = new java.util.HashMap(); params.put("regno", param1); params.put("regname", param2); pageContext.setAttribute("paramsName", params); %> <html:link styleClass="link" page="/xAction.do? action=x" name="paramsName"/> I dont want to use the scriptlet. I want to put these two beans(param1 and param2) in another bean collection using struts tags, so that I could use the created bean name in my link. Could anyone pls help me in providing a solution for this. thanks Praveen |
| Re[2]: create a HashMap array and use name attribute of html:link tag
Author: Phil Spanninger (http://www.jguru.com/guru/viewbio.jsp?EID=1106267), Aug 4, 2003 Thanks for the tip! This worked great, but now i need to know how to actually pull those values out of the querystring in your Action class? I know that typically you can use the "getAttribute" method off the request, but i am using an ICL package that wraps the request into a different object and will not grant me access. Do you have any suggestions other than pulling this from the request object? Ie. could i somehow map each parameter in my mapping method within the Action class (the one being called)? Please help! |
| Re[2]: create a HashMap array and use name attribute of html:link tag
Author: w yj (http://www.jguru.com/guru/viewbio.jsp?EID=1120205), Oct 8, 2003 thanks for your code. But I am still bit confusing, hope you can spare some time for me. My problem is I got a results.jsp page which contains search results including three dynamic parameters tableName,batchId and recordId. So I 'll have <% java.util.HashMap rawSourceMap=new java.util.HashMap(); rawSourceMap.put("tableName", tableNameValue); rawSourceMap.put("batchId", batchIdValue); rawSourceMap.put("recordId", recordIdValue); pageContext.setAttribute("rsMap",rawSourceMap);%> <html:link forward="CheckRawSource.do" name="rsMap"/> My question is, depends on what tableName I got, I should direct to different jsp pages. I have tableA, tableB, tableC,etc, all tables have different fields name, so I 'll have tableA.jsp, tableB.jsp, tableC.jsp to show different raw sources. How can I do this? How do I write this in my struts-config file? Thanks, WYJ |
| Re[3]: create a HashMap array and use name attribute of html:link tag
Author: wu haixing (http://www.jguru.com/guru/viewbio.jsp?EID=1148860), Feb 24, 2004 I had solved my problem.I want to set two request parameters value by objects had stored in session,but is there has better solution?thanks a lot as follow:
<bean:define id="category" name="product" property="categoryId"/>
<bean:define id="keywords" name="item" property="attribute4"/>
<%
java.util.HashMap params = new java.util.HashMap();
params.put("category",category);
params.put("keywords",keywords);
pageContext.setAttribute("paramsName", params);
%>
<html:link name="paramsName" scope="page" page="/searchItems.do">
<bean:write name="item" property="attribute4" />
</html:link>
|
| Re[4]: create a HashMap array and use name attribute of html:link tag
Author: Kris M (http://www.jguru.com/guru/viewbio.jsp?EID=78001), Feb 27, 2004 Hi Someone had the same problem and wrote a tag library to handle this problem. Where you can pass multiple parameters through a link. The link is http://sourceforge.net/project/showfiles.php?group_id=47722 get the sources and take a look at the LinkTag and LinkParamTag roller\web\website\edit-pages.jsp has the code that utlizes this tag. If you end up using this tag, may be you can retain the copy right, after all you have to give the credit to the people who wrote it.. hope this will solve your problem.. !! Reuse of Code !! Always, Every Time, Give Credit, It makes people Happy !! enjoy kris |
| Re[5]: create a HashMap array and use name attribute of html:link tag
Author: vasanth tatta (http://www.jguru.com/guru/viewbio.jsp?EID=1166824), Jun 23, 2004 hi, with respect to the Maps I do not want to define the bean or create the map in the page Instead I thought this would work. Except for it didn't. Please point me in right direction. what I have done is written a public Map getParams() method that returns my parameters in a map. and this is in the FormBean but, when i try to access the params in the link as <html:link action="/something.do" name="params" />I get an error Cannot find bean params in any scope The bean is in the session and can get all the other stuff from that bean in the jsp except this map? I would appreciate your suggestions. regards. |
| Re[6]: create a HashMap array and use name attribute of html:link tag
Author: Pratik Das (http://www.jguru.com/guru/viewbio.jsp?EID=1188134), Aug 4, 2004 You need to have either Map by the name "params" or a bean by the name "params" in any scope with a property of type Map. In your case: 1. define a property of type Map in your formbean and populate the map with key value pairs in your formAction and put it in request or session scope.The key will appear as parameter name and key value will appear as parameter value. In your jsp use the following code: <html:link page="/flightDetail.do" name="orionForm" property="paramList"><bean:write name="orionList" property="c64" /></html:link> where orionForm is the name of the formBean having a property named paramList of type Map. Make sure the map is not null and populated. The parameters will not appear without giving any errors. |
| Re[7]: create a HashMap array and use name attribute of html:link tag
Author: Marky Goldstein (http://www.jguru.com/guru/viewbio.jsp?EID=1270121), Nov 4, 2005 Get the Source here: http://forums.m7.com/forum/viewtopic.php?t=479 Read this: You can use the JSTL core c:url tag. For example: <c:url value="/myAction.do" var="url"> <c:param name="param1" value="${user.fullName}"/> <c:param name="param2" value="${'parameter 2'}"/> </c:url> Click The smart editor for c:url allows you to select multiple parameters and enter dynamic values for them. Solution provided by R.O.S.A. and M7 |
| Yes, use C:URL
Author: Jay Yabi (http://www.jguru.com/guru/viewbio.jsp?EID=1291284), Apr 1, 2006 Marky, that's a great suggestion. Worked perfectly for me, love it. Thanks, just starting out with struts/jstl. |
| passing Multiple params
Author: venkat b (http://www.jguru.com/guru/viewbio.jsp?EID=1306432), Jul 24, 2006 Guys , I dont know what the exact solution , even i am facing the problem of sending multiple params...i tried some of codes given but they r not working ..could anybody plz give the solution for this. passing mutiple params onto action from linktag..even if they use HashMap..link tag not supporting properly. |
| Re[8]: create a HashMap array and use name attribute of html:link tag
Author: Mike M (http://www.jguru.com/guru/viewbio.jsp?EID=1314697), Oct 2, 2006 Unfortunately, if you do this the c:url way, you lose any special params that html:link adds for you automatically, like the jsessionid, and other stuff that may be necessary (including the token for when you need to do transactions that don't double submit). -m |
| Re[9]: create a HashMap array and use name attribute of html:link tag
Author: Radu G (http://www.jguru.com/guru/viewbio.jsp?EID=1343286), Jul 25, 2007 you could also do something like this:
|
| How come this page is like 1800 pixels wide???
Author: Johnson Johnson (http://www.jguru.com/guru/viewbio.jsp?EID=1321636), Dec 7, 2006 Totally rediculous for a site that suggests it's for expert developers. |
| Re: How come this page is like 1800 pixels wide???
Author: WarnerJan Veldhuis (http://www.jguru.com/guru/viewbio.jsp?EID=854798), Dec 7, 2006 Because some of the people who answered used pre-tags all around their answer instead of only around their code-fragments. This seriously messed up the page. Thanks for noticing, I liked the positive comment. I fixed it. |
| Another alternative is to not use html:link but html:form instead
Author: spam signup (http://www.jguru.com/guru/viewbio.jsp?EID=1346391), Sep 4, 2007 If all you want to do is pass information from the client to the server, then the html:form tag already encapsulates this. Just make all the fields you want hidden and then style the submit button like a link. This was far easier to do and it comes with the added benefit of being able to post and not muck up the url with obscene numbers of parameters. You can apply the style="display:inline;" attribute to the form to make it display more like a link as well. |
Using Map instead of String properties with ActionForm. How do you use a Map object with ActionForm with Struts 1.1-b1?
Mr. Husted, in a message posted on the FAQS you said:
In Struts 1.1 beta, a Map can be used instead of individual properties on an ActionForm.Could you please elaborate?
I would like to define a common ActionForm that accepts a Map which would just include the form elements and values. I would like to use this ActionForm with reusable Actions that could be used across multiple forms or JSPs. Is this possible with Struts?
Thanks.
Location: http://www.jguru.com/faq/view.jsp?EID=890992
Created: May 24, 2002
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Question originally posed by Kevin Turner (http://www.jguru.com/guru/viewbio.jsp?EID=844420
Comments and alternative answersSince 1.1b
private Map values = null; public void setValues(Map values) { this.values = values; } public Map getValues() { return this.values; } public void setValue(String key, Object value) { getValues().put(key,value); } public Object getValue(String key) { return getValues().get(key); }...
<html:text property="value(name)"/>HTH -Ted
| To clarify further...
Author: Peter Hamlen (http://www.jguru.com/guru/viewbio.jsp?EID=924276), Jun 23, 2002 Since I spent a little bit of time trying to figure this out, I thought I would try to add some clarification that I have since discovered... The key to the ability to use "maps" in your Beans comes from the the class org.apache.commons.beanutils.PropertyUtils. This very useful class extends the syntax for accessing Bean properties to include 5 different methods:
So what this means is that, if you want to get away from writing getFoo, setFoo, getBar, setBar, etc, you need to:
That's my best take on explaining this. Read the commons link, it will help a lot. |
| Re: To clarify further...
Author: rajani sarikonda (http://www.jguru.com/guru/viewbio.jsp?EID=933318), Jul 1, 2002 when i try this approach, i am getting the following error. Could you please help me in getting the solution. Root cause of ServletException javax.servlet.jsp.JspException: No getter method for property value(test) of bean org.apache.struts.taglib.html.BEAN at org.apache.struts.util.RequestUtils.lookup(RequestUtils.java:227) at org.apache.struts.taglib.html.BaseFieldTag.doStartTag(BaseFieldTag.java:220) at jsp_servlet._ui._questionnaire._jspService(_questionnaire.java:209) at weblogic.servlet.jsp.JspBase.service(JspBase.java:27) at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:213) at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:1265) at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:1622) at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137) at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120) |
| Re[2]: To clarify further...
Author: Peter Hamlen (http://www.jguru.com/guru/viewbio.jsp?EID=924276), Jul 1, 2002 Rajani, I might try the following:
|
| Re[3]: To clarify further...
Author: rajani sarikonda (http://www.jguru.com/guru/viewbio.jsp?EID=933318), Jul 1, 2002 Hi, can you please elaborate the 3rd point(Make sure you include the "name='YourBeanNameHere'" in the <HTML:Base> tag). I have written the following code in actionform class, private Map values = null; public void setValues(Map values) { this.values = values; } public Map getValues() { return this.values; } public void setValue(String key, Object value) { getValues().put(key,value); } public Object getValue(String key) { return getValues().get(key); } and accessing from jsp like this. <html:text property="value(name)"/> thanks |
| Re[4]: To clarify further...
Author: Peter Hamlen (http://www.jguru.com/guru/viewbio.jsp?EID=924276), Jul 1, 2002 My HTML tag usually looks like this: <html:text name="appForm" property="value(name)"/> You need to specify the name of the bean in the HTML:text call . Thus, I would change your code to: <html:text name="registrationForm" property="value(name)"/>(assuming that the name of your form bean is "registrationForm" -Peter |
| Re[4]: To clarify further...
Author: Ivan Filipino (http://www.jguru.com/guru/viewbio.jsp?EID=929600), Jul 3, 2002 I think you forgot to create a HashMap object. Try adding this code in your ActionForm object.
|
| Re[5]: To clarify further...
Author: Susan Weber (http://www.jguru.com/guru/viewbio.jsp?EID=1005214), Sep 27, 2002 here is how I made it work. this is /test.jsp:
here are the snippets from struts-config.xml
MapBackedActionForm extends ActionForm and has the structure described in the above thread, with generic getter and setter and a reset method that initializes the hashmap. I am still slightly boggled by the fact that I had to reference MapBackedActionForm in two places, in the .jsp source and in the form-bean descriptor, but my grasp of struts is still quite shallow. If someone can post a cleaner example, that would be a useful thing I'm sure.
|
| Re[3]: To clarify further...
Author: Ping Long (http://www.jguru.com/guru/viewbio.jsp?EID=799119), Aug 6, 2002 Hi,Peter, Any ideas how to use map inside <logic:iterate></<logic:iterate>? Example code: <logic:iterate id="desc" collection="<%=(Collection) HashMapForm.getList()%>" type="java.lang.String"> <html:text property="value(???)"/> </logic:iterate> Thanks. -Ping |
| Re[4]: To clarify further...
Author: neal ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=17737), Dec 20, 2002 Did you find an answer for this? If so kindly share. |
| Re[4]: To clarify further...
Author: Brad Schneider (http://www.jguru.com/guru/viewbio.jsp?EID=1089492), Jun 1, 2003 I got the following to work: <logic:iterate name="listRightsForm" property="rights" id="RightsView"> |
| Re[2]: To clarify further...
Author: java maniac (http://www.jguru.com/guru/viewbio.jsp?EID=1059488), Feb 25, 2003 i got the same problem but when i changed the jsp to values() rather than value() it worked. |
| Re[2]: To clarify further...
Author: Thomas Poulet (http://www.jguru.com/guru/viewbio.jsp?EID=1101382), Jul 15, 2003 Hi Rajani, I am exactly in your situation,(one year later,) and I was wondering if you finally found out the cause of your problem... I read a lot of useful things on different forums (I am new in Struts), but unfortunately I still have this : "javax.servlet.ServletException: No getter method for property value(test) of bean org.apache.struts.taglib.html.BEAN". Would you have any idea to help me ?
Thanks. Thomas. |
| Re[3]: To clarify further...
Author: Tony Cao (http://www.jguru.com/guru/viewbio.jsp?EID=1182538), Jun 29, 2004 getter and setter functions are case sensitive. For example: // variables String userid; String password; // getter setter public String getUserid() { return this.userid; } public void setUserid(String u) { this.userid = u; } public String getPassword() { return this.password; } public void setPassword(String p) { this.password = p; }
Hope this help. |
| Re[4]: To clarify further...
Author: Tony Cao (http://www.jguru.com/guru/viewbio.jsp?EID=1182538), Jun 29, 2004 getter and setter functions are case sensitive. For example: // variables String userid; String password;
// getter setter
public void setUserid(String u) { this.userid = u; } public String getPassword() { return this.password; } public void setPassword(String p) { this.password = p; }
Hope this help.
|
| Re[3]: To clarify further...
Author: Rick Herrick (http://www.jguru.com/guru/viewbio.jsp?EID=1195078), Aug 25, 2004 Hey, Thomas! I've been struggling with this one all day and finally got it figured out. You can check out some sample code I wrote up that demonstrates the solution. Note that this works with the standard Struts 1.1 release (at one point I thought I needed to upgrade the commons-beanutils.jar, but I didn't). |
| Re[4]: To clarify further...
Author: grace goona (http://www.jguru.com/guru/viewbio.jsp?EID=1203569), Oct 5, 2004 where is the sample code you wrote up? |
| Re[5]: To clarify further...
Author: yayo yayez (http://www.jguru.com/guru/viewbio.jsp?EID=1222082), Jan 19, 2005 I use this to avoid the use of scriplets: protected Map cursos = new HashMap(); public Map getCursos(){return new HashMap(cursos);}  c; ... <!-- inside the iterate of the property 'cursos' --> <html-el:hidden property="indexedCurso('${pageScope.i}').cursoId" /> And it workz!! |
| Re: To clarify further...
Author: Alex Apollonsky (http://www.jguru.com/guru/viewbio.jsp?EID=1296649), May 12, 2006 I'm trying to use this approach with html:select where multiple=true, no success so far (exposed getter and setter with String[] param). Anybody made it working? -A |
| Re[2]: To clarify further...
Author: krishan rathi (http://www.jguru.com/guru/viewbio.jsp?EID=1303178), Jul 5, 2006 hi alex you can use it this way using indexed properties <logic-el:iterate indexId="bookctr" id="booktype" name="booktypes">
where booktypes is a list of booktype bean which have Can anybody suggests how i can combine both mapped |
Struts Tip #1 - Use an ImageButtonBean to represent an image button.
Location: http://www.jguru.com/faq/view.jsp?EID=893423
Created: May 27, 2002
Modified: 2002-09-06 04:52:16.755
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersAn endless source of aggravation is the HTML input image element. The specification says that browsers should treat this control like an image map. Unlike other buttons, it does not submit a string representing the button's label, it submits the X and Y coordinates. If you look at the HTTP post for an image button, you'll see it looks something like this
myImageButton.x=200 myImageButton.y=300For most other controls, a Struts developer can create a simple String property to represent the element. This clearly won't work with an image button, because it submits two "dotted" properties instead of a simple "name=value" entry like other elements.
Happily, Struts allows an ActionForm to contain, or nest, other JavaBeans, and will automatically populate the beans using the same syntax as the image element. (What a co-inky-dink!)
To represent an image input element in your ActionForm, say what you mean, and use an ImageButtonBean to capture the X and Y parameters.
public final class ImageButtonBean extends Object { private String x = null; private String y = null; public String getX() { return (this.x); } public void setX(String x) { this.x = x; } public String getY() { return (this.y); } public void setY(String y) { this.y = y; } public boolean isSelected() { return ((x!=null) || (y!=null)); } } // End ImageButtonBeanNote that we've included a helper method on this bean, isSelected(). This just returns true if either the x or y property is not null. If both are still null, then isSelected() returns false.
Here's how you could declare two ImageButtonBeans on an ActionForm.
// .. private ImageButtonBean logonButton = new ImageButtonBean(); public void setLogonButton(ImageButtonBean button) { this.logonButton = button; } public ImageButtonBean getLogonButton() { return this.logonButton; } private ImageButtonBean cancelButton = new ImageButtonBean(); public void setCancelButton(ImageButtonBean button) { this.cancelButton = button; } public ImageButtonBean getCancelButton() { return this.cancelButton; } // ...The next question will be "OK, which button did they push?", so let's define another helper method on the ActionForm to tell us.
public String getSelected() { if (getLogonButton().isSelected()) { return Constants.LOGON; } if (getCancelButton().isSelected()) { return Constants.CANCEL; } return null; // nobody home }In an Action, determining which button is pressed is then a simple matter of asking the form what was selected.
String selected = ((myForm) form).getSelected(); if (Constants.CANCEL.equals(selected)) ...Of course selected doesn't need to be a String; it could be an int, a custom type to represent your API functions, or even the name of another method for use with a DispatchAction.
Using "API helper methods" on ActionForms, as we did with getSelected(), is a very useful technique. We'll use it again in Tip #2, when we discuss the standard Dispatch Actions.
HTH, Ted.
---
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| multiple image buttons
Author: joy joy (http://www.jguru.com/guru/viewbio.jsp?EID=1027752), Nov 19, 2002 Suppose I have two image buttons in a form
<html:image srcKey="image.next" align="center"/>
Any reply are appreciated. Joy |
| Make sure "value" isn't set
Author: Michael Rush (http://www.jguru.com/guru/viewbio.jsp?EID=1140634), Jan 22, 2004 Make sure that within the html:image tag that "value" isn't specified. If so, some browsers (Firebird is an example) submit *3* params instead of 2, so you end up with request parameters like: loginButton: Login When that happens, BeanUtils.populate() will spit out the following: java.lang.IllegalArgumentException: argument type mismatch If omitting the value isn't possible, the following workaround works: original:
public void setCancelButton(ImageButtonBean cancelButton) {
this.cancelButton = cancelButton;
}
new:
public void setCancelButton(Object cancelButton) {
if (cancelButton instanceof String) return;
this.cancelButton = (ImageButtonBean) cancelButton;
}
|
| How to reset the submit action in Action
Author: Anuj Upadhyay (http://www.jguru.com/guru/viewbio.jsp?EID=243531), Mar 11, 2004 I have implemented the image button as defined and all was working fine till I had to process a now UI action which I define as a separation action in the struts-config file. At first i get the button click, no UI event in my case, I forward the call to the relevant action class. i.e. in the /mainAction mapping
if(form.getA().pressed()){
//mapping is of type ActionMapping
return (mapping.findForward("resetDate"));
}
The call get forwaded to the action I defined for /resetDate action mapping. now in resetDate action i do some porcessing and finally forward back the to /mainAction (definded in the struts-config).
return (mapping.findForward("mainAction"));
I may be doing something wrong but I want to get back to my calling action.
The called does get back to the /mainAction but the implementation finds that button A was pressed and then i run into a never ending look. I have tried various ways to set the X & Y values to null but that does not hely either. Can you suggest of a way to do this. One way I found was to have the processing I was doing in /resetDate in the /mainAction, but I would like to have this implementation separate as a separate action mapping.
What are your comments on the same.
|
Struts Tip #2 - Use DispatchAction to organize related operations
Location: http://www.jguru.com/faq/view.jsp?EID=897290
Created: May 30, 2002
Modified: 2002-09-06 04:51:29.193
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersAny software application is defined by the things it can do for you. In a Struts Web application, the things an application does is usually defined by its action-mapping elements. An action-mapping is designed to be the target of an HTML form, and is often used with hyperlinks as well.
Each action-mapping can specify a Struts Action class as its handler. In larger applications, developers can find themselves managing dozens or even hundreds of Action classes.
In practice, many of these Action classes handle related operations, often evidenced by their name. A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action.
A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.
<html:hidden property="dispatch" value="error"/>
<SCRIPT>function set(target) {document.forms[0].dispatch.value=target;}</SCRIPT>
<html:submit onclick="set('save');">SAVE</html:submit>
<html:submit onclick="set('create');">SAVE AS NEW</html:submitl>
<html:submit onclick="set('delete);">DELETE</html:submit>Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field.
String dispatch = myForm.getDispatch();
if ("create".equals(dispatch)) { ...
if ("save".equals(dispatch)) { ...The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic. The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway.
To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to create methods like this
public ActionForward create(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...
public ActionForward save(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this:
<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="dispatch"/>If you wanted to use the property "o" instead, as in o=create, you would change the mapping to
<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="o"/>Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each?
You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtualy impossible.
If you prefer not to use JavaScript buttons, you can use the DispatchLookup Action instead. This works much like the DispatchAction, but requires more setup. We'll explore the DispatchLookup Action in Tip #3.
HTH, Ted.
---
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| How do we validate the errors?
Author: Asha Augustine (http://www.jguru.com/guru/viewbio.jsp?EID=1156829), Mar 23, 2004 Hi Ted. How do we validate the errors when using DispatchAction using validator framework, if the submitting page and resultting page are same, but with different argument? For example, if I submit from /login.do?page=page1 and the action is /login.do?page=page2. How do I write the action in Struts config ? |
| input vs. buttons
Author: Mark Diggory (http://www.jguru.com/guru/viewbio.jsp?EID=1180720), Jun 22, 2004 Well, the good news is that "button" tags in xhtml support the button value and its presented text being quite different so even this is possible <button name="dispatch" value="doIt">My Button</button> This makes using the submit button all the more easier. -Mark |
| Re: input vs. buttons
Author: Binay Warrier (http://www.jguru.com/guru/viewbio.jsp?EID=1181171), Jun 27, 2004 But then how will "My Button" be able to behave like a submit button? Isnt it necc. that it has to be of type input? so that inside the action, i can get the "value" attribute for the button name. I am a newbie to this, so I dunno if I am going wrong here... |
| Which is better: ActionForm or Dispatch ActionForm
Author: Charu Goyal (http://www.jguru.com/guru/viewbio.jsp?EID=1285075), Mar 10, 2006 Hi Ted, Would you please list me the differences between a normal ActionForm and Dispatch ActionForm. I am currently using ActionForm and pretty comfortable with it. But I wonder if using DispatchAction can make things simpler and provides some additional capabilities. Any suggestion would be appreciated. Thanks, Charu Goyal |
Struts Tip #3 - Use LookupDispatchAction for a JavaScript-free dispatch
Location: http://www.jguru.com/faq/view.jsp?EID=900642
Created: Jun 3, 2002
Modified: 2002-09-06 04:50:22.724
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersMany forms can be put to multiple uses. The fields we need to create a record are usually the same fields we use to update a record. Likewise, the same page can usually used to identify a record to delete, copy, or update a record.
A DispatchAction (see Tip #2) is a convenient way to collect related operations like this into a single Struts Action class. A field in the request identifies the operation, and so all the developer has to do is get the right value into the field. The simplest way to do this is to label the buttons for the operation, and give each button the same name. But that ties the presentation label to the business operation and confounds localization.
As an alternative, most developers use a JavaScript attached to the button to update the dispatch field, which in practice works quite well. If JavaScript is not enabled, the submit fails gracefully, and in practice most applications do rely JavaScript for essential operations.
If JavaScript is not an option, another good alternative is the LookupDispatchAction [
org.apache.struts.actions.LookupDispatchAction]. This object is a little more work to setup that the original DispatchAction, but lets you use this technique without using JavaScript as a crutch.As with the DispatchAction, the first step is to indicate the name of the dispatch parameter in the action-mapping element. In this case the parameter will the name given to each of the buttons, rather than a hidden field. Let's just call our buttons "submit", which is the default name the html:submit tag will use.
<action path="/test"
type="org.example.MyAction"
name="MyForm"
scope="request"
input="/test.jsp"
parameter="submit"/>In our JSP, we can refer to the buttons in the usual way
<html:form action="/test">
<html:submit>
<bean:message key="button.add"/>
</html:submit>
<html:submit>
<bean:message key="button.delete"/>
</html:submit>
</html:form>Later, when the user selects a button, the form will pass the submit parameter, along with whatever message is Struts finds for "button.add" or "button.delete" in the resource bundle. In a localized application, this message could vary by the user's selected locale.
Using the conventional DispatchAction, this approach would problematic, since there would have to a Java method named for each message, and not all the messages might valid Java identifiers. This is where the magic of the LookupDispatchAction comes into play.
When you create your LookupDispatchAction subclass, along with the methods for the dispatch operations (see Tip #20) you must also implement a getKeyMethodMap method. This is a "hotspot" that the LookupDispatchAction will call.
Here's an example of the methods you might declare in your subclass:
protected Map getKeyMethodMap(ActionMapping mapping,
ActionForm form,
HttpServletRequest request) {
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
return map;
}
public ActionForward add(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// do add
return mapping.findForward("success");
}
public ActionForward delete(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
// do delete
return mapping.findForward("success");
}Internally, the base action will lookup the messages for button.add and button.delete, and match those against the submit parameter. When it finds a match, it will then use either "add" or "delete" to call the corresponding methods.
So while the LookupDispatchAction means adding an extra method to your Action, it lets you skip putting a JavaScript in your form.
Both the DispatchAction and LookupDispatchAction are an excellent way to streamline your Struts action classes, and group several related operations into a single umbrella action.
So, how many dispatch actions do you need? Can you use a dispatch action to collect everything into a single action?
Most often not. In practice, you can easily use one dispatch action for any forms that share a common validation. Sharing a dispatch action between different form beans, or form beans that are validated differently, can start to make things harder rather than simpler. But the use of a dispatch action can easily half or quarter the number of action classes in most Struts application.
HTH, Ted.
Credits. The LookupDispatchAction was originated by Erik Hatcher, one of Struts many volunteer contributors. The examples used in this tip relied heavily on Erik's documentation. (Yeah reuse! Yeah JavaDocs!)-----
Struts Tips are released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| LookUpDispatchAction and indexed buttons.
Author: Jaakko R (http://www.jguru.com/guru/viewbio.jsp?EID=1116356), Oct 7, 2003 I have a form that has 2 submit buttons / line, edit and delete. Form can have 0-n lines (I'm iterating a collection called properties) so what would be the best way to submit the form if I have to pass one value (property key for databaseconnection) and the required action to perform the required operation. <logic:iterate id="property" name="properties"/><!-- property.key & other info here (all indexed) --> <html:button property="action" indexed="true"> <bean:message key="button.edit"/> </html:button> <html:button property="action" indexed="true"> <bean:message key="button.edit"/> </html:button> </logic:iterate> |
| Alternative to using LookupDispatchAction
Author: John Hughes (http://www.jguru.com/guru/viewbio.jsp?EID=1179286), Jun 16, 2004 LookupDispatchAction provides a lot of flexibility for multi-lingual applications but it is kind of cumbersome in that you have to have to implement additional methods set up for each type of "action" your form needs to take. Here is an alternative: Example action mapping: <action path="/test" type="org.example.MyAction" name="MyForm" scope="request" input="/test.jsp"/>Example JSP block:
<html:form action="/test">
<html:submit>
<bean:message key="button.add"/>
</html:submit>
<html:submit>
<bean:message key="button.delete"/>
</html:submit>
</html:form>
Import MessageResources class in your Action:
import org.apache.struts.util.MessageResources;Example Action execute method:
public ActionForward execute(ActionMapping map, ActionForm reqForm, HttpServletRequest request, HttpServletResponse response){
MyForm form = (MyForm) reqForm;
//****************************************************************************
//Gets a specified 'key' value from the resource bundle based on the current Locale.
//This comes in handy when needing to compare a button label to the same 'key'
// value when using a form with multiple submit buttons.
MessageResources resources = this.getResources(request);
String sAddAction = resources.getMessage(this.getLocale(request), "button.add");
String sDeleteAction = resources.getMessage(this.getLocale(request), "button.delete");
//****************************************************************************
if (form.getAction().equals(sAddAction)){
//pass control to the proper business logic method for the add action
}
else if (form.getAction().equals(sDeleteAction)){
//pass control to the proper business logic method for the delete action
}
return map.findForward("success");
}
Why we chose this particular technique:We wanted to keep our "controller" layer as light as possible. Because of this all of our business logic is farmed out to EJBs. So, each action method would have been indentical except for a few lines of code. We chose this technique to simplify our code rather than going with the LookupDispatchAction. |
| Re: Alternative to using LookupDispatchAction
Author: vijai kanth (http://www.jguru.com/guru/viewbio.jsp?EID=1228316), Feb 21, 2005 i have tryed this technique but i get an error message of "cannot find symbol of getAcion()" what can i do |
| Correction to: Alternative to using LookupDispatchAction
Author: John Hughes (http://www.jguru.com/guru/viewbio.jsp?EID=1179286), Jun 16, 2004 JSP code for the example should be:
<html:form action="/test">
<html:submit property="action">
<bean:message key="button.add"/>
</html:submit>
<html:submit property="action">
<bean:message key="button.delete"/>
</html:submit>
</html:form>
|
| Well, what if I need javascript
Author: MC Moisei (http://www.jguru.com/guru/viewbio.jsp?EID=1264757), Sep 28, 2005 The LookupDispatchAction is great but sometime I need to use javascript. For example I have a huge form that would require to lookup some data javascript's onblur() In that case how do I simulate that I've clicked on the right button ? Thanks, MCAffordable Stock Photography http://www.goodstockimages.com |
| Re: Well, what if I need javascript
Author: bedek bedek (http://www.jguru.com/guru/viewbio.jsp?EID=1331756), Mar 21, 2007 Hi, I'm using also LookupDispatchAction in my action, but unfortunately I need (I suppose at least) JavaScript simultaneously. My current situation: - my class extends LookupDispatchAction - this class has lot of methods which are called (of course) by getKeyMethodMap() My target: I need button to update part of form, unfortunately the label on the button must be different then the key which will be used in getKeyMethodMap() My solution - _which_is_not_working_: <html:button property="method" onclick="setLabelForGetKeyMethodMap('button.update')" BUTTON_LABEL_WHICH_IS_NO_APPROPRIATE_FOR_A_LABEL </html:button> <script type='text/javascript'> function updateStatus(method) { document.PuForm.method.value = method; document.PuForm.submit(); } </script> |
| Re[2]: Well, what if I need javascript
Author: bedek bedek (http://www.jguru.com/guru/viewbio.jsp?EID=1331756), Mar 21, 2007 Sorry, small fix: <html:button property="method" onclick="setLabelForGetKeyMethodMap('button.update')"> BUTTON_LABEL_WHICH_IS_NO_APPROPRIATE_FOR_A_LABEL </html:button> |
| Re[3]: Well, what if I need javascript
Author: bedek bedek (http://www.jguru.com/guru/viewbio.jsp?EID=1331756), Mar 21, 2007 To be clear: My idea is to set manually method "key" but after clicking my button the action is executing its method called "unspecified" - so the "key" is not set at all - how to do it ? |
Struts Tip #4 - Formatting output with MessageResources
Location: http://www.jguru.com/faq/view.jsp?EID=915891
Created: Jun 17, 2002
Modified: 2002-11-09 19:41:09.511
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersA common requirement of the presentation layer is to format information in a human-friendly way. While a numeral rendered as 1000000 works well for the software, most humans can't turn that data into information at a glance. Humans expect a numeral to be rendered as 1,000,000 - which they can interpret at a glance to be the value one million.
At least to Americans.
People in other countries might find the name rather strange, since it includes two decimal points, or what an American would render as 1.000.000.
Since many Struts applications are localized, this are important issues. When a page in a Struts application renderes a number, or a date, or a percentage, it should be able to do so according to each user's locale.
Struts already has localized messaging built-in, which most developers use for error messages, prompts, and field label names. A Struts applications refers to messages like this using a symbolic key, which is used to retrieve the actual messages from the Struts application resource bundle. The messages can also be used as templates, and the application can pass custom values to them at runtime. Often, there is a default template for an entire class of message, and the field name or other value is merged into the static text at runtime. Each locale can have it's own resource properties file, which
Now, it's important to note that Struts didn't invent any of this. Resource bundles, message templates, locales, and the rest of it are all part of the Java internationalization framework. Struts makes Java i18n an intregal part of its own framework, and provides support classes making it easier to use. But the core functionality is provided by the Java internationalization framework.
Including the abilty to apply formatting to a value a runtime.
Most message templates are created by just indicating the placeholder, like
ordering.authorized.range.staff=Staff is only authorized to requisition supplies that cost less than ${0}It then becomes the application's responsiblility to supply whatever string is needed to replace {0}, which will be inserted into the message template, as-is.
However, you can also pass more than one parameter as the placeholder, and also include one of the standard message format classes: number, currency, percent - along with a default mask. This means you can just as easily render the template as
ordering.authorized.range.staff=Staff is only authorized to requisition supplies that cost less than {0,currency}which will insert the appropriate thousands-delimter or decimal-separator for the user's locale. This example would also insert the monetary symbol for the user's country. If everything should be expressed in a single currency, then you'd use number instead
ordering.authorized.range.staff=Staff is only authorized to requisition supplies that cost less than ${0,number} USDThe same technique can be applied to dates and percentages. See the Java Internationalization Tutorial's page on the MessageFormat class for more
While the Struts application resource bundle is most often used when generating error messages, the <bean:message> tag can be used to access message templates throughout your application, and pass the replacement parameters at runtime to generate a customized display.
Here's the same example message coded for <bean:message>
<bean:message key="ordering.authorized.range.staff" arg0='<%= config.getStaffAuthAmnt() %>'/>where there is a bean in some scope named "config" that can return the amount in question.
HTH, Ted.
-----
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Struts in Action and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| How to format a Date, using this?
Author: Calle Sollander (http://www.jguru.com/guru/viewbio.jsp?EID=2642), Jul 5, 2002 Hello! I'm abit new to struts so forgive me if this is stupid. I want to show a Date diffrently in diffrent Locales so I put departureDate=Depaturedate: {0,date,long} in my properties file. Then I realized that the "bean:message" only takes Strings as arguments. Can you explain how to format the Date? Before reading this tip I had solved it by making my own customtag that handled the formating. Thanks in advance for any help! Regards, Calle |
| Re: How to format a Date, using this?
Author: Erik Godding Boye (http://www.jguru.com/guru/viewbio.jsp?EID=985651), Aug 20, 2002 It seems impossible to do this since the bean:message tag require String as arguments. I would would suggest the Struts people to change the type of the arguments to Object (as expected by the MessageFormat class that is actually used from whitin the Struts classes). For now you could use the i18n taglib from Apache taglibs project - which uses Object for argument. Regards, Erik |
| Example doesn't work
Author: Jason Marshall (http://www.jguru.com/guru/viewbio.jsp?EID=1007649), Oct 3, 2002 When I run the number format example in this code, I get an error: Cannot format given Object as a NumberThe most likely conclusion from this is that number formatting doesn't actually work in Struts 1.0. Is that correct? |
| I18N'd arguments
Author: Josh Marquart (http://www.jguru.com/guru/viewbio.jsp?EID=30693), Jan 16, 2004 Here's a strange conundrum. I want to use
where
That works fine if I do:
or
But what if arg0 has to be I18N'd and I don't want to use scriptlets? I can't do this, can I?
Or do I have to rely on the fmt: tag? |
| Re: I18N'd arguments
Author: Holm Krieger (http://www.jguru.com/guru/viewbio.jsp?EID=1334581), Apr 20, 2007 No you can´t the last one is not allowed according to TLD the bean tag must be empty. |
Struts Tip #5 - Use coarse-grained ActionForms
Location: http://www.jguru.com/faq/view.jsp?EID=915895
Created: Jun 17, 2002
Modified: 2002-09-06 04:43:12.545
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersThe biggest hassle for any Struts developer can maintaining the #@$!% ActionForms. The ActionForm provides several important services to an application, since it is
- a firewall,
- a buffer for the HTML controls, and
- a mutable transfer object.
As a firewall it keeps untrusted input from passing directly into your application. As a field buffer, it stores new input so it can verified before it is passed to more trusting parts of your application, As a mutable transfer object (fka value object), the ActionForm provides an extensible container where data can collected and passed in a batch to one or more business or resource layer objects.
But, in practice, you usually need a different form-bean for each HTML form in your application. This makes it easy to store the data for each form under its own attribute, and to fine-tune the validation for each form.
Hey -- what's that about form-beans? I thought we were talking about ActionForms?
This is an important distinction. Each HTML form typically needs its own form-bean, but a form-bean is not an ActionForm. A form-bean identifies which ActionForm to use, in the same way an action-mapping identifies which Action class to use. Many Struts developers share Actions between action-mapping, but tend to forget that you can share ActionForms between form-beans too.
While ActionForms are vital objects, they are not subtle. Typically, they are a pure data-only JavaBean, with nothing but accessors and mutators. Occasionally, there is a helper method to transform data from one type to another, but even those are a simple wrappers around standard library functions. With the Struts-Validator, most ActionForms don't even need to subclass validate(). All that's needed is to define a formset for each form-bean, or attribute, that needs validation.
So, why bother with more than one ActionForm class? The form-bean determines the runtime attribute name, and therefore the formset the Struts-Validator will use. Neither the validator nor the autopopulation utilities care if there are more properties a form than are used with a given request. And, null properties consume fewer resources that instantiating yet another class. So why not just put all the application's properties together in a single ActionForm?
Worst case, you can define a base ActionForm with all the properties you need, and subclass to provide any custom validations. Meanwhile, by aggregating your application's properties into a single ActionForm, several key benefits are realized.
- Better Manageability. Implementing ActionForms as fine-grained containers results in a large number of objects in the application, many of which have redundant properties. This consumes both system and developer resources, and can negatively impact application performance and long-term maintenance.
- Relationships are preserved. Most HTML forms represent, in part, a SQL view, which includes properties from several different tables. If an ActionForm contains properties for all the fields, any relationship can represented.
- Schema independance. When ActionForms are fine-grained, each ActionForm usually represents a single row in a database. This ties the presentation layer to the database schema, rather than to the greater business model. When the schema changes, fine-grained ActionForm objects may also need to changed. Coarse-grained ActionForms change less frequently, since if a field is moved from one table to another, it will still available the form. If a field is introduced or renamed, only one ActionForm object needs to adjusted.
In a larger application being developed by a team, you may want more than one ActionForm for the application (even if you don't "need" one). There may, for example, be one ActionForm each each major segment of the application being handled by a smaller group or pair of programmers within the team. The important thing is to try and group together all the properties that will be used together, so that they are not continually re-defined throughout several related classes. ActionForms are objects too and can be subclassed like any other object.
So the next time you need an ActionForm to go with a new form-bean, think twice before creating a new class. Maybe you already have one you can reuse.
HTH, Ted.
-----
For more about aggregate entities in J2EE applications, see < http://developer.java.sun.com/developer/restricted/patterns/AggregateEntity.html >.
Struts Tips are released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| Hassle
Author: Nick Pellow (http://www.jguru.com/guru/viewbio.jsp?EID=920830), Jun 20, 2002 "The biggest hassle for any Struts developer can maintaining the #@$!% ActionForms."
Does this not sound alarm bells that ActionForms are just not ideal. |
| How 'bout an example?
Author: Daniel Kehoe (http://www.jguru.com/guru/viewbio.jsp?EID=940015), Jul 6, 2002 I like the concept but I'm not sure how to share one ActionForm between multiple web pages. Usually you specify the ActionForm to instantiate when input comes from a particular page:
<action path="/mypath"
type="someAction"
parameter="action"
scope="request"
name="someForm"
input="/somepage.jsp"
validate="false">
</action>
How does a page know what ActionForm to use? The
<jsp:useBean> tag? Or Struts <bean:define> tag? Sure it's a newbie question, but I'd like to see where in the elusive struts documentation the proper practice is explained. |
| Re: How 'bout an example?
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042), Sep 6, 2002 The name attribute in the snippet refers to a form-bean element that in turns specifies the ActionForm class. The ActionForms tend to be used by more than one mapping, and so they are encapsulated under their own block. By default, the name is also used as the attribute name in the servlet context. So this saves specifying a logical name more than once. HTH, -Ted. |
Struts Tip #6 - Use an array to capture multiple parameters
Location: http://www.jguru.com/faq/view.jsp?EID=915898
Created: Jun 17, 2002
Modified: 2002-09-06 04:42:13.652
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersIn a perfect universe, our users would happily subscribe to the One True Workflow. In every case, we could list some records, select a record to view or edit, and list some records again. But in real life, users often want to do unreasonable things, like edit 17 records at once.
Usually, we'd already have a business procedure for saving one copy of the record. Perhaps something like this
String key= form.getKey();
String category = form.getCategory();
db.updateCategory(new Integer(key),category);A very simple way to convert this to "multiple use" would to do something like this:
String[] key = form.getKey();
String[] category = form.getCategory();
for (int i=0; i<category.length; i++) { db.updateCategory(new Integer(key),category); }Depending on what the db object did behind the scenes, and the scale of the application, this code fragment could too simple to be efficient, but for many small intranet applications, it could work just fine.
Of course, that still leaves the problem of where to get an array of keys and a matching array of categories.
Happily, HTTP supports submitting multiple parameters of the same name, and Struts will autopopulate a String array as easily as a single String. So, to represent the "multi-use" business operation in an ActionForm, we can do this:
private String[] key= null;
public String[] getKey() { return this.key; }
public void setKey(String[] key) { this.key = key; }
private String[] category = null;
public String[] getCategory() { return this.category; }
public void setCategory(String[] category) { this.category = category; }Which is just the single-record version but with
String[]instead ofString.In the JavaServer Page, the only real trick is to refer to the iterate id in the html form tags.
<TABLE><html:form action="/item/StoreCategory">
<logic:iterate name="RESULT" property="iterator" id="row">
<TR>
<TH>name</TH>
<TH>category</TH>
</TR>
<TR>
<TD><bean:write name="row" property="name"/></TD>
<TD><%-- REMEMBER TO SPECIFY THE ITERATE ID AS THE NAME --%>
<html:select name="row" property="category">
<html:option value="ART">Art</html:option>
<html:option value="AUT">Automotive</html:option>
<%-- ... --%>
</html:select>
<%-- REMEMBER TO SPECIFY THE ITERATE ID AS THE NAME --%>
<html:hidden name="row" property="key"/>
</TD>
</TR>
</logic:iterate>
<TR>
<TD colspan="2" align="right">
<html:submit/>
</TD>
</TR>
</html:form>
</TABLE>Now when they submit the form, it will include several
category=XYZ&key=123pairs in the request. Struts will convert the category and key entries into individual arrays, and the arrays can be used with your business objects to make the appropriate update.HTH, Ted.
-----
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| iterator?!?
Author: Kevin Yuen (http://www.jguru.com/guru/viewbio.jsp?EID=352701), Jun 19, 2002 Thanks Ted for such a good Struts Tip!! I am in need for such solution! However, I do not fully understand the solution mentioned in the article. In the <logic:iterate>, you mentioned a property called "iterator" and the name "RESULT", what are they? I cannot find them in other places in the article. Do you mind to explain them in more details? In particular, do we need to implement some kind of iterator here? Thanks. |
| Re: iterator?!?
Author: deeje cooley (http://www.jguru.com/guru/viewbio.jsp?EID=931933), Jul 2, 2002 I am also appreciative of this tip, but am struggling to understand how to actually implement it within my project. Any follow up would be most helpful! peace deeje |
| Re: iterator?!?
Author: Yves Remels (http://www.jguru.com/guru/viewbio.jsp?EID=806386), Jul 3, 2002 As far as I understood, we have to define and populate a bean which has a getIterator() method and contains attributes for all parameters needed. This collection substitutes "RESULT" in example. In this case the ActionForm is only used for posting and validating data and is not used to retrieve the parameters into the jsp. Y.R. |
| Using array to capture multiple parameters
Author: sameena tabassum (http://www.jguru.com/guru/viewbio.jsp?EID=920868), Jun 20, 2002 Thanks for the tip you had mentioned.I require to have a multiple input fields with the same name which is populated within a loop.Iam able to capture the values in a String array,but when I get an error in the page I need to repopulate the screen with same error values.In that case,Iam facing the problem like I only get reference of array elements in the textfield.How can I populate the values back to the same screen with error?? Thanks, Sameena. |
| Re: Using array to capture multiple parameters
Author: Ralph Brandes (http://www.jguru.com/guru/viewbio.jsp?EID=928554), Jun 26, 2002 I have the same problem. Did you find a solution ? Thanks in advance Ralph |
| Re: Using array to capture multiple parameters. My solution
Author: Ralph Brandes (http://www.jguru.com/guru/viewbio.jsp?EID=928554), Jun 27, 2002 i found a solution :
Form :
private String[] owner = new String[100];
public String getOwner (int x) {
return owner[x];
}
public void setAbsetzHASBETRAG (int num, String owner) {
this.owner[num] = owner;
}
Form-Validation :
for (int i = 0; i < owner.length; i++) {
String errorFeld = "owner" + i;
...
errors.add(errorFeld, new ActionError("error.input.format"));
...
}
Jsp :
<% int count = 0;%>
<logic:iterate name="RESULT" property="iterator" id="row">
<bean:write name="row" property="foo"/>
<html:text property='<%= "owner[" + count +"]" %>' size="16" maxlength="16"/>
<html:errors property='<%= "owner" + count %>'/>
<% count++ ;%>
</logic:iterate>
Hope it helps. But if there is a better solution, i would be happy to see it.
Ralph |
| Re[2]: Using array to capture multiple parameters. My solution
Author: Carole L. (http://www.jguru.com/guru/viewbio.jsp?EID=994730), Sep 5, 2002 Ralph, I have tried your solution (without the validation stuff) but I get an error when I try to display my JSP: Exception thrown by getter for property owner[0] of bean org.apache.struts.taglib.html.BEAN Did I miss something? |
| Generated ActionForm and JSPs
Author: gilles vandaele (http://www.jguru.com/guru/viewbio.jsp?EID=938970), Jul 9, 2002 Could you please explain the 'RESULT' and the 'iterator' you used in there: logic:iterate name="RESULT" property="iterator" id="row" How do I separate the values of the iteration and the values of the bean. I need to capture the values of the bean in an array (generated properties), but the default values and the layout atributes are from the Action servlet. The Action servlet generate my jsp and the ActionForm is generic and capture the values of the bean into an array. Any further ideas? Tx. |
| Re: Generated ActionForm and JSPs
Author: john Walsh (http://www.jguru.com/guru/viewbio.jsp?EID=948255), Jul 13, 2002 If anyone has a working example of how to create an updateable collection on a web page I'd be very grateful!!! these examples here get me 90% of the way there but as the other's have commented there seems to be some confusion as to what the substitutions of variables would be...ie."result" and so forth. for instance I have a database table with x records...I don't know how many....I can create an arraylist, vector or whatever of the records...but how do you accesss them as an array from the jsp page.... this example is soooo close but doesn't compile... Help!!! Thank you very much John Walsh jwalsh@kelaroo.com Struts newbie.... |
| Re[2]: Generated ActionForm and JSPs
Author: Judy Wang (http://www.jguru.com/guru/viewbio.jsp?EID=1020579), Nov 2, 2002 I have same problem. In the actionform, I define a array of a class like: TestData{ int id; String desc; } In the array: TestArray{ String userid; TestData[] s; } I can write the array to jsp. But I can't read the form's array from jsp. |
| here is a complete working example.
Author: Raj K (http://www.jguru.com/guru/viewbio.jsp?EID=1027421), Dec 19, 2002 I first invoke /rowsActionShow.do it displays the prepopulated values. I change the displayed values and submit the form you will see that the form bean is getting updated with the new values I have print statements in the RowsActionSave.java. HTH Thanks, Raj.
/////////// RowsForm.java ////////////////
package test;
import org.apache.struts.action.*;
import java.util.*;
public class RowsForm extends ActionForm {
private String[] rowId;
private String[] rowProperty1;
public String[] getRowId() {
return rowId;
}
public void setRowId(String[] rowId) {
this.rowId = rowId;
}
public String[] getRowProperty1() {
return rowProperty1;
}
public void setRowProperty1(String[] rowProperty1) {
this.rowProperty1 = rowProperty1;
}
public ArrayList getRows() {
ArrayList rows = new ArrayList();
final int size = rowId.length;
for (int i = 0; i < size; i++) {
RowForm row = new RowForm();
row.setRowId(rowId[i]);
row.setRowProperty1(rowProperty1[i]);
rows.add(row);
}
return rows;
}
public void populateForm(Vector rowData) {
final int size = rowData.size();
rowId = new String[size];
rowProperty1 = new String[size];
Enumeration enum = rowData.elements();
for (int i = 0; i < size; i++) {
RowForm element = (RowForm) enum.nextElement();
rowId[i] = String.valueOf(element.getRowId());
rowProperty1[i] = element.getRowProperty1();
}
}
}
///////////////// RowForm.java /////////////////////
package test;
import org.apache.struts.action.*;
import java.util.List;
import java.util.ArrayList;
public class RowForm extends ActionForm {
private String rowId;
private String rowProperty1;
public String getRowId() {
return rowId;
}
public void setRowId(String id) {
this.rowId = id;
}
public String getRowProperty1() {
return rowProperty1;
}
public void setRowProperty1(String property1) {
this.rowProperty1 = property1;
}
}
//////////////// RowsActionShow.java /////////////
package test;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.lang.reflect.Method;
import java.util.*;
public class RowsActionShow extends Action {
public ActionForward perform(
ActionMapping mapping,ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException,
Javax.servlet.ServletException {
RowsForm rowsForm = (RowsForm) form ;
Vector rowData = new Vector() ;
RowForm rf0 = new RowForm() ;
rf0.setRowId("1") ;
rf0.setRowProperty1("James") ;
rowData.add(rf0) ;
RowForm rf1 = new RowForm() ;
rf1.setRowId("2") ;
rf1.setRowProperty1("Peter") ;
rowData.add(rf1) ;
rowsForm.populateForm(rowData) ;
ActionForward result= mapping.findForward("rowspage");
return result;
}
}
//////////////// RowsActionSave.java /////////////
package test;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.lang.reflect.Method;
import java.util.*;
public class RowsActionSave extends Action {
public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, x.servlet.ServletException {
RowsForm rowsForm = (RowsForm) form ;
ArrayList rows = rowsForm.getRows() ;
RowForm rf0 = (RowForm) rows.get(0) ;
System.out.println("In RowsActionSave") ;
System.out.println("ID: " + rf0.getRowId()) ;
System.out.println("Property: " + rf0.getRowProperty1()) ;
ActionForward result= mapping.findForward("rowspage");
return result;
}
}
//////////////// RowsPage.jsp ///////////
<TABLE><html:form action="/rowsActionSave.do">
<table>
<tr>
<th>id</th>
<th>property1</th>
</tr>
<logic:iterate name="rowsForm" property="rows" id="row" type="test.RowForm">
<tr>
<td>
<bean:write name="row" property="rowId" />
<html:hidden name="row" property="rowId" />
</td>
<td>
<html:text name="row" property="rowProperty1" />
</td>
</tr>
</logic:iterate>
</table>
<html:submit property="Submit">Submit</html:submit>
</html:form>
</TABLE>
/////////////////// strutsconfig.xml ///////////
<form-bean name="rowsForm" type="test.RowsForm"/>
<forward name="rowspage" path="/RowsPage.jsp"/>
<action
path="/rowsActionShow"
type="test.RowsActionShow"
name="rowsForm"
scope="session"
validate="false">
</action>
<action
path="/rowsActionSave"
type="test.RowsActionSave"
name="rowsForm"
scope="session"
validate="false">
</action>
|
| Re: here is a complete working example.
Author: Vicky Lamont (http://www.jguru.com/guru/viewbio.jsp?EID=1033674), Dec 24, 2002 Hi Raj, I tried your example, it doesnot work. The exception I get when trying to access the RowsPage.jsp is: Exception thrown by getter for property rows of bean rowsForm Looking forward for your reply Thanks, Vicky |
| Re[2]: here is a complete working example.
Author: SaikrishnaRao K (http://www.jguru.com/guru/viewbio.jsp?EID=1212791), Nov 24, 2004 Hi, Guys Just add the Following Code in the RowsForm.java private ArrayList rows ;Recompile and Redeploy the App It Should Work atleast it works for Me. |
| Re: here is a complete working example.
Author: Subramanyam Gandikota (http://www.jguru.com/guru/viewbio.jsp?EID=1040772), Dec 24, 2002 I am working with struts 1.1-b2. When I run the code it throws the following error: Exception thrown by getter for property rows of bean rowsForm in the jsp. Please help me on this . Thanks a lot. Subramanyam |
| Re[2]: here is a complete working example.
Author: Raj K (http://www.jguru.com/guru/viewbio.jsp?EID=1027421), Dec 31, 2002 I don't know why this error occurs when you try to run the JSP. for some reason it does not load the form. It works as expected when you invoke the "rowsActionShow.do" http://localhost:8080/IndexedProps/rowsActionShow.do and then make changes and submit the form. you can see the originale data and the updated data in the debug messages that are in the Action classes RowsActionShow.java and RowsActionSave.java |
| Re[3]: here is a complete working example.
Author: Raj K (http://www.jguru.com/guru/viewbio.jsp?EID=1027421), Dec 31, 2002 on second thought.....I think it gives an exception because the form bean RowsForm is not initialized and gets initialized only when the rowsActionShow.do is invoked....... |
| Re[4]: here is a complete working example.
Author: Sunil Ravindran (http://www.jguru.com/guru/viewbio.jsp?EID=1046123), Jan 14, 2003 The exception is thrown, because the first time the form is |
| Re[5]: an easier alternative
Author: john anderson (http://www.jguru.com/guru/viewbio.jsp?EID=1206684), Oct 21, 2004 Probably an easier alternative would be to use a data array to store it and retrieve it from... here is an example. <%! String[] fieldstore; %> <% fieldstore = new String[40]; for (int t=0; t<40; t++) { fieldstore[t]=""; } for (int a=1;a<children.getLength();a+=2) { if (children.item(a).getAttributes().item(0).getNodeValue().equals(fieldstore[0])) { childelements = children.item(a).getChildNodes(); fieldstore[1] = childelements.item(1).getChildNodes().item(1).getChildNodes().item(0).getNodeValue(); if (childelements.item(1).getChildNodes().getLength()>2) { fieldstore[2] = childelements.item(1).getChildNodes().item(3).getChildNodes().item(0).getNodeValue(); } int e=0, c=0; for (int b=3; b<childelements.getLength();b+=2) { if (childelements.item(b).getNodeName().equals("address")) { e=0; if(childelements.item(b).getAttributes().item(0).getNodeValue().equals("home")) { } else if(childelements.item(b).getAttributes().item(0).getNodeValue().equals("work")) { c=10; } else if(childelements.item(b).getAttributes().item(0).getNodeValue().equals("postal")) { c=17; } addresselements = childelements.item(b).getChildNodes(); for (int d=1;d<addresselements.getLength();d+=2) { if (addresselements.item(d).getNodeName().equals("street")) { fieldstore .... so on, else if (childelements.item(b).getNodeName().equals("dob")) { fieldstore[30] = childelements.item(b).getChildNodes().item(0).getNodeValue();} else if (childelements.item(b).getNodeName().equals("comments")) { fieldstore[31] = childelements.item(b).getChildNodes().item(0).getNodeValue().trim();} } } } |
| Re: here is a complete working example.
Author: d b (http://www.jguru.com/guru/viewbio.jsp?EID=1119055), Oct 1, 2003 I have a question regarding the code. In RowsActionShow.java, you are get an instance of the form before the jsp has created it. RowsForm rowsForm = (RowsForm) form; what allows you to do this? I've been trying to mimic your example, and when I do this my form = null. ... I'm trying to understand what I'm missing. thanks, d |
| Re: here is a complete working example.
Author: aby chaturvedi (http://www.jguru.com/guru/viewbio.jsp?EID=1217698), Jan 30, 2005 Raj I saw your code on the internet in connection to population of rows.However on running the code i get an error RowForm Class not found.Could you help me in running this code. Please help Aby |
| « previous | beginning | next » |
Struts Tip #7 - Use Multibox to manage checkboxes
Location: http://www.jguru.com/faq/view.jsp?EID=925277
Created: Jun 24, 2002
Modified: 2002-09-06 04:41:23.732
Author: Ted Husted (http://www.jguru.com/guru/viewbio.jsp?EID=462042)
Comments and alternative answersMany applications need to use a large number of checkboxes to track options or selected items. To help with this, Struts provides the multibox control. It's quite handy but a little tricky to understand at first.
The multibox leverages the way HTML handles checkboxes. If the box is not checked, the browser does not submit a value for the control. If the box is checked, then the name of the control and its value are submitted. This behavior is the reason there is a reset() method on the ActionForm. Since the browser will never signal that a box has been un-checked, the only solution is to reset all the boxes, and then check the ones that are now present in the request.
The multibox control is designed to use an array of Strings. Each element in the array represents a checked box. To check a box, add a String to the array with the box's value. To uncheck a box, remove the element from the array. (Sound familiar?)
When passed a value, the multibox control scans the elements of its array to see if there is a match. If so, the box is checked. If not, the box is left unchecked. If the user checks the box and submits the form, the box's value will be included in the request. The controller will then add that box to the "checked" array. If a box is unchecked, nothing is submitted, and nothing is added to the array. If the ActionForm bean is kept in the session context, in between requests, the reset() method needs to reduce the array to zero length (but not null).
In this example,
<logic:iterate id="item" property="items">
<html:multibox property="selectedItems">
<bean:write name="item"/>
</html:multibox>
<bean:write name="item"/>
</logic:iterate>The labels for the individual checkboxes is in the items property. The list of selected items is in an array named selectedItems. Items that are not selected are not present in the selectedItems array. The multibox checks the selectedItems array for the current item. If it is present, it writes a checked checkbox. If not, it writes an unchecked checkbox.
Given an ActionForm setup like this
private String[] selectedItems = {};
private String[] items = {"UPS","FedEx","Airborne"};
public String[] getSelectedItems() {
return this.selectedItems;
}
public void setSelectedItems(String[] selectedItems) {
this.selectedItems = selectedItems;
}The markup in the example would generate three checkboxes, labeled UPS, FedEx, and Airborne.
<input type="checkbox" name="selectedItems" value="UPS">UPS
<input type="checkbox" name="selectedItems" value="FedEx">FedEx
<input type="checkbox" name="selectedItems" value="AirBorne">AirBorneInitially, the selectedItems array would be empty. If UPS were checked and submitted, it would become the equivalent of
private String[] selectedItems = {"UPS"};If UPS and Airborne were both checked, it would become the equivalent of
private String[] selectedItems = {"UPS","Airborne"};And when the checkboxes are rendered, the appropriate elements are automagically checked by the multibox tag.
<input type="checkbox" name="selectedItems" value="UPS" checked="checked">UPS
<input type="checkbox" name="selectedItems" value="FedEx">FedEx
<input type="checkbox" name="selectedItems" value="AirBorne" checked="checked">AirBorneTo provide different sets of labels and values, the standard LabelValueBean class [
org.apache.struts.util.LabelValueBean] (since 1.1) can be used with the multibox control.
<logic:iterate id="item" property="items">
<html:multibox property="selectedItems">
<bean:write name="item" property="value"/>
</html:multibox>
<bean:write name="item" property="label"/>
</logic:iterate>HTH, Ted.
-----
Struts Tips are excerpts from the book Java Web Development with Struts. The tips released twice weekly on the MVC-Programmers List. To subscribe, visit BaseBean Engineering.
About Ted. Ted Husted is an active Struts Committer and co-author of Java Web Development with Struts and Professional JSP Site Design. Ted also moderates the Struts mailing list and the JGuru Struts FAQ.
Copyright Ted Husted 2002. All rights reserved.---
MVC-Programmers mailing list
MVC-Programmers@basebeans.com
http://www.basebeans.com:8081/mailman/listinfo/mvc-programmers
| Comments on Checkboxes in Struts.
Author: Mainak Ghosh (http://www.jguru.com/guru/viewbio.jsp?EID=975164), Aug 2, 2002 Thanks to Mr. Ted or this wonderful and helping article. |
| unable to utilize the multibox example in my struts application
Author: sam m (http://www.jguru.com/guru/viewbio.jsp?EID=1052110), Jan 30, 2003 I have tried using the multibox example but Struts is not invoking the set method which takes String[] arguments, rather it invokes the set method which accepts only one String argument. My ActionForm class looks like this: private String[] teamList; public String[] getTeams() { return teamList; } public void setTeams(String[] teams) { System.out.println("setTeams(String[])-> size: " + teams.length); teamList = teams; } public void setTeams(String team) { System.out.println("setTeams(String)-> " + team); } Also, I notice that getTeams() gets called for each "checkbox" entry in the JSP page. What am I missing or doing incorrectly? Thanks for the help. |
| Re: unable to utilize the multibox example in my struts application
Author: Isam Abdelhameed (http://www.jguru.com/guru/viewbio.jsp?EID=1199121), Sep 14, 2004 How about naming your setter and getter to match you bean property; I mean setTeamList() and getTeamList() instead of setTeams() and getTeams() |
| Re[2]: unable to utilize the multibox example in my struts application
Author: Naman Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=1310609), Aug 29, 2006 The getter-setter functions dont have to match the bean property. U cud name them anything u want. Its just that the same name has to be set in the property attribute in ur JSPs. As the value of property attribute defines which getter function will be called when the page is loaded and the respective setter function on submitting the page. |
| Problem using LabelValueBean[] instead of String[] with the multibox Struts tag
Author: Niall Hosiene (http://www.jguru.com/guru/viewbio.jsp?EID=1027863), Apr 14, 2003 I successfully used the code from tip #7 to create checkboxes. However, when moving from a String[] array to a LabelValueBean[] array, I ran into problems. There wasn't a problem when typing in the url in the browser and being forwarded to the appropriate JSP - everything rendered nicely. When I tried to submit the form, I got the following exception:
java.lang.IllegalArgumentException: array element type mismatch at java.lang.reflect.Array.set(Native Method) at org.apache.commons.beanutils.ConvertUtils.convert(ConvertUtils.java:415) Trying another tack and using a List of LabelValueBean objects instead of an array, I had a similar result when submitting the form, just a slightly different exception:
java.lang.IllegalArgumentException: argument type mismatch at java.lang.reflect.Method.invoke(Native Method) at org.apache.commons.beanutils.PropertyUtils.setSimpleProperty(PropertyUtils.java:1789) Has anyone met this problem? thanks,
N. |
| Re: Problem using LabelValueBean[] instead of String[] with the multibox Struts tag
Author: Tariq Chalabi (http://www.jguru.com/guru/viewbio.jsp?EID=1110935), Aug 26, 2003 Hi, I'm having exactly the same behaviour that you describe. Did you (or anyone else) get a fix for this? |
| Re: Problem using LabelValueBean[] instead of String[] with the multibox Struts tag
Author: Eduardo Lazarine (http://www.jguru.com/guru/viewbio.jsp?EID=1199028), Nov 23, 2004 Hi, N.! Maybe you should use LabelValueBean only during presentation of data (in Ted´s example, the LabelValueBean[] is named "items"). For collecting results, the multibox tag will only parse String values. The "selectedItems" property should still be String [] (and so their setter and getter methods). Hope it helps! Cheers, Eduardo. |
| Multibox-Iterate and Arrays with primitive Datatypes
Author: Timo Waldschmidt (http://www.jguru.com/guru/viewbio.jsp?EID=1084794), Jun 13, 2003 Hi, as I read in the documentation, its not supported to iterate over an Array with primitive Datatypes - instead I can only iterate over collections with objects and getter and setter methods inside. That means, that your example with multibox doesn't work in the kind you wrote - right? maybe the struts-docu is old or wrong? So why do you write (JSP) <logic:iterate id="item"property="items"> ... (ActionForm) private String[] items = {"UPS","FedEx","Airborne"}; that didn't work at me. What I want to do is to iterate over an Collection. Within the Collection I have Objects with the String- attribute Id. An this Id I want to use to name the value of the checkbox. Can you help me to solve this problem? Greetings from Germany! |
| Re: Multibox-Iterate and Arrays with primitive Datatypes
Author: Barett McGavock (http://www.jguru.com/guru/viewbio.jsp?EID=484005), Oct 22, 2004 A String is not a primitive data type. The JSP can't see a private variable on the ActionForm. You'll need to have a public get method in addition to the code you mentioned above.
|
| multibox doesnt take indexed attribute
Author: Prakash Reddy (http://www.jguru.com/guru/viewbio.jsp?EID=1225652), Feb 8, 2005 I think the fact that html:multibox doesnt take the indexed attribute severely limits its useful in advanced table like forms. |
| problem is if i have all the checkboxes checked
Author: sameep dawar (http://www.jguru.com/guru/viewbio.jsp?EID=1229501), Feb 26, 2005 so i want to retrieve the ids of the checked ones only but i expect the user to uncheck the ones that he doesnt want 2 display pl help |
| multibox not working
Author: shiva prasad (http://www.jguru.com/guru/viewbio.jsp?EID=107760), Nov 29, 2005
I have my iterate tag as below:
<logic:iterate id="item" name="userListForm" property="userList" >
<html:multibox property="selectedItemList">
<bean:write name="item" property="userid" />
</html:multibox>
<bean:write name="item" property="userid" />
--
--
</logic:iterate>
Getting error: [ServletException in:userlist.jsp] Cannot find bean under name org.apache.struts.taglib.html.BEAN'
userListForm: is of Type UserListForm class
userList is ArrayList in UserListForm class - list of 'item's
item is of type: UserForm
userid is a field in UserForm
I am not able to figure out what the error is.
I am able to get values for below code on jsp.
<%
System.out.println(item);
System.out.println(((test.forms.UserForm)item).getUserid());
%>
Pls help.
|
| Re: multibox not working
Author: pradeep chintam (http://www.jguru.com/guru/viewbio.jsp?EID=1356775), Feb 19, 2008 hi shiva.. may be this will solve your prob.. make sure your form is <html:form> dont write any "name" in the form.. |
| multibox in mozilla
Author: vishnu bhargava (http://www.jguru.com/guru/viewbio.jsp?EID=1415473), Jun 30, 2009 Could u plz tell me whether multibox feature works in mozilla 1.5 version? |
| What if every check box is unselected ?
Author: Vamshi Jampala (http://www.jguru.com/guru/viewbio.jsp?EID=1418313), Jun 30, 2009 Hi Ted, Thanks for the very good explanantion. When i check atleast one of them it works perfectly fine, but when i uncheck everything and submit , it shows me the previous selection instead of uncheking everything. I am stuck, How do you think that one should solve this problem ? Thanks for your time :) |
Struts Tip #8 - Use result objects to transfer values
Location: http://www.jguru.com/faq/view.jsp?EID=933388