Необходимо получить список стран для выбора из выпадающего списка select2 посредством вызова ajex, используя действие Struts, но столкнувшись с проблемой. Пожалуйста, помогите мне - PullRequest
0 голосов
/ 08 ноября 2019

Мне нужна помощь, чтобы получить названия стран из json-файла для выпадающего списка select2 с помощью класса действий struts2.

Я написал один JSP-файл для внешнего интерфейса, Struts.xml, web.xml и класс действий Struts. Я получаю сообщение об ошибке при вызове класса действия через select2.

Когда я нажимаю на выпадающий список select2, ajax вызывает метод действия для отображения названий стран в списке. Но ничего не отображается

index.jsp

 <%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<body>

<s:form action="fetchCountries">
    <select class="myselect" name="countriesL.code" style="width: 500px;">
    <option value="0">Select</option>
    </select>
</s:form>

<script type="text/javascript">     
    $(document).ready(function () {
        $('.myselect').select2({
            placeholder: 'Select an item',
            ajax: {
            url: 'fetchCountries',
            dataType: 'json',
            data: function (params) 
            {
                var query = {
                search: params.term,     //this is Sending Input key by search
                userInput: params.term  //this is Sending Input key by userInput
            }
            return query;
            },
        processResults: function (data) 
        { 
            //Return Response
            console.log(data);
            var results = $.map(data.countriesL, function (obj)
        {

        return {
        id: obj.id,
        //text: obj.text
            };
        });
        console.log(results);   //Printing Response
        return {
        results: results,
            };
        },
            "more": true,
            cache: true
        }
        });
        });
    </script type>
</body>
</html>


struts.xml

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>

    <constant name="struts.devMode" value="true" /> 
    <package name="default"  namespace="" extends="struts-default" >    

        <action name="Getountries"
                class="com.getjsondata.Getountries" >
         <result>/index.jsp</result>        
        </action>   

        <action name="fetchCountries" class="com.getjsondata.Getountries" method="findcountry">
        <result name="success"></result>
        </action>               
    </package>

</struts>

класс действий Struts

package com.getjsondata;

import com.opensymphony.xwork2.ActionSupport;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator; 
import java.util.Map; 

import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.*;

public class Getountries extends ActionSupport
{

    String userInput;
    ArrayList<String> countriesL;



    public String getUserInput() {
        return userInput;
    }



    public void setUserInput(String userInput) {
        this.userInput = userInput;
    }



    public ArrayList<String> getCountriesL() {
        return countriesL;
    }



    public void setCountriesL(ArrayList<String> countriesL) {
        this.countriesL = countriesL;
    }


        public String findcountry() throws Exception {

        countries cl = new countries();
        //countriesL=cl.getIdList(userInput);
        countriesL=cl.getcountries(userInput);

        return "success";
  }


}

country.java

package com.getjsondata;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class countries 
{
    public String countryName;
    ArrayList<String> idList = new ArrayList<String>();

    public ArrayList<String> getIdList(String userInput) {
        return idList;
    }

    public void setIdList(ArrayList<String> idList) {
        this.idList = idList;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }



    public ArrayList<String> getcountries(String userInput) throws Exception
    {
    try{
        System.out.println("executing execut() method");
        String path = "C:/Workspace2/Select2Json/resources/countries.json";
        JSONParser parser = new JSONParser();
        JSONArray a = (JSONArray) parser.parse(new FileReader(path));

        for (Object o : a)
          {
            JSONObject person = (JSONObject) o;

            String id = (String) person.get("text");
            idList.add(id);
            System.out.println(id);  

          }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return idList;
    }   
}

пример файла JSON

[
  {
    "id": "AX",
    "text": "Ă…land Islands"
  },
  {
    "id": "PK",
    "text": "Pakistan"
  },
  {
    "id": "SE",
    "text": "Sweden"
  },
  {
    "id": "BV",
    "text": "Bouvet Island"
  }
]
...