406尝试解析从Spring-MVC Controller

时间:2017-08-03 07:44:26

标签: java json spring-mvc jackson

我正在尝试从我的控制器传递一个对象列表,我必须在我的jsp中显示它。但是我得到了例外,

[org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] (http-localhost/127.0.0.1:8080-1) Handler execution resulted in exception: Could not find acceptable representation

问题是即使使用produces = "application/json"

,控制器内的标头也未正确设置

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

也许这可能是由于例外 Handler execution resulted in exception: Could not find acceptable representation

在浏览器中显示406错误

  

JBWEB000126:此请求标识的资源只能根据请求生成具有不可接受的特征的响应。接受'头。

我无法找到答案,

我已经检查了类似的帖子,但说明的答案并没有帮助我解决我的问题。

我用过罐子

1)jackson-mapper-asl-1.9.13.jar

2)jackson-core-asl-1.9.13.jar

3)jackson-databind-2.8.7.jar

4)jackson-core-2.8.7.jar

5)jackson-annotations-2.8.7.jar

6)jackson-datatype-joda-2.8.7.jar

7)jackson-jaxrs-json-provider-2.8.7.jar

8)jackson-module-jaxb-annotations-2.8.7.jar

我认为只需要第一个。

我没有使用maven结构,所以没有pom.xml。我没有对AppConfig或WebInitializer进行任何其他更改(我使用的是java配置而不是xml)

以下是我的AppConfig

 @Configuration
 @EnableWebMvc
 @ComponentScan(basePackages = "com.myapps.empregister")
 public class AppConfig extends WebMvcConfigurerAdapter {


@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .defaultContentType(MediaType.TEXT_HTML)
            .parameterName("type")
            .ignoreUnknownPathExtensions(false)
            .ignoreAcceptHeader(true)
            .favorParameter(true)
            .favorPathExtension(false)
            .useJaf(true);
}

@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setContentNegotiationManager(manager);

    // Define all possible view resolvers
    List<ViewResolver> resolvers = new ArrayList<ViewResolver>();

    resolvers.add(jsonViewResolver());
    resolvers.add(defaultViewResolver());
    resolvers.add(excelViewResolver());

    resolver.setViewResolvers(resolvers);
    return resolver;
}

@Bean
public ViewResolver defaultViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    viewResolver.setOrder(2);

    return viewResolver;
}

@Bean(name="excelView")
public ViewResolver excelViewResolver() {
    ResourceBundleViewResolver viewResolver = new ResourceBundleViewResolver();
    viewResolver.setBasename("views");
    viewResolver.setOrder(1);

    return viewResolver;
}

@Bean
public ViewResolver jsonViewResolver() {
    return new JsonViewResolver();
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Bean(name = "multipartResolver")
public StandardServletMultipartResolver resolver() {
    return new StandardServletMultipartResolver();
}
}

WebAppInitializer /(等同于web.xml)

  public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { AppConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return null;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "*.html", "*.json"};
}

@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
  registration.setMultipartConfig(getMultipartConfigElement());
}

  private MultipartConfigElement getMultipartConfigElement() {
      MultipartConfigElement multipartConfigElement = new MultipartConfigElement( LOCATION, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD);
  return multipartConfigElement;
}


@Override
protected Filter[] getServletFilters() {

    CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
    encodingFilter.setEncoding("UTF-8");
    encodingFilter.setForceEncoding(true);
    ---------
}

@Override
protected void registerDispatcherServlet(ServletContext servletContext) {
    super.registerDispatcherServlet(servletContext);

    servletContext.addListener(new HttpSessionEventPublisher());
    servletContext.addListener(new RequestContextListener());

    SessionCookieConfig cookieConfig = servletContext.getSessionCookieConfig();
    cookieConfig.setHttpOnly(true);


/*** Login Success ***/
servletContext.setInitParameter("HOME_URL", "Home.html");
servletContext.setInitParameter("SSO_ENABLED", "Yes");
servletContext.setInitParameter("SSO_LOGIN_URL", "ssoLogin.html");

/*** Login Failure ***/
servletContext.setInitParameter("LOGIN_ERROR_URL", "index.jsp");
servletContext.setInitParameter("LOGOUT_URL", "index.jsp");

/*** Bypass Redirect ***/
servletContext.setInitParameter("BYPASS-URLS", "Home.html");

servletContext.setInitParameter("defaultHtmlEscape", "true");
servletContext.setInitParameter("log4jExposeWebAppRoot", "false");  

/*** Login Page ***/
servletContext.setInitParameter("LOGIN_URL", "index.jsp");

/*** Default Home Page ***/
servletContext.setInitParameter("SHOW_DEFAULT_HOMEPAGE", "Yes");    

}


 @SuppressWarnings("unused")
 private AnnotationConfigWebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setConfigLocations("com.....config");
    return context;
 }

 private static final String LOCATION = "C:/TESTdevelopments/files/"; // Temporary location where files will be stored

private static final long MAX_FILE_SIZE = 5242880; // 5MB : Max file size.
                                            // Beyond that size spring will throw exception.
private static final long MAX_REQUEST_SIZE = 20971520; // 20MB : Total request size containing Multi part.

private static final int FILE_SIZE_THRESHOLD = 0; // Size threshold after which files will be written to disk

}

JsonViewResolver类

public class JsonViewResolver implements ViewResolver{

    @Override
    public View resolveViewName(String viewName, Locale locale) throws Exception {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setPrettyPrint(true);    
        return view;
      }

}

以下是我的控制器代码。

@RequestMapping(method = RequestMethod.GET, value = "/getEmpDetails.html", produces="application/json;charset=utf-8")
public @ResponseBody List<EmpRecordParams> getEmpDetails(@RequestParam String id, HttpServletRequest request, HttpServletResponse response,
        Model model) {
    System.out.println("get");
    List<EmpRecordParams> empRecordParams = empRegisterService.getEmpDetails(id);
    return empRecordParams;
}

在我的jsp中,我使用ajax如下:

var empDetails = function() {
    $
            .ajax({
                type : "GET",
                url : "${pageContext.request.contextPath}/new/getEmpDetails.html",
                headers: {Accept: '*/*'},
                data : {
                    "id" : $("#empNo").val()
                },
                success : function(data) {
                        //Other functions
                        -------------
                    }

                 }

请帮我解决此异常。

提前致谢

1 个答案:

答案 0 :(得分:2)

最后我找到了答案,

变化不大,但花了很多时间才注意到这一点。

我对

进行了以下更改
  

WebAppInitializer.java   (这与web.xml相同)

@Override
protected String[] getServletMappings() {
return new String[] { "*.html", "*.json" };
}

这很简单,我很遗憾没有找到这个。

然后我在<{p>中的.ignoreAcceptHeader(false)中更改了configureContentNegotiation

  

AppConfig.java

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer
            .defaultContentType(MediaType.TEXT_HTML)
            .parameterName("type")
            .ignoreUnknownPathExtensions(false)
            .ignoreAcceptHeader(false)
            .favorParameter(true)
            .favorPathExtension(false)
            .useJaf(true);
}

最后,我对ajax call和控制器@RequestMapping进行了更改,以调用 getEmpDetails.json

所以它已经解决了。

最重要的部分是 servlet映射,但没有它是不可能的。

特别感谢@RC和@ P.J.Meisch帮我解决这个问题。并感谢所有花时间研究这个问题的人。