質問

指定されているように、JSONでスプリングMVCを使用しています Ajax Simplification Spring 3.0の記事.

さまざまなフォーラムで見つかったアドバイスに応じて、コードの非常に多くの試みとバリエーションの後、私のコードはまだ機能しません。

次のエラーを取得し続けます。(406)このリクエストによって特定されたリソースは、リクエスト「受け入れ」ヘッダー()に従って許容されない特性を持つ応答を生成することができます。

必要に応じて、appconfig.xmlにあります。

app-config.xml

    <context:component-scan base-package="org.ajaxjavadojo" />

    <!-- Configures Spring MVC -->
    <import resource="mvc-config.xml" />

MVC-config.xml

<mvc:annotation-driven />

<!-- Forwards requests to the "/" resource to the "index" view -->
<mvc:view-controller path="/" view-name="index"/>


<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
  <entry key="html" value="text/html"/>
  <entry key="json" value="application/json"/>
</map>
</property>
<property name="viewResolvers">
<list>
  <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
</list>
</property>

</bean>

これは私がコントローラーのために持っているものです

@Controller
@RequestMapping (value = "/convert")
public class ConversionController {

  @RequestMapping(method=RequestMethod.GET)
  public String getConversionForm(){
    return "convertView";
  }

  @RequestMapping(value = "/working", headers="Accept=application/json", method=RequestMethod.GET)
  public @ResponseBody Conversion getConversion(){
    Conversion d = new Conversion("d");
    return d;
  }
}

jsp jqueryコール

  function convertToDecimal(){
    $.getJSON("convert/working", {key: "r"}, function(aConversion){
      alert("it worked.");
      $('#decimal').val(aConversion.input);
    });
  }

この問題に関する意見を本当に感謝しています。ありがとうございました

役に立ちましたか?

解決

ヘッダーの制限を削除してみてください Accept, 、ブレークポイントを入れて、実際の値が何であるかを確認します。または、FireBugでこれを行います。

また、見てください このjQueryの問題

他のヒント

からJSON応答を返すため @ResponseBody-Anntated Methodには、2つのことが必要です。

必要はありません ContentNegotiatingViewResolverheaders@RequestMapping.

Springを3.2.xから4.1.xにアップグレードした後、この問題が発生しました。ジャクソンを1.9.xから2.2.x(fasterXML)にアップグレードして修正しました

 <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.2.3</version>
</dependency>

追加 org.springframework.http.converter.json.MappingJacksonHttpMessageConverterorg.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter Dispatcherservlet-servlet.xmlへ。そして、使用して2番目の最初のものを参照してください

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>

私もこのエラーがあり、ウサギの穴に深くデバッグしている間、私はこの例外に出会いました

java.lang.illegalargumentexception:プロパティ「エラー」の競合するゲッター定義:com.mycomp.model.outputjsonmodel#iserror(0 params)vs com.mycomp.model.outputjsonmodel#getError(0 params)

だから基本的に私のJava Beanで私は次のようなものを持っていました:

private boolean isError;
private ErrorModel error;

public ErrorModel getError() {
return error;
}

public void setError(ErrorModel error) {
this.error = error;
}
public boolean isError() {
return isError;
}

public void setError(boolean isError) {
this.isError = isError;
}

エラーメンバー変数名の1つを他の何かに変更すると、問題が解決しました。

私もこの問題を抱えていました、あなたは追加する必要があります <mvc:annotation-driven /> 構成XML

<!-- Jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.databind-version}</version>
        </dependency>

pom.xmlで

Java構成を使用しましたが、同じエラーが発生しました。 @enablewebmvcを構成ファイルに追加することを逃しました。このエラーは、WebConfigファイルに@EnableWebMVCを追加した後に解決されます。

また、スプリングコントローラーから返されるオブジェクトには、適切なゲッターとセッターのメソッドが必要です。

package com.raghu.dashboard.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.raghu.dashboard.dao.ITaskDAO;
import com.raghu.dashboard.dao.TaskDAOImpl;


    @Configuration
    @EnableWebMvc  //missed earlier...after adding this it works.no 406 error
    @ComponentScan(basePackages = { "com.raghu.dashboard.api", "com.raghu.dashboard.dao" })
    public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

        protected Class<?>[] getRootConfigClasses() { return null;}

        protected Class<?>[] getServletConfigClasses() {
            return new Class[] { MongoConfiguration.class};
        }

        protected String[] getServletMappings() {
            return new String[]{"*.htm"}; 
        }

        @Bean(name = "taskDao")
        public ITaskDAO taskDao() {
            return new TaskDAOImpl();
        }

        @Bean
        public InternalResourceViewResolver getInternalResourceViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/pages/");
            resolver.setSuffix(".jsp");
            return resolver;
        }

    }

appinitializer.java

package com.raghu.dashboard.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
    public class AppInitalizer implements WebApplicationInitializer {

        @Override
        public void onStartup(ServletContext servletContext)
                throws ServletException {
            WebApplicationContext context = getContext();
            servletContext.addListener(new ContextLoaderListener(context));
            ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping("/*");
        }

        private AnnotationConfigWebApplicationContext getContext() {
            AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
            context.register(com.raghu.dashboard.config.WebConfig.class);
            context.scan("com.raghu.dashboard.api");
            return context;
        }

    }

また、返されるオブジェクトに適切なゲッターとセッターがあることを確認してください。

例:

@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<TaskInfo> findAll() {
    logger.info("Calling the findAll1()");
    TaskInfo taskInfo = dashboardService.getTasks();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    ResponseEntity<TaskInfo> entity = new ResponseEntity<TaskInfo>(taskInfo,
            headers, HttpStatus.OK);
    logger.info("entity is := " + entity);
    return entity;
}

TaskInfoオブジェクトには、適切なゲッターとセッターが必要です。そうでない場合、406エラーがスローされます。

参照用のPOMファイル:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.raghu.DashBoardService</groupId>
    <artifactId>DashBoardService</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>DashBoardService Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- Spring -->
        <spring-framework.version>4.0.6.RELEASE</spring-framework.version>
        <jackson.version>2.4.0</jackson.version>
        <jaxb-api.version>2.2.11</jaxb-api.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.10.1</version>
        </dependency>
        <!-- Spring Data Mongo Support -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.4.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring-framework.version}</version>
</dependency>


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-dao</artifactId>
    <version>2.0.3</version>
</dependency>



        <!-- Jackson mapper -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>1.7.1</version>
        </dependency>

        <!-- Log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>1.5.0.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>DashBoardService</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

問題はjQueryとは関係ありません。バグでさえ、それがサーバー側の問題であると言っています。クラスパスに存在する2つのジャーが次のことを確認してください: -

Jackson-Core-ASL-1.9.X.Jar Jackson-Mapper-Asl-1.9.x.jar

私もこの同じ問題に直面し、この[jar]をダウンロードしました:(http://www.java2s.com/code/jar/j/downloadjacksonall190jar.htm)! libフォルダーに配置され、アプリは魅力のように機能します:)

見る ここで同様の問題に対する私の答え スプリングMVCがURIの拡張を解釈し、舞台裏で生成される予想されるMIMEタイプを変更すると、406が生成されます。

まあ、このページの答えは正しいかもしれませんが、それらはうまく駐在しませんでした。これが私がしたことです

これをpom.xmlに追加しました

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.8</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.8</version>  
</dependency>

次に、以下のようにリクエストマッピングにヘッダーを追加しました

@RequestMapping(value="/admin/getGallery", method = RequestMethod.GET, headers={"Content-Type=application/json"})

それから私のjquery ajaxで私が追加した-contentType: "Application/JSON"なので、

jQuery.ajax({
            type:'GET',
            url:"getGallery.html",
            data: "designId="+designId,
            processData:false,
            contentType: "application/json",
            //dataType: "json",
           success:function(data){
              console.log(data);

           },
            error : function(e) {
                console.log("ERROR: ", e);
            },
        });

それから私のサーブレットに追加しました

<bean id="jsonHttpMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
    <!-- Bind the return value of the Rest service to the ResponseBody. -->
    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
    <util:list id="beanList">
    <ref bean="jsonHttpMessageConverter" />
    </util:list>
    </property>
</bean> 

サーブレットにutilタグに問題がある場合は、同じサーブレットファイルに追加するだけです

xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd

Axtavtが言ったように、MVC:Annotation-strivenとJackson Json Mapperが必要です。私はそれに続いて、コントラから返されるオブジェクトに@xmlrootelementと@xmlelementがある場合、コードを変更せずに同じ方法からJSON文字列とXMLの両方の文字列を返すようにアプリケーションを取得しました。違いは、リクエストまたはヘッダーで渡された受け入れパラメーターにありました。 XMLを返すには、ブラウザからの通常の呼び出しがそれを行い、それ以外の場合は「アプリケーション/XML」として受け入れます。 JSONを返したい場合は、リクエストのAcceptパラメーターで「Application/JSON」を使用します。

Firefoxを使用する場合、TamperDataを使用してこのパラメーターを変更できます

jQueryを使用して、ContentTypeを目的の1つ(Application/JSON; charset = utf-8 ')に設定し、サーバー側で同じヘッダーを設定できます。

テスト中にキャッシュをクリアすることを忘れないでください。

それ以外の @RequestMapping(...headers="Accept=application/json"...) 使用する @RequestMapping(... , produces = "application/json")

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top