简体   繁体   中英

Spring-mvc 406 NOT Acceptable URl

I saw the relevant questions in stackoverflow but i didn't find a solution to my problem. This is my Initializer Class:

    public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        public static HashMap<String, String> response_code = new HashMap<String, String>();


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

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

        @Override
        protected String[] getServletMappings() {
            return new String[] { "/" };
        }

        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            super.onStartup(servletContext);
            Security.addProvider(new BouncyCastleProvider());
            servletContext.addListener(new MainContextListener());
 }
}

This is the Controller:

@RestController 
@Component
public class MainController {
@RequestMapping(value = "/getAll", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Int addNumber (
            @RequestParam(value = "number", defaultValue = "0",
                    required = false) int number ) {
// code to set and return number
}
}

This is the Structure of webapp folder:

main/webapp/index.jsp

Css and Scripts folders are in webapp folder.

and I'm trying to run the project on intellij using tomcat web server. the problem is when I run the project, index.jsp opens in a browser but it gives 406 not acceptable uri error on getAll.

You intercept all URLs (CSS as well)

protected String[] getServletMappings() {
    return new String[] { "/" };
}

You need tyo exclude resources from the intercepting. See eg Spring 4.x Java code-based configuration: Static resource files and Dispatcher servlet

This should work

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

But make sure that you put the static contents under resources folder.

Please note that webapp is not a part of the Java web application folder structure and that's the reason why the code you put in your previous comment is not working

after trying lots of ways I discovered I had missed one dependency in my pom file, so response wasn't sent as json and 406 error occured, the missing dependency was jackson:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM