Skip to main content

Struts 2 Ajax drop down Example

Struts 2 has emerged as boon for developers. But the documentation available is very small. So I had decided to give a brief demonstration of the ajax used in struts 2.1.8.1
Libraries used:

commons-beanutils-1.7.0.jar
commons-fileupload-1.2.jar
commons-logging-1.1.jar
commons-logging-api-1.1.jar
freemarker-2.3.8.jar
struts2-core-2.1.8.1.jar
struts2-dojo-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar

In this example when u select from one drop down the other will populate accordingly. You can use it as it is or play with it. Enjoy !!

index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:action name="ListingAction" executeResult="true"></s:action>

listing.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>



Listing



 
  
detail.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>


 

DetailAction.java
package ajaxdemo.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class DetailAction extends ActionSupport {
 private String lst;
 private List lstList = null;
 private List lstList2 = null;

 public String execute() throws Exception {

  if (getLst() != null && !getLst().equals("")) {
   populateDetail(getLst());
   return SUCCESS;
  } else {
   return SUCCESS;
  }
 }

 private void populateDetail(String id) {
  lstList = new ArrayList();
  if (id.equalsIgnoreCase("Fruits")) {
   lstList.add("Apple");
   lstList.add("PineApple");
   lstList.add("Mango");
   lstList.add("Banana");
   lstList.add("Grapes");
  } else if (id.equalsIgnoreCase("Places")) {
   lstList.add("New York");
   lstList.add("Sydney");
   lstList.add("California");
   lstList.add("Switzerland");
   lstList.add("Paris");
  } else {
   lstList.add("Other 1");
   lstList.add("Other 2");
   lstList.add("Other 3");
   lstList.add("Other 4");
   lstList.add("Other 5");
  }
 }

 public List getLstList() {
  return lstList;
 }

 public void setLstList(List lstList) {
  this.lstList = lstList;
 }

 public String getLst() {
  return lst;
 }

 public void setLst(String lst) {
  this.lst = lst;
 }
}


ListingAction.java
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;

public class ListingAction extends ActionSupport {
 private List lstList1 = null;

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

 private void populateDetail() {
  lstList1 = new ArrayList();
  lstList1.add("Fruits");
  lstList1.add("Places");
  lstList1.add("Others");
 }

 public List getLstList1() {
  return lstList1;
 }

 public void setLstList1(List lstList1) {
  this.lstList1 = lstList1;
 }
}


Struts.xml

 
  
   /listing.jsp
  
  
   /detail.jsp
  
 

 

web.xml


 
  struts2
  org.apache.struts2.dispatcher.FilterDispatcher
 
 
  struts2
  /*
 
 
  index.jsp
 
 

Comments

  1. Hi, I've tried your example but it doesn't work. It doesn't give an error. The list list1 is displayed but apparently the id needed to populate the second list, is null. The id of the selected value ( fruits,places and others) is set in the javascript no? For some reson it is null im my DetailAction class.
    Can u help me? :(

    ReplyDelete
  2. Hi Adriana,

    Thanks for your comment. Actually when I tried this example I got the same error but I found the error.
    You have to replace the variable name from id to pid or any other name.
    Once again thanks. I had changed my code. You can try this. If it works do write to me (It will work now :) ).

    ReplyDelete
  3. I like this example and it works for me

    Thanx Vinod

    ReplyDelete
  4. Nicely done. One comment though is that the hidden field is not needed. The 'lst' parameter from the first select box is passed into the DetailAction just as the pid one is via the formId. So you can remove the hidden field and the javascript setting of the hidden field and just use get1st() after adding String 1st;.

    ReplyDelete
  5. Hi Jason

    thanks for your valuable comments. You are right there is no need of hidden variable. I will be removing it from this post.
    Thanks Again :)

    ReplyDelete
  6. Thank you for your post.
    Appreciate it. Where do you usually refer to accomplish things like these. -harsh

    ReplyDelete
  7. Thanks for the example; it does work for me. But what if I want to populate the 2nd select based upon the listKey (integer id) of the selected value in the first select, rather than using the listValue? I've played around with this, but I can't get it to work.

    ReplyDelete
  8. Hey this is exactly what I was looking for. Good Job.

    ReplyDelete
  9. When i first load the script, i will be directed to an empty page that will be loading the second dropdown box. Only when i click on the back button of the browser, then the actual page with the two dropdown boxes will be displayed. Any idea how do i solve this problem?

    ReplyDelete
  10. Thanks for the example. Worked and was helpful.

    ReplyDelete
  11. I tried your example but strangely I get just one of the drop downs. I have javascript error that dojo is undefined.
    Am I missing something?

    ReplyDelete
  12. Hey Vinod, the example is helpful, but i have a problem of my own and have got 10 solutions to it too, but not sure if they are efficient. I am writing this here cause it is related to the same example and i want to share it with the concerned masses. So, the question is if i add a submit button to your example which will invoke an action to insert the value of both the select boxes in database, and when the operation is complete, the requirement is, the user is to be returned back to the same page with state of both the select boxes maintained. I have many solutions to this and will also post it here but want to listen from you guys first.. Regards

    ReplyDelete
  13. Hi,
    These days I am little busy in my office schedule. I will be very happy if you post your solution of what you have told me. But these are the comments and posting solutions here will be somewhat awkward. You can mail me the solution if you want to. I will make sure to include your name in the next post.
    Thanks for your concern.. :)

    ReplyDelete
  14. Fantastic example..gr8 work...If I have a submit button in listing.jsp which maps to a method in DetailListingAction.java, how do I get the selected value for the drop down used in Detail.jsp?

    Thanks in Advance

    ReplyDelete
  15. Hi Vinod,
    Nice tutorial.
    Similar tutorial is Struts Application using Eclipse.
    Do post tutorials frequently.. Waiting to see more..

    ReplyDelete
  16. Hi

    I have the same problem as the one described above: "I tried your example but strangely I get just one of the drop downs. I have javascript error that dojo is undefined."

    Could you please help me with this.

    ReplyDelete
  17. Hi,

    Great working Example. Only naming convention of classes/jSP/action bit difficult to understand.

    Appreciate the effort.

    ReplyDelete
  18. I did make the following changes to get it work. I am using Tomcat 6.0, Struts-2.1.6 and eclipse:
    1. copy struts2-dojo-plugin-2.1.6.tar from struts to WEB-INF/lib folder.
    2. make changes in listing.jsp:
    2.1 Add dojo taglib reference.
    < %@ taglib prefix="sx" uri="/struts-dojo-tags" % >
    2.2 remove the header tag < s:head theme="ajax" /> and replace it with
    < sx:head debug="false" cache="false" compressed="true"/>
    2.3 Change the < s:url ... action="DetailAction"/> to < s:url ... action="demo/DetailAction"/>
    2.4 Change the < s:div> and < /s:div> to < sx:div> and < /sx:div>

    Note: forget the space right after "<".

    ReplyDelete
  19. JSF with Struts2 example available?

    ReplyDelete
  20. Hey, here's a question that has me stumped now for a couple days and I have a feeling the answer is really easy. I am writing a struts 2 web application and for some reason, my struts 2 ajax tags (s:div specifically) only work on the welcome-file (index.jsp). When I click a link to call an action that has a result page called result.jsp, the very same s:div that executed and dispalyed its contents just fine on the welcome page no longer works on the result.jsp page. Why is this? It seems that no ajax theme elements are working on any page other than the welcome page. If you have an answer to help me, I would GREATLY appreciate it!!! :) Thanks in advance.

    ReplyDelete
  21. Thanks a lot for sharing this example.

    ReplyDelete
  22. Hi
    I refer your example it is nice but I can not get both list on same page, control moves to detail page.
    is there any solution for that

    Thanks in advance

    ReplyDelete
  23. It is not working for me.Visiting http://localhost:8280/my-app/jsp/index.jsp gives a blank page whereas visiting http://localhost:8280/my-app/ListingAction.action gives following error:

    exception

    org.apache.jasper.JasperException: Expression parameters.parseContent is undefined on line 45, column 28 in template/ajax/head.ftl. - Class: freemarker.core.TemplateObject
    File: TemplateObject.java
    Method: assertNonNull
    Line: 124 - freemarker/core/TemplateObject.java:124:-1
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:515)



    root cause

    Expression parameters.parseContent is undefined on line 45, column 28 in template/ajax/head.ftl. - Class: freemarker.core.TemplateObject
    File: TemplateObject.java
    Method: assertNonNull
    Line: 124 - freemarker/core/TemplateObject.java:124:-1
    org.apache.struts2.components.UIBean.end(UIBean.java:515)
    org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)



    root cause

    freemarker.core.InvalidReferenceException: Expression parameters.parseContent is undefined on line 45, column 28 in template/ajax/head.ftl.
    freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124)
    freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:134)
    freemarker.core.BuiltIn$stringBI._getAsTemplateModel(BuiltIn.java:361)

    ReplyDelete
  24. After adding parseContent="true" to < sx:head /> , it worked by with http://localhost:8280/my-app/ListingAction.action

    But accessing http://localhost:8280/my-app/jsp/index.jsp still gives blank page

    ReplyDelete
  25. Thanks for your code

    ReplyDelete
  26. I have the same above issue File: TemplateObject.java
    Method: assertNonNull
    freemarker.core.InvalidReferenceException: Expression parameters.parseContent is undefined on line 45, column 28 in template/ajax/head.ftl.

    anybody have any idea...

    thanks in advance,
    Rajeev

    ReplyDelete
  27. Hi,
    i am getting the same excpetion

    freemarker.core.InvalidReferenceException: Expression parameters.parseContent is undefined on line 45, column 28 in template/ajax/head.ftl..........
    which are jars files we need to use to work these examples........?

    anybody have the idea to solve this......me in trouble pls hlep.........

    ReplyDelete
  28. Thanks for this working example. Very Helpful to start.

    ReplyDelete
  29. i got a blank page?......how is it? any solutions to it

    ReplyDelete
  30. wow.. great work... keep up the good work



    claudegals jr
    icotp on ict
    leyte

    ReplyDelete
  31. Hi Vinod,
    I tried this example.But beside first combo box I am getting the following error message.Please help me
    Error loading '/struts2-blank-2.0.14/example/DetailAction.action' (404 /struts2-blank-2.0.14/example/detail.jsp)

    ReplyDelete
  32. Awesome work Vinod !! Thank you very much.
    Here you go beginner fellas...
    http: //megaupload. com/?d=96VZMLJ5
    or

    http: //rapidshare. com/files/304188145/ajSample.war

    ReplyDelete
  33. hi

    this article is nice ,but small application i need to create with three list they how i call do that
    can u explain it

    ReplyDelete
  34. It is not working for me....

    ReplyDelete
  35. Hi Tao

    Thanks very much , I did the changes as you told to run the above example in Struts-2.1.6
    It is worked fine

    I think in the later versions some struts tags they moved it to stuts-dojo-tags etc ..

    ReplyDelete
  36. hi vinod,nice tutorial and its helped me a lot ,is it possible to display three colmbo boxs when hanging the values as explained in the above example

    ReplyDelete
  37. Hi Vinod
    Where should I change the id to PID? Do you have the whole code available as a download. Thanks

    ReplyDelete
  38. Hi Vinod

    Its nice example, If u put option for download entire code Its should be very nice
    Thanks

    ReplyDelete
  39. Can someone explain how the second drop down knows the value of the first drop down. That is, how is the field lst of the class DetailAction filled in.

    ReplyDelete
  40. Superb guys, I was struggling from morning, this was an oasis to test how I could integrate ajax with my Struts2 project.

    ReplyDelete
  41. Hi Vinod
    I am working with strut2 and now its new form me. When I used ur given such example its realy good .
    I tried it and got it at first time.
    Thank You.

    Vikram

    ReplyDelete
  42. Hey Vikram

    Enjoy more examples here :)

    ReplyDelete
  43. Hi,Vinod
    Can you explain what exactly the example does?? I want to have 2 jsps. one top and one bottom. when i click the top jsp it should load bottom jsp content without refreshing the page..

    ReplyDelete
  44. have anyone tried of printing the selected values in both the select boxes?
    i just get only the values i select in the first select box and not getting the 2nd select box value...

    pls help..

    ReplyDelete
  45. This is really helpful for me.But I do not understand the ajax part.Can you describe what is happening with each code.

    ReplyDelete
  46. Hi,
    Ajax not working fine when i keep s:file
    component in struts2
    why it is not working fine
    can any one give me ans....

    ReplyDelete
  47. Doesn't work under IE, the form data is not sent to the next action.

    ReplyDelete
  48. very nice article, even to new bee.
    thanks

    ReplyDelete
  49. Hi can enyne explain in details.jsp file?

    ReplyDelete
  50. can i put more than one ajax request in same jsp page?I am not getting it done? please help me.

    ReplyDelete
  51. hi

    i want to populate table from database when i select value from select both select and table should be in same jsp

    any one help me please i am trying it from 4 days its urgent.

    thanks

    ReplyDelete
  52. Hi

    Can anyone tell me that, using above example, how can i place the second combo box directly in listing.jsp instead of getting it from detail.jsp.

    Because, in my application, there are lot of dependencies between combo boxes and creating new jsp for each one is not good.

    Please reply urgently...

    ReplyDelete
  53. Hi

    I want to use second combo box in listing.jsp, instead of getting it from details.jsp

    Creating new jsp for each combo box when multiple dependencies are there is not good way to do.

    Please suggest the possible way as soon as possible.

    ReplyDelete
  54. Excellent example, it works for me, just what i looking for! Thank you so much!

    ReplyDelete
  55. Thanks you admin. this code was very useful for dependent drop down..
    thanks you
    if anybody not got value from 2nd drop down then go through details.jsp and there name="any variable name".. if any qury let me know on my emails mugeesh@gmail.com

    ReplyDelete

Post a Comment

Popular posts from this blog

SSL in Spring Boot using GoDaddy certificate on EC2

In this article, we will be going to see how we can achieve the HTTPS in the spring boot application . You will get lots of items on how to use the self-generated certificate with Spring Boot. But today we are going to use the CA generated certificates with the Spring Boot so that our application will work on HTTPS. We need the following things to work: CA certificates including, private key and certificate. In this article, we are using the GoDaddy wild card certificate. Spring Boot application OpenSSL library Convert the certificate and private key to PKCS 12 First of all, we need to convert the CA certificate to .p12 format . We need to have OpenSSL on the system to work with command. Also, we need to have all files in the same directory where we are running this command. The command required to covert the same: openssl pkcs12 -export -in [ceritificate-name] -inkey [private-key] -name [host] -out [new-file.p12] Here replace the values: [ceritificate-name] with

Getting height and width of image in Java

Yesterday I was working on something that requires manipulation of image for getting its properties. After searching over the internet I found a very intersting class on Java i.e ImageIO and BufferedImage class. These classes are good enough to manipulate images. there are many other claases also. But what I need i got it from these. I found many developers searching over internet for getting properties of image and there is no good small example for that. Thats why I thought why not creating a simple code to manipulate the image and help the developers. Here is the small code that helps to get the height and width of the image. Enjoy it!! import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class GetImage { public static void main(String[] args) { try { File f = new File("E:/Vinod/Docs/Pics/krishna_01.jpg"); BufferedImage image = ImageIO.read(f); int height = image.getHeight(); in