`

76. Spring Boot完美解决(406)Could not find acceptable representation原因及解决方法

阅读更多

 

 

【原创文章】

       使用Spring BootWeb项目,处理/login请求的控制器方法(该方法会返回JSON格式的数据)。此时如果访问localhost:8080/login.html,用户期望返回jsons数据,但框架却报错:

 

There was an unexpected error (type=Not Acceptable, status=406).

Could not find acceptable representation

 

 

或者这样的异常信息:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

    at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:235) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]

    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:382) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]

 

 

错误原因:

       Spring BootMVC默认配置中使用的 ViewResolver ContentNegotiatingViewResolver,该视图解析器的功能是根据要请求的文档类型,来查找不同的视图以返回对应格式的文档。请求的文档类型要可以从请求头中的Accept中获取,也可以通过URI后缀名得到,如/login.html即为请求HTML格式的文档,这两种方式分别对应着两种不同的Strategy(策略),默认为根据URI后缀名。

 

ContentNegotiatingViewResolver中有说明:

The ContentNegotiatingViewResolver does not resolve views itself but rather delegates to other view resolvers, selecting the view that resembles the representation requested by the client. Two strategies exist for a client to request a representation from the server: 
• Use a distinct URI for each resource, typically by using a different file extension in the URI. For example, the URIhttp://www.example.com/users/fred.pdf requests a PDF representation of the user fred, and http://www.example.com/users/fred.xmlrequests an XML representation. 
• Use the same URI for the client to locate the resource, but set the Accept HTTP request header to list the media types that it understands. For example, an HTTP request for http:// www.example.com/users/fred with an Accept header set to application/pdf requests a PDF representation of the user fred, while 
http://www.example.com/users/fred with an Accept header set to text/xml requests an XML representation. This strategy is known as content negotiation.

      

        因此,当用户请求 /login.html 时,spring会查找/login对应的控制器,并得到其返回的文档类型为application/json, 然后判断它与后缀名.html文档类型是否匹配,如果不匹配,就报HttpMediaTypeNotAcceptableException了。

       其实它的初衷是好的,它是想实现访问/user.json时返回JSON数据,访问/user.html返回HTML, 访问/user.xml则返回XML的功能。但是在这里我们只用Spring Boot提供RESTful接口,因此该功能就无用武之地了。

 

解决方案

       我们刚才在上面说了Spring 会通过URI后缀获取请求格式,当访问/login.html的时候,那么根据当前的URI获取到后缀.html,那么判断与.html文档类型是否匹配,匹配的话执行相应的解析器。那么我们就会想,我们能够关闭这种默认的后缀匹配规则呢,既然本文章说是完美解决答案就是肯定的。解决步骤就两步骤:

1)在启动类App.java类中继承:WebMvcConfigurerAdapter

2)覆盖方法:configureContentNegotiation

具体代码如下:

package com.kfit;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

 

/**

 *

 * @author Angel --守护天使

 * @version v.0.1

 * @date 2016729下午7:06:11

 */

@SpringBootApplication

public class ApiCoreApp extends WebMvcConfigurerAdapter {

   

    /**

     1)在启动类App.java类中继承:WebMvcConfigurerAdapter

    2)覆盖方法:configureContentNegotiation

   

    favorPathExtension表示支持后缀匹配,

    属性ignoreAcceptHeader默认为fasle,表示accept-header匹配,defaultContentType开启默认匹配。

       例如:请求aaa.xx,若设置<entry key="xx" value="application/xml"/> 也能匹配以xml返回。

根据以上条件进行一一匹配最终,得到相关并符合的策略初始化ContentNegotiationManager  

     */

    @Override

   public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

        configurer.favorPathExtension(false);

    }

    public static void main(String[] args) {

       SpringApplication.run(ApiCoreApp.class, args);

    }

}

       这里说下核心代码:

configurer.favorPathExtension(false);

   favorPathExtension表示支持后缀匹配,

   属性ignoreAcceptHeader默认为fasle,表示accept-header匹配,defaultContentType开启默认匹配。

      例如:请求aaa.xx,若设置<entry key="xx" value="application/xml"/> 也能匹配以xml返回。

 

根据以上条件进行一一匹配最终,得到相关并符合的策略初始化ContentNegotiationManager

 

 à悟空学院:https://t.cn/Rg3fKJD

学院中有Spring Boot相关的课程!点击「阅读原文」进行查看!

SpringBoot视频:http://t.cn/A6ZagYTi

Spring Cloud视频:http://t.cn/A6ZagxSR

SpringBoot Shiro视频:http://t.cn/A6Zag7IV

SpringBoot交流平台:https://t.cn/R3QDhU0

SpringData和JPA视频:http://t.cn/A6Zad1OH

SpringSecurity5.0视频:http://t.cn/A6ZadMBe

Sharding-JDBC分库分表实战http://t.cn/A6ZarrqS

分布式事务解决方案「手写代码」:http://t.cn/A6ZaBnIr

 

 

网易云课堂视频最新更新

第十一章 Spring Boot 日志

1、spring boot日志—理论

2、Spring Boot日志-logback

3、Spring Boot日志-log4j2

第十二章 Spring Boot 知识点2

1、spring boot 服务配置和部署

2、Spring Boot 定制URL匹配规则

 

 

历史章节

 

第一章 快速开始

1、Spring Boot之Hello World

2、Spring Boot之Hello World访问404

 

第二章 Spring Boot之JSON

1、spring boot返回json数据

2、Spring Boot完美使用FastJson解析JSON数据

 

第三章 Spring Boot热部署

1、Spring Boot热部署(springloader)

2、springboot + devtools(热部署)

 

第四章 Spring Boot数据库

1、Spring Boot JPA/Hibernate/Spring Data概念

2、Spring Boot JPA-Hibernate

3、Spring Boot Spring Data JPA介绍

4、Spring Boot JdbcTemplate

5、Spring Boot集成MyBatis

 

第五章 web开发

1、全局异常捕捉

2、配置server信息

3、spring boot使用thymeleaf

4、Spring Boot 使用freemarker

5、Spring Boot添加JSP支持

 

第六章 定时任务

1、Spring Boot定时任务

2、Spring Boot 定时任务升级篇(动态修改cron参数)

3、Spring Boot 定时任务升级篇(动态添加修改删除定时任务)

4、Spring Boot 定时任务升级篇(集群/分布式下的定时任务说明)

5、Spring Boot Quartz介绍

6、Spring Boot Quartz在Java Project中使用

7、Spring Boot 集成Quartz普通使用

8、Spring Boot 集成Quartz升级版

9、Spring Boot 集成Quartz二次升级版

10、Spring Boot 集成Quartz-Job如何自动注入Spring容器托管的对象

 

第七章 Spring Boot MyBatis升级篇

1、Spring Boot MyBatis升级篇-注解

2、Spring Boot MyBatis升级篇-注解-自增ID

3、Spring Boot MyBatis升级篇-注解-增删改查

4、Spring Boot MyBatis升级篇-注解-分页查询

5、Spring Boot MyBatis升级篇-注解-分页PageHelper不生效

6、Spring Boot MyBatis升级篇-注解- mybatic insert异常:BindingException: Parameter 'name' not found

7、Spring Boot MyBatis升级篇-注解- #和$符号特别篇

8、Spring Boot MyBatis升级篇-注解-@Result

9、Spring Boot MyBatis升级篇-注解-动态SQL(if test)-方案一:<script>

10、Spring Boot MyBatis升级篇-注解-动态SQL(if test)-方案二:@Provider

11、Spring Boot MyBatis升级篇-注解-动态SQL-参数问题

12、Spring Boot MyBatis升级篇-注解-特别篇:@MapperScan和@Mapper

13、Spring Boot MyBatis升级篇-XML

14、Spring Boot MyBatis升级篇-XML-自增ID

15、Spring Boot MyBatis升级篇-XML-增删改查

16、Spring Boot MyBatis升级篇-XML-分页查询

17、Spring Boot MyBatis升级篇-XML-分页PageHelper不生效

18、Spring Boot MyBatis升级篇-XML-动态SQL(if test)

19、Spring Boot MyBatis升级篇-XML-注解-初尝试

20、Spring Boot MyBatis升级篇- pagehelper替换为pagehelper-spring-boot-starter

 

第八章 Spring Boot 知识点1

1、Spring Boot 拦截器HandlerInterceptor

2、Spring Boot启动加载数据CommandLineRunner

3、Spring Boot环境变量读取和属性对象的绑定

4、Spring Boot使用自定义的properties

5、Spring Boot使用自定义的properties

6、Spring Boot使用@SpringBootApplication

7、Spring Boot 监控和管理生产环境

 

第十章 Spring Boot 打包部署

1、Spring Boot打包部署((提供Linux的sh文件))

 

第十一章 Spring Boot 日志

1、spring boot日志—理论

2、Spring Boot日志-logback

 

3、Spring Boot日志-log4j2

 

更多查看博客: http://412887952-qq-com.iteye.com/

 

分享到:
评论
3 楼 林祥纤 2018-04-26  
zhang89xiao 写道
南有令秧 写道
有个问题,springmvc中可以拦截指定的请求,需要在web.xml中配置,那么如果在springboot如何实现呢?

  可以再properties 或者 ylm 文件中配置.


你谁对的。(properties或者yml)


2 楼 zhang89xiao 2016-11-09  
南有令秧 写道
有个问题,springmvc中可以拦截指定的请求,需要在web.xml中配置,那么如果在springboot如何实现呢?

  可以再properties 或者 ylm 文件中配置.
1 楼 南有令秧 2016-09-10  
有个问题,springmvc中可以拦截指定的请求,需要在web.xml中配置,那么如果在springboot如何实现呢?

相关推荐

    Whether mandatory donation is acceptable or not?

    Whether mandatory donation is acceptable or not?

    SIP rfc3261 协议下载

    SIP 协议 会话初始协议 很有帮助 Contents 1 Introduction 9 2 Overview of SIP Functionality 10 3 Terminology 11 4 Overview of Operation 11 5 Structure of the Protocol 16 6 Definitions ...

    DebuggingWithGDB 6.8-2008

    Table of Contents Summary of gdb . . . . . . . . ....Free Software ....Free Software Needs Free Documentation ....Contributors to gdb....1 A Sample gdb Session ....2 Getting In and Out of gdb ....2.1 Invoking gdb ....

    利用dcmtk实现C-FIND SCU

    专栏博文“DICOM:基于DCMTK实现C-FIND SCU”中对应的源代码。基于dcmtk开源库中的findscu工程,实现的简单的C-FIND SCU,用于示范如何使用dcmtk操作实现具体的DICOM应用。

    elasticsearch-head

    ## Synopsis ... ## Motivation This was created because ElasticSearch 5 removed the ability to run ElasticSearch Head as an Elastic Plugin. This offers an alternative to self-hosting in your own web ...

    jackson-core-asl-1.9.13及jackson-mapper-asl-1.9.13架包.rar

    可用于Spring MVC框架,spring MVC中返回使用@ResponseBody注解返回时,后台没报错,就控制台显示406 Not Acceptable 原因是缺少jackson的包:jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar

    ANSI-ASHRAE Standard 62.1-2019 Ventilation for Acceptable Indoor

    ANSI-ASHRAE Standard 62.1-2019 Ventilation for Acceptable Indoor

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, ...

    jackson的包:jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar

    spring MVC中返回使用@ResponseBody注解返回时,后台没报错,就控制台显示406 Not Acceptable 原因是缺少jackson的包:jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar

    socket网络编程讲解

    /* The WinSock DLL is acceptable. Proceed. */ //1.创建套接字 SOCKET sockClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(INVALID_SOCKET == WSAGetLastError()) MessageBox(NULL, "Create ...

    servlet2.4doc

    Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. -------------------------------------------------------------------------------...

    php.ini-development

    directive because it is not set or is mistyped, a default value will be used. ; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one ; of the INI constants (On, Off, True, ...

    Resizes Images to sizes acceptable by half life for transiti

    Resizes Images to sizes acceptable by half life for transitioning into pldecal.wad files This code is incomplete... A Majority of the programming has been accomplished.

    Linux-jpcap-gcc

    configure: error: no acceptable C compiler found in $PATH ------------------------ linux 中,安装,提示缺少其他一些组件,经过来回搜索与拷贝,GCC安装成功,所需文件有: libf2c-3.3.2-1.i386.rpm libstdc -devel...

    Agile.Information.Security.Using.Scrum.1511804246

    In Agile Information Security, James Fitzer ...What is Acceptable Risk? Compliance and Agility Implementing Controls, Prevention, Monitoring, and Response Final Thoughts Bibliography About the Author

    rsh软件(LoadRunner监控Linux)

    解决办法:照上述方法安装rpc.rstatd并开启即可监控Linux. 2. configure: error: no acceptable C compiler found in $PATH 原因:未安装gcc编译器. 在命令行里敲入gcc –v, 如果提示command not found 就表示...

    Windows Forensic Analysis Including DVD Toolkit.pdf

    tems.It does not cover everything that could possibly be addressed.There is still considerable room for research in several areas,and a great deal of information needs to be catalogued.My hope is that...

    英语四级整理笔记.doc

    31. Despite the wonderful acting and well-developed plot the _B_ movie could not hold our attention. A three-hours B three-hour C three-hours’ D three-hour’s 267. Professor White wrote a _C_ report ...

    sip RFC3261 中文版

    21.4.7 406 Not Acceptable 209 21.4.8 407 Proxy Authentication Required 209 21.4.9 408 Request Timeout 210 21.4.10 410 Gone 210 21.4.11 413请求实体过大。 210 21.4.12 414 Request-URI Too Long 210 21.4....

    SIP - Understanding the Session Initiation Protocol, 2nd Ed - 1459

    5.4.7 406 Not Acceptable 115 5.4.8 407 Proxy Authentication Required 115 5.4.9 408 Request Timeout 116 5.4.10 409 Conflict 116 5.4.11 410 Gone 116 5.4.12 411 Length Required 116 5.4.13 413 Request ...

Global site tag (gtag.js) - Google Analytics