programing

스프링 MVC + JSON = 406 사용 불가

nicegoodjob 2023. 3. 6. 22:23
반응형

스프링 MVC + JSON = 406 사용 불가

JSON을 사용하다제406조 받아들일 수긍 불가.은 ""accept헤더에 되지 않는 할 수 뿐"이라고 응답은 Tomcat이 "accept"라고 합니다.고고말말말말다다Accept는 "syslog"입니다.

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Tomcat/lib에는 모든 Tomcat jars, Spring jars 및 jackson-all-1.9.0.jar가 있습니다.Tomcat 7에서 Spring 3.2.2를 사용하고 있습니다.

이 문제가 여러 번 논의된 것은 알고 있지만, 어떤 해결책도 제게는 효과가 없습니다.

web.xml

<web-app id="WebApp_ID" version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Spring Web MVC Application</display-name>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
        <servlet-class>
                  org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

</web-app>

dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 <context:component-scan base-package="com.smiechmateusz.controller" />
 <context:annotation-config />

    <mvc:annotation-driven />

</beans>

HelloWorldController.java

package com.smiechmateusz.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.smiechmateusz.dao.Foo;

@Controller
@RequestMapping("/")
public class HelloWorldController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView("HelloWorldPage");
        return model;
    }

    @RequestMapping(value="foobar.htm", method = RequestMethod.GET)
    public @ResponseBody Foo getShopInJSON() {
        Foo f = new Foo();
        f.setX(1);
        f.setY(2);
        f.setDescription("desc");
        return f;
    }
}

푸자바

package com.smiechmateusz.dao;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="foobaz")
public class Foo implements Serializable
{
    private int x, y;
    String description;
    int id;

    @Column(name = "x")
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    @Column(name = "y")
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    @Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    @Id @GeneratedValue
    @Column(name = "id")
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}

나는 이미 추가하려고 했다.

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

dispatcher-servlet.xml 또는 jakcson-alljackson-asljackson-core-asl로 변경하지만 출력은 동일합니다.

Maven과 최신 Jackson 코드를 사용하는 경우 스프링 구성 XML 파일에서 잭슨 고유의 설정을 모두 삭제하고(주석 기반 태그 <mvc:annotation-drived/>가 필요함) pom.xml 파일에 잭슨 종속성을 추가할 수 있습니다.종속성의 예에 대해서는, 이하를 참조해 주세요.이것은 나에게 효과가 있었고, 나는 다음을 사용하고 있다.

  • Apache Maven 3.0.4 (r1232337; 2012-01-17 01:44:56-0700)
  • org.springframework 버전 3.1.2.풀어주다
  • spring-security 버전 3.1.0 입니다.풀어주다.

    ...<dependencies>
    ...
        <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>
        ...
    </dependencies>...
    

이 에러가 발생하는 또 하나의 방법은 퍼블릭멤버가 없는 클래스를 만드는 것입니다.406 unacceptive는 이 시나리오에서는 매우 쓸모없는 오류 메시지입니다.

동의: text/html, application/xhtml+xml, application/xml;q=0.9,/;q=0.8

JSON으로 .application/json. (헤더할 수 의 '가 가장 (Firefox의 '포스터'가 가장 좋습니다.)Firefox )) " Poster " 。

에는 Spring .@EnableWebMvc예를 들어 다음과 같습니다.

@Controller
@EnableWebMvc
@RequestMapping(value = "/articles/action", headers="Accept=*/*",  produces="application/json")
public class ArticlesController {

}

다른 대답들은 전혀 도움이 되지 않았다.

406 Not Acceptable, Http Media Type Not Acceptable에 대한 Stackoverflow 답변을 수십 개 읽었습니다.예외, 멀티파트 파일, Response Body, Accept 헤더 설정, 생성, 소비 등

Spring 4.2.4와 Spring Boot 및 Jackson을 build.gradle로 구성했습니다.

compile "com.fasterxml.jackson.core:jackson-core:2.6.7"
compile "com.fasterxml.jackson.core:jackson-databind:2.6.7"

다른 컨트롤러에서는 모든 루트가 정상적으로 동작하며 GET, POST, PUT 및 DELETE를 사용할 수 있습니다.그 후 멀티파트 파일 업로드 기능을 추가하여 새로운 컨트롤러를 만들었습니다.GET 루트는 정상적으로 동작하지만 POST와 DELETE는 동작하지 않았습니다.여기서 어떻게 다른 솔루션을 시도해도 406 Not Acceptable이 계속 되었습니다.

그러다가 우연히 SO의 답을 발견했습니다.Http Media Type Not Acceptable을 던지는 입니다.예외: URL 경로의 점으로 인해 허용 가능한 표현을 찾을 수 없습니다.

라니즈의 답변과 모든 코멘트를 읽어주세요.

이 모든 것은 @RequestMapping 값으로 요약됩니다.

@RequestMapping(value = "/audio/{fileName:.+}", method = RequestMethod.POST, consumes="multipart/*")
public AudioFileDto insertAudio(@PathVariable String fileName, @RequestParam("audiofile") MultipartFile audiofile) {

    return audioService.insert(fileName, audiofile);
}

@RequestMapping(value = "/audio/{fileName:.+}", method = RequestMethod.DELETE)
public Boolean deleteAudio(@PathVariable String fileName) {

    return audioService.remove(fileName);
}

{fileName:.+}@RequestMapping 406 Not Acceptable 。

라니즈의 답변에서 추가한 코드는 다음과 같습니다.

@Configuration
public class ContentNegotiationConfig extends WebMvcConfigurerAdapter {
    @Override
    void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
        // Turn off suffix-based content negotiation
        configurer.favorPathExtension(false);
    }
}

2016년 8월 29일 편집:

이 때문에 문제가 발생하였습니다.configurer.favorPathExtension(false): SVG를 선택합니다.「Spring」SVG SVG 「image/svg+xml」의 컨텐츠 타입 「application/octet-stream」의 UI.를 해결하려면 을 전송해야 합니다.

@RequestMapping(value = "/audio", method = RequestMethod.DELETE)
public Boolean deleteAudio(@RequestParam String fileName) {

    return audioService.remove(fileName);
}

★★도했습니다.configurer.favorPathExtension(false)다른 방법으로는 경로에서 fileName을 인코딩하는 방법이 있는데, 더 이상의 부작용을 피하기 위해 쿼리 파라미터 방식을 선택했습니다.

POM에 아래의 의존관계를 사용하세요.

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

잭슨의 주석 바인딩을 spring-mvc-config.xml에 등록해야 합니다.다음은 예를 제시하겠습니다.

<!-- activates annotation driven binding -->
<mvc:annotation-driven ignoreDefaultModelOnRedirect="true" validator="validator">
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
    </mvc:message-converters>
</mvc:annotation-driven>

다음으로 컨트롤러에서 다음을 사용할 수 있습니다.

@RequestMapping(value = "/your_url", method = RequestMethod.GET, produces = "application/json")
@ResponseBody

Request Mapping(foobar.htm)에서 *.htm 확장자를 사용한 것이 문제였던 것 같습니다.footer.json 또는 다른 것으로 변경해 보십시오.

정답 링크: https://stackoverflow.com/a/21236862/537246

추신.

개발자가 A부터 Z까지 Spring의 API 전체를 알고 있는 것은 기본적으로 Spring과 같습니다.그리고 세부사항 없이 "406 not acceptable"만 표시하면 Tomcat 로그는 비워집니다!

내선 번호에 문제가 있는 것을 확인합니다.확장에 따라 스프링은 내용 유형을 파악할 수 있습니다.URL .com으로 끝나는 경우 텍스트/html이 content-type 헤더로 전송됩니다.스프링의 동작을 변경하려면 다음 코드를 사용하십시오.

@Configuration
@Import(HibernateConfig.class)
@EnableWebMvc
// @EnableAsync()
// @EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.azim.web.service.*",  basePackageClasses = { WebSecurityConfig.class }, excludeFilters = { @ComponentScan.Filter(Configuration.class) })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false)
                .defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
    }

    @Bean(name = "validator")
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }
}

여기서는 preferPathExtension을 false로, 기본 Content-type을 Application/json으로 설정합니다.메모: Hibernate Config 클래스에는 모든 콩이 포함되어 있습니다.

이치 경우에는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★.web.xml 있다

   <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

은 "URL"을 가지고 ..html예:.../getUsers.html하지만 컨트롤러에 JSON 데이터를 반환하고 있습니다. .html 확장자는 기본적으로 html 타입을 html로 받습니다.

그래서 다음과 같이 바꿨습니다.

web.xml:

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.html</url-pattern>
    <url-pattern>*.json</url-pattern>
</servlet-mapping>

URL:

.../getUsers.json

지금은 모든 게 잘 되고 있어요.도움이 됐으면 좋겠다.

추가해 보다

@RequestMapping(method = RequestMethod.GET,headers = {"Accept=text/xml, application/json"})

getShopInJSON().

그것은 나에게 효과가 있었다.

POJO의 모든 분야에서 Getter와 Setter가 필요할 수 있습니다.

저는 이 문제에 따라 수정했습니다.참조:스프링 MVC - Http Media Type Not Acceptable예외

그리고 406은 버그를 수정하는 데 유용한 메시지가 아닙니다.코드를 디버깅하여 예외의 의미를 확인해야 합니다.

이는 jsp에서 오브젝트를 받아들일 수 없기 때문입니다.그의 것을 사용하다

이 종속성 또는 변환된 다른 전송 json 문자열을 jsp에 추가합니다...

예를 들어 이것을 pom에 추가한다.

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

다음과 같은 코드를 사용합니다.

@RequestMapping(value="foobar.htm", method = RequestMethod.GET)
    public @ResponseBody String getShopInJSON() {
        Foo f = new Foo();
        f.setX(1);
        f.setY(2);
        f.setDescription("desc");
        return new Gson().toJson(f); //converted object into json string
    }//return converted json string

json 출력을 생성/수신하려고 하는 것 같습니다.접근법에 두 가지 문제가 있습니다. 1) Accept 헤더에 application/json을 지정하지 않았습니다 2) @RequestMapping에 products="application/json"을 지정해야 합니다.

여기에서는 답변으로 볼 수 없었기 때문에 Json으로 반환될 것으로 기대했던 클래스의 getter/setter를 실수로 제거했을 때 spring 4.2에서 이 오류가 발생했다고 언급하려고 합니다.

★★★RequestMapping값은 .disclos로 끝나 있습니다.이것은 다른 것이어야 합니다.

.json으로 바꾸려고 했는데 잘 되더라고요.

유사한 문제가 발생하여 아래 코드를 사용하여 해결했습니다.

public class ProductList {

    private List<Product> productList =  new ArrayList<Product>();

    @JsonProperty("data")
    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
    public List<Product> getProductList() {
        return productList;
    }
public void setProductList(List<Product> productList) {
        this.productList = productList;
    }

I am setting ProductList object in ResponseEntity object and returning from controller.

클래스에서는 JsonSerialize에 주석을 달았고 include 파라미터는 다음과 같이 설정되었습니다.JsonSerialize.Inclusion.NON_DEFAULT이로 인해 잭슨은 각 콩 속성의 기본값을 결정하게 되었습니다.인트이 경우 빈게터가 리턴 타입이 추측된 메서드(즉, 범용 메서드)를 호출한 것이 문제였습니다.어떤 이상한 이유로 이 코드가 컴파일되었습니다.추정된 반환 유형에 int를 사용할 수 없기 때문에 컴파일되지 않아야 합니다.나는 그 콩 소유지의 'int'를 'integer'로 바꾸었고, 나는 더 이상 406을 얻지 못했다.integer intent.

이 상태가 반환되는 또 다른 사례가 있습니다.잭슨 매퍼가 당신의 콩을 시리얼화하는 방법을 알아낼 수 없는 경우입니다.예를 들어, 같은 부울 속성에 2개의 접근자 방식이 있는 경우,isFoo() ★★★★★★★★★★★★★★★★★」getFoo().

완료getFoo() 리 and를 붙입니다.isFoo()가 있었어그것은 나에게 효과가 있었다.

이 오류에 대한 상위 답변이므로 XML에 대한 사례를 여기에 추가합니다.

반환된 개체가 XML 구조를 올바르게 정의하지 않았을 수도 있습니다.나는 그런 경우였다.

public @ResponseBody DataObject getData(

헤더는 맞는데 같은 에러가 발생하고 있습니다.오브젝트 헤더에 @XmlRootElement를 추가했을 때 오류가 중지되었습니다.

@XmlRootElement
public class DataObject {
    @XmlElement(name = "field", nillable = true)
    protected String field;

같은 문제가 있었습니다.저의 경우 xxx-servlet.xml 설정 파일에서 다음 항목이 누락되었습니다.

<mvc:annotation-driven/>

내가 이걸 넣자마자 작동했어.

동일한 "406" 오류가 발생했지만 근본 원인은 Spring의 개체 => json 전략과 관련이 있습니다.

스프링: 3.2.2.풀어주다

Tomcat: 7

@RequestMapping(value = "/employee/search/v2/{employeeId}")
    public ResponseEntity<EmployeeProfileResponseData> searchEmployeeV2(@PathVariable String employeeId) 

Employee Profile Response Data.java 세그먼트


    private Boolean profileActive;

    public Boolean isProfileActive() {
        return this.profileActive;
    }

    public Boolean getProfileActive() {
        return this.profileActive;
    }

    public void setProfileActive(Boolean profileActive) {
        this.profileActive = profileActive;
    }

「POJO」가 되어 있는 .isProfileActive406을 . , 406을 반환할 입니다.

하지만 메서드를 삭제하면 일반 JSON이 반환됩니다.

그 을 '어느새 하다'로 요.isMyProfileActive반환된 JSON에 새로운 속성이 포함되어 있는 것을 발견했습니다.

{
    ...
    "profileActive": true,
    "myProfileActive": true
}

그리고 무슨 일이 일어났는지 깨달았다.

POJO가 되어 있는 isProfileActive를 spring은 'profileActive'를 생성합니다.son 、 JSON 、 Attribute 、 ( public getter / setter ) 。따라서 이 두 가지 속성이 경합을 일으켰기 때문에 Tomcat은 일반 JSON을 반환하지 않습니다.

그게 바로 "406" 코드의 의미야

HyperText Transfer Protocol(HTTP) 406 Not Acceptable client error response 코드는 서버가 요청의 프로 액티브콘텐츠 네고시에이션헤더에 정의되어 있는 허용치 목록에 일치하는 응답을 생성할 수 없으며 서버가 기본 표현을 제공하지 않음을 나타냅니다.

으로 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★isProfileActive「 」, 「 」

데 b b b 。isProfileActive의해 되고, 제 하지 않고 그 코드를 눌렀습니다.

언급URL : https://stackoverflow.com/questions/16335591/spring-mvc-json-406-not-acceptable

반응형