簡體   English   中英

415不支持的媒體類型AngularJS到SpringMVC控制器

[英]415 Unsupported Media Type AngularJS to SpringMVC Controller

嘗試將JSON數據從angularjs控制器發布到SpringMVC控制器時遇到此錯誤。 我已經嘗試過這里發布的許多解決方案,以及網上其他可用的東西。 我的類路徑中已經有傑克遜圖書館。 而且由於互聯網問題,我不使用Maven。

SpringMVC控制器

@Controller
public class MainController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "/employee", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    String saveEmployee(@RequestBody Employee employee) {

        //Will do some stuff here.
        System.out.println("INSIDE CONTROLLER");
        StringBuilder json = new StringBuilder();

        return json.toString();
    }
}

AngularJS控制器

app.controller('saveEmployeeCtrl', function ($scope, $http) {
    $scope.employee = {};

    $scope.saveEmployee = function () {
        $http({
            method: 'POST',
            url: 'employee',
            data: $scope.employee,
            headers:{'Accept':'application/json', 'Content': 'application/json'}
        }).success(function(data){
           console.log('something nice'); 
        });
    };
});

Web配置

@EnableWebMvc
@Configuration
@ComponentScan("springmvc.com.")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webapp/resources/static/app/**")
                .addResourceLocations("/webapp/resources/static/app/");
        registry.addResourceHandler("/webapp/resources/static/lib/**")
                .addResourceLocations("/webapp/resources/static/lib/");
        registry.addResourceHandler("/webapp/resources/static/js/**")
                .addResourceLocations("/webapp/resources/static/js/");
        registry.addResourceHandler("/webapp/resources/static/css/**")
                .addResourceLocations("/webapp/resources/static/css/");
        registry.addResourceHandler("/webapp/webapp/resources/static/views/**")
                .addResourceLocations("/webapp/webapp/resources/static/views/");
        registry.addResourceHandler("/webapp/resources/static/**")
                .addResourceLocations("/webapp/resources/static/");
    }

    @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
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

WebAppInitializer

public class WebAppInitializer implements WebApplicationInitializer {

    private static final String CONFIG_LOCATION = "springmvc.com.config";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        System.out.println("***** Initializing Application for " + servletContext.getServerInfo() + " *****");

        // Create ApplicationContext
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.setConfigLocation(CONFIG_LOCATION);

        // Add the servlet mapping manually and make it initialize automatically
        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);

        servlet.addMapping("/");
        servlet.setAsyncSupported(true);
        servlet.setLoadOnStartup(1);
    }
}
  1. 您正在發送標頭“ Content”,但應發送“ Content-Type”
  2. 您是否在JSON中發送與Employee類中完全相同的字段,請檢查是否沒有其他字段,因為Jackson設置為如果設置了無法識別的字段,它將失敗。 並且有一些針對此問題的解決方案(例如您班上的注釋或更改此設置)

最重要的是服務器應用程序的日志文件中顯示的內容。 引發什么異常是導致此http狀態的原因。 因此,如果上述解決方案對您沒有幫助,請檢查日志(也許增加春季的日志級別)並將其發布在此處。

更新:

我還有幾個其他問題:

  • 您的Employee類是否具有默認(非args)構造函數,或者僅使用參數創建了構造函數? 您能張貼您的Employee類嗎?
  • 您的項目是否有任何記錄器,日志文件中是否有任何記錄(如果有,請發布)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM