Struts2 JasonInterceptor Тип содержимого должен быть «application / json» или «application / json-rpc» - PullRequest
0 голосов
/ 29 марта 2012

Может ли кто-нибудь объяснить мне, в каких случаях я получаю следующую ошибку в журнале?

Struts2 JasonInterceptor Тип содержимого должен быть «application / json» или «application / json-> rpc».Игнорирование запроса с типом контента application / x-www-form-urlencoded

Я также заметил, что в IE он показывает сообщение отладки следующим образом (не уверен, что эти 2 сообщения связаны):

DEBUG: рассмотрите возможность использования mimetype с фильтром text / json-comment, чтобы избежать потенциальных> проблем безопасности с конечными точками JSON. DEBUG: [SyntaxError: Синтаксическая ошибка]

I специальноизменил мой атрибут s: form enctype следующим образом и все еще не смог избавиться от этого сообщения:

<s:form id="dealerForm" action="AjaxAutocompleterAction" 
enctype="text/json-comment-filtered">
</s:form>

и это тоже (не сработало снова)

<s:form id="dealerForm" action="AjaxAutocompleterAction" 
enctype="application/json">
</s:form>

есть идеи?

************* Обновление - 1 *****************

Более подробная информация о коде, с которым я работаю:

My AjaxAutocompleter.jsp содержащий связанные автозаполнения:

<s:form id="dealerForm" action="AjaxAutocompleterAction"
enctype="text/json-comment-filtered">
<sx:autocompleter id="dealer" name="dealer" searchType="substring"
    label="Dealer" list="dealerList" listKey="name" listValue="name"
    showDownArrow="false" valueNotifyTopics="/notifyBranch"
    errorNotifyTopics="/error" beforeNotifyTopics="/before"
    forceValidOption="true" loadMinimumCount="3" />
<sx:autocompleter id="branch" name="branch" searchType="substring"
    label="Branch" list="branchList" showDownArrow="false"
    listenTopics="/notifyBranch" formId="dealerForm"
    formFilter="function(paramName){return true;}"
    valueNotifyTopics="/notifyRep" beforeNotifyTopics="/before"
    afterNotifyTopics="/after" forceValidOption="true"
    loadMinimumCount="0" loadMinimumCount="3" />
<sx:autocompleter id="representative" name="representative"
    searchType="substring" label="Rep" list="repList"
    showDownArrow="false" forceValidOption="true" loadMinimumCount="0"
    formId="dealerForm" formFilter="function(paramName){return true;}"
    listenTopics="/notifyRep" beforeNotifyTopics="/before"
    afterNotifyTopics="/after" loadMinimumCount="3" />
<textarea name="mytextarea" id="mytextarea" rows="25" cols="190"></textarea>
</s:form>

struts.xml

<package name="ajax" extends="json-default">
    <action name="AjaxAutocompleterAction" class="com.frk.gid.action.AjaxAutocompleterAction">
        <interceptor-ref name="json"/>
        <interceptor-ref name="params">
            <param name="ordered">true</param>
        </interceptor-ref>
        <interceptor-ref name="prepare" />
        <result type="json" />
        <result name="success">/AjaxAutocompleter.jsp</result>
    </action>
</package>

мои классы моделей

public class Representative {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class Branch {
    private String name;
    private List<Representative> representatives;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setRepresentatives(List<Representative> representatives) {
        this.representatives = representatives;
    }

    public List<Representative> getRepresentatives() {
        return representatives;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class Dealer {
    private String name;
    private List<Branch> branches;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setBranches(List<Branch> branches) {
        this.branches = branches;
    }

    public List<Branch> getBranches() {
        return branches;
    }

    @Override
    public String toString() {
        return name;
    }
}

мой метод подготовки

@Override
public void prepare() throws Exception {
    logger.info("Prepare Started ...");
    ServletActionContext.getResponse().setContentType(
            "text/json-comment-filtered");
    dealerList = new ArrayList<Dealer>();
    int branchCounter = 0;
    int repCounter = 0;

    for (int i = 0; i < 5; i++) {
        Dealer d = new Dealer();
        List<Branch> branches = new ArrayList<Branch>();
        for (int j = 0; j < 3; j++) {
            Branch b = new Branch();
            b.setName("BRANCH-" + branchCounter++);
            List<Representative> representatives = new ArrayList<Representative>();
            for (int k = 0; k < 2; k++) {
                Representative rep = new Representative();
                rep.setName("REP-" + repCounter++);
                representatives.add(rep);
            }
            b.setRepresentatives(representatives);
            branches.add(b);
        }
        d.setName("DEALER-" + i);
        d.setBranches(branches);
        dealerList.add(d);
        if (this.dealer == null && i == 0) {
            setDealer(d.getName());
        }

        // Populate DBR Hierarchy for the selected dealer.
        if (this.dealer != null && this.dealer.equals(d.getName())) {
            branchList = new ArrayList<String>();
            int bCount = 0;
            for (Branch b : branches) {
                branchList.add(b.getName());
                if (this.branch == null && bCount++ == 0) {
                    setBranch(b.getName());
                }
                if (this.branch != null && this.branch.equals(b.getName())) {
                    repList = new ArrayList<String>();
                    for (Representative r : b.getRepresentatives()) {
                        repList.add(r.getName());
                    }
                    if ((this.representative == null && repList.size() > 0)
                            || (this.representative != null && !repList
                                    .contains(this.representative))) {
                        setRepresentative(repList.get(0));
                    }
                }
            }

        }
    }

1 Ответ

0 голосов
/ 30 марта 2012

Ладно ... наконец, после большой борьбы, мне удалось решить это самому. подсказка лежит в моем определении автозаполнения, где мне приходилось использовать dataFieldName всегда, когда я использовал href.

Кроме того, я не смог загрузить иерархию первого уровня (в моем случае Dealer) для работы с href -i пришлось явно вызывать действие и использовать локальную переменную.

Я публикую свой модифицированный код, чтобы он мог пригодиться другим учащимся :-) Удачи !!!

Мой обновленный JSP

<s:url id="dbrList" action="AjaxAutocompleterAction" 
encode="text/json-comment-filtered"/>
<s:action name="AjaxAutocompleterAction" id="myDBRAction" />
<sx:autocompleter id="dealerList" name="dealer" searchType="substring"
    label="Dealer" showDownArrow="false" valueNotifyTopics="/notifyBranch"
    errorNotifyTopics="/error" beforeNotifyTopics="/before"
    forceValidOption="true" loadMinimumCount="1"
    list="%{#myDBRAction.dealerList}" />

<sx:autocompleter id="branchList" name="branch" searchType="substring"
    label="Branch" list="branchList" showDownArrow="false"
    listenTopics="/notifyBranch" formId="dealerForm"
    formFilter="function(paramName){return true;}"
    valueNotifyTopics="/notifyRep" beforeNotifyTopics="/before"
    afterNotifyTopics="/after" errorNotifyTopics="/error"
    forceValidOption="true" loadMinimumCount="1" href="%{dbrList}"
    list="branchList" dataFieldName="branchList" />
<sx:autocompleter id="repList" name="representative"
    searchType="substring" label="Rep" list="repList"
    showDownArrow="false" forceValidOption="true" formId="dealerForm"
    formFilter="function(paramName){return true;}"
    listenTopics="/notifyRep" beforeNotifyTopics="/before"
    errorNotifyTopics="/error" afterNotifyTopics="/after"
    loadMinimumCount="1" href="%{dbrList}" dataFieldName="repList" />

Мои обновленные struts.xml

<package name="ajax" extends="json-default">
    <result-types>
        <result-type name="json"     class="org.apache.struts2.json.JSONResult" />
    </result-types>
    <action name="AjaxAutocompleterAction" class="com.frk.gid.action.AjaxAutocompleterAction">
        <interceptor-ref name="json">
            <param name="contentType">application/json</param>
        </interceptor-ref>
        <interceptor-ref name="jsonValidation" />
        <interceptor-ref name="params">
            <param name="ordered">true</param>
        </interceptor-ref>
        <interceptor-ref name="prepare" />
        <result name="success" type="json">
            <param name="contentType">text/html</param>
        </result>
    </action>
</package>
...