aspose file tools*
The moose likes Struts and the fly likes populate items using struts2 <s:select> Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "populate items using struts2 <s:select>" Watch "populate items using struts2 <s:select>" New topic
Author

populate items using struts2 <s:select>

unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
Hi all,

i am new to struts2.. am struggling to get the result for populating items from DB.

my requirement is to populate country, which is stored in DB, using struts2 and when you choose a particular country, another select box populate its cities, which also stored in DB..

at first i tried, fetching the list from java class instead of DB... since there is an example available in
struts2-showcase-2.0.14,built in project of struts2.

when i imported struts2-showcase-2.0.14 and tried that program the <s:select> is working.. so i thought to implement that into my project.. but unfortunately it is not working..

i will post here and please have a look and try providing the reason

I paste here the example block of a program from struts2-showcase-2.0.14 :

Portion of Jsp file contains the list Like : example.jsp

<s:form action="exampleSubmit" >
<s:select
tooltip="Choose Your Favourite Language"
label="Favourite Language"
list="favouriteLanguages"
name="favouriteLanguage"
listKey="key"
listValue="description"
emptyOption="true"
headerKey="None"
headerValue="None"/>


portion of java class file contains like the following: UITagExample.java

package com.dirstructure.action; // i pasted this since i mentioned this in struts.xml - you should not confuse

public String execute() throws Exception {
return SUCCESS;
}

//constructor
public UITagExample() {
favouriteLanguages.add(new Language("EnglishKey", "English Language"));
favouriteLanguages.add(new Language("FrenchKey", "French Language"));
favouriteLanguages.add(new Language("SpanishKey", "Spanish Language"));
}

public List getFavouriteLanguages() {
return favouriteLanguages;
}


public void setFavouriteLanguage(String favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}

public String getFavouriteLanguage() {
return favouriteLanguage;
}

// === inner class
public static class Language {
String description;
String key;

public Language(String key, String description) {
this.key = key;
this.description = description;
}

public String getKey() {
return key;
}
public String getDescription() {
return description;
}

}

portion of struts.xml

<action name="exampleSubmit" class="com.dirstructure.action.UITagExample" >
<result>example.jsp</result>
<result name="input">example.jsp</result>
</action>


when i execute http://localhost:8080/DirStructure/example.jsp .. result is a blank page

if example.jsp contains other tags like <s:textfield> with <s:select> , result is only a textfield .. select box is not shown...

and in the Eclipse Ganymede output window, the error is like the following:

SEVERE: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'favouriteLanguage': The requested list key 'favouriteLanguages' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:231)
at org.apache.struts2.components.Component.findValue(Component.java:293)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:79)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:99)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:780)
at org.apache.struts2.components.UIBean.end(UIBean.java:481)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:43)
at org.apache.jsp.example_jsp._jspx_meth_s_005fselect_005f0(example_jsp.java:383)
at org.apache.jsp.example_jsp._jspx_meth_s_005fform_005f0(example_jsp.java:244)
at org.apache.jsp.example_jsp._jspService(example_jsp.java:111)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:416)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)



I explained every single point detail in manner... i hope you guys can help me by seeing this..


Please don't tell me to try the following: i tried and its working
<s:select
tooltip="Choose Your Favourite Color"
label="Favorite Color"
list="{'Red', 'Blue', 'Green'}"
name="favouriteColor"
emptyOption="true"
headerKey="None"
headerValue="None"/>

i need to populate from DB or from java class, like i explained at top


Thanks in advance...

I hope this post helps you lot...

Cheers!!!
Unnii
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

Hi Unnii,

Welcome to Javaranch.
Please use the [code] tag properly when you post a message. Only your code needs to be inside the [code] tag, not your entire message. Please use the button to format your previous post properly.

SCJP 5.0 and now fighting with ExtJS
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
when i post without code tag, am getting the following error message:

We're sorry, but your post appears to contain abbreviations that we don't like people to use at the Ranch. Because JavaRanch is an international forum, many of our members are not native English speakers. For that reason, it's important that we all try to write clear, standard English, and avoid abbreviations and SMS shortcuts. See here for more of an explanation. Thanks for understanding.

If the abbreviation occurs within code, you can use code tags to post it successfully.

The specific error message is: "u" is a silly English abbreviation; use "you" instead.


can you provide me a solution to post a message without this error

Cheers!!!
unnii
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

my requirement is to populate country, which is stored in DB, using struts2 and when u choose a particular country, another select box populate its cities, which also stored in DB..

Replace the bold highlighted alphabet with "you". Please don't use abbreviations as the error message says.
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
Thanks Balagopal Kannampallil ..

i have edited my first post and now its fine ..

thanks for your comments on posting...

and

Guys, please help me to get solved this <s:select> issue

Thanks in advance

Cheers!!!
Unnii
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

But your code is still not properly formatted. You need to take a look at this link thoroughly.
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
any help???

please its bit urgent... I have already posted all the codes here.. can you guys provide me any suggestion please..

thanks in advance

Cheers!!!
Unnii
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

See this thread. May be it will help you.
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
Thanks for your reply, Balagopal Kannampallil...

The thread you have provided demonstrates iteration of a list. using <s:iterator> tag

But my thread belongs to populating a list in drop-down list using <s:select>

Actually i have added favourite languages in an list in the .java file. I have to display it in .jsp as follows:



Is there anyway to list the languages, which are coded in .java file, in drop-down list.

Mainly,

1. How to fetch the values from class file to jsp?
2. Whether the way i displayed in jsp (list, listKey, listValue) are correct or not?

Cheers!!!
Unnii



Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

OK now Unnii, here comes my question.
* Do your Action form has a List declared in the name of favouriteLanguages with its corresponding getter and setter method?
* What 'Type' is your favouriteLanguages list holding? A POJO?
* If it is a POJO then do it has fields like key, description etc?

Ok here I go with the an example. I have a simple POJO MyLanguage which has fields country and language.

In my action class, I declare a list named favouriteLanguages which holds MyLanguage type with its getter and setter method. Something like this

In my action method, I am creating new MyLanguage objects and adding it to favouriteLanguages list

Now in my result jsp, I can use the favouriteLanguages list directly inside s:select like this

This example will help you solve your problem.
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
Hi Balagopal Kannampallil,

Thanks for the reply..

I tried same type of code like the one you have posted here. But it did not work out.

Please have a look on this code and suggest me where i am wrong,

JSP page:



and let me explain here what the output when i execute jsp page in different way without changing class file:

1. if i execute the above select tag and run , the page does not list any drop-down list, its a blank page

2. if i change select tag like:
list="{favouriteLanguages}" , i will get the drop-down list but only with "None" header Value

3. if i change select tag like:
list="{favouriteLanguages}"
listKey="%{key}"
listValue="%{description}" , i will get the drop-down list but only with "None" header Value

(page displays at least an empty list only if list attribute have curly brace like {favouriteLanguages})

i tried all variations, with and without {}, %, #.. but no luck.

i have only one class file which has getter/setter methods and execute method (POJO)



Please suggest me if anything wrong in the code (jsp, java)

Whether the inner class makes any problem here? Will outer class's constructor creates list and render it to jsp page?

Actually the same example works in struts2-showcase-2.0.14 but when i implement in our project its not.. any Help???

you can have a glance on this error too : detail list is in my first post of this thread

SEVERE: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'favouriteLanguage': The requested list key 'favouriteLanguages' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]

Cheers!!!
Unnii
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

When you post code make sure it's the actual code--the Java class above won't compile as-is.

That aside, your code works fine for me. Are you accessing the JSP form page through the action?
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
Hi David Newton,

Thanks for your reply..

Yes.. am using as follows:



have to import the following with my previous code to compile:



Cheers!!!
Unnii
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
HI guys,

i have pasted entire the codes(jsp, pojo class, struts.xml) in my thread...i expect anybody giving me a solution..
i know its very minor mistake... would you please point me out ...

Cheers!!!
unnii
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

That wasn't my question.

What is the URL you use to access the form?
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23

http://localhost:8080/DirStructure/example.jsp

Thanks
Unnii
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

If you access the JSP directly the list won't be populated: the list is created by the *action*.

So besides that it's probably not a good idea to have people directly accessing JSP pages, it won't work: the S2 tags require there to be an action on the value stack, particularly when it's the action that's creating the data used by the tags.
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
HI ,

I didnt get you properly... Can you please give me the code to work out.

i went thru quickly on topic called ValueStack.. and think its methods can use once the list is populated when page loads.. Here, i am not getting any drop-down list in the page... page is blank always.. when i change jsp code like list= "{favouriteLanguages}", page displays empty drop-down list.

I FOUND SOMETHING LIKE THIS: dont know whats the use
ValueStack stack = ServletActionContext.getValueStack(ServletActionContext.getRequest());

Thanks
Unnii
Bilal A. Siddiqui
Ranch Hand

Joined: Sep 14, 2008
Posts: 53

Hi unni

I have gone through your code and what i say is you please implement a simpler version first. I mean without and inner class.

Write a method which will add values in your list( favouriteLanguages) and call this method in execute method before returning success. You will surely get the output. Once you done with this let me know i will guide you how to get another drop down depending on the previous one.


Cheers!!! Bilal
Handsome Android||@bilal_speed||LinkedIn
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

If you access a JSP page directly there *is* no value stack (well, there might be, but it won't be relevant, since the action won't be on it).

If you're using S2 tags on a page and expect them to work then you must access the page via an action.

@bilal: The code is fine--the original poster just isn't accessing the page via an action.
Bilal A. Siddiqui
Ranch Hand

Joined: Sep 14, 2008
Posts: 53

Unni can you please post the xml file you are using to direct the action.
Bilal A. Siddiqui
Ranch Hand

Joined: Sep 14, 2008
Posts: 53

Sorry i didnt see it. xml file is already there.

do one thing i got some what similar problem.

in execute method instead of doing return SUCCESS make it return "SUCCESS" and then in xml do <result type="SUCCESS">example.jsp</result>, its not very intelligent reply but try it once, i hope it will work.
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
HI BilalSiddiqui Siddiqui,

When i made the changes that you have suggested , i am getting the following errors:

SEVERE: Exception starting filter struts
java.lang.RuntimeException: java.lang.RuntimeException: java.lang.NullPointerException
at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:290)
at com.opensymphony.xwork2.inject.ContainerImpl$2.call(ContainerImpl.java:117)
at com.opensymphony.xwork2.inject.ContainerImpl$2.call(ContainerImpl.java:115)
at com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:542)
at com.opensymphony.xwork2.inject.ContainerImpl.injectStatics(ContainerImpl.java:114)
at com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:494)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reload(DefaultConfiguration.java:145)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:52)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:395)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:452)
at org.apache.struts2.dispatcher.FilterDispatcher.init(FilterDispatcher.java:205)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:397)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:108)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3709)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4363)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at com.opensymphony.xwork2.inject.ContainerBuilder$4.create(ContainerBuilder.java:136)
at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:49)
at com.opensymphony.xwork2.inject.ContainerImpl$ParameterInjector.inject(ContainerImpl.java:431)
at com.opensymphony.xwork2.inject.ContainerImpl.getParameters(ContainerImpl.java:446)
at com.opensymphony.xwork2.inject.ContainerImpl.access$000(ContainerImpl.java:48)
at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:288)
... 28 more
Caused by: java.lang.NullPointerException
at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:126)
at org.apache.struts2.config.BeanSelectionProvider$ObjectFactoryDelegateFactory.create(BeanSelectionProvider.java:245)
at com.opensymphony.xwork2.inject.ContainerBuilder$4.create(ContainerBuilder.java:134)


without these changes i am getting atleast jsp page without these errors

Thanks
Unni
unnii
Greenhorn

Joined: Jan 21, 2008
Posts: 23
HI David Newton ,

You are correct.. but can you please tell me how to access page directly using action..

my jsp is :



ans struts.xml looks as follows:



where can i change in my code to get the action first?


when i run the project in eclipse it call index.jsp where i written,

  • <s:url id="url" value="example.jsp"/><s:a href="%{#url}">Select LanguageExample</s:a>


  • when i click the link it shows following page:

    http://localhost:8080/DirStructure/example.jsp;jsessionid=1F365122B17FF1129118931855FD9C89 and shows the jsp page


    Thanks
    Unnii
    Bilal A. Siddiqui
    Ranch Hand

    Joined: Sep 14, 2008
    Posts: 53

    Hi unni

    i have done few changes in your code and its running fine at my end.



    as you can see i have removed

    listKey="key"
    listValue="description" from select tag and

    i have removed constructor and instead of that i have placed a new method and called it in execute method. It gave me perfect output.

    and this is how my xml looks






    unnii
    Greenhorn

    Joined: Jan 21, 2008
    Posts: 23
    Hi All,

    its working.. i have created namespace(ah) in struts.xml and called it in index.jsp like


    i post previous line of code several time .. but couldnt post it correctly .. its strange


    Thanks all

    Meet you soon

    Cheers!!!
    Unnii
    unnii
    Greenhorn

    Joined: Jan 21, 2008
    Posts: 23
    Hi BilalSiddiqui Siddiqui,

    Thanks for your reply...

    I done it thru action as directed by David Newton.. and really your suggestion were motivated me a lot.
    and thanks for your working example that you posted in this thread using a function, addLang().. i havent tried.. but it seems it works

    Cheers!!!
    Unnii
    unnii
    Greenhorn

    Joined: Jan 21, 2008
    Posts: 23
    Hi Guys,

    YOU ARE REALLY REALLY HELPFUL

    Thank you so much for your contributions... and i hope this thread will solve most of <s:select> tag issues... and more users find this solution useful..

    Cheers!!!
    Unnii
    bern wey
    Greenhorn

    Joined: Jul 05, 2009
    Posts: 1
    actually,if you access the page like this:http://localhost:8080/app/dirStructure/example.action,it will work out
    Js Bendeshah
    Greenhorn

    Joined: Sep 08, 2010
    Posts: 1
    Hi All,
    I also a newbie in Struts2 i was going through the thread to resolve the problem of population of <s:select>. I referred the code semantics given in the thread and it helped me a lot. The only place where i had difference was the value of the list attribute in the select tag. I have specified the value of the list attribute without the curly braces and it worked for me. With curly braces the page was displayed but without the values being populated in the select box. The semantics of the select tag that i have used is as follows

    <s:select name="accountList" list="accountList" emptyOption="false" listValue="%{AccountIdValue}" listKey="%{AccountIdKey}" label="From Account" />
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: populate items using struts2 <s:select>