File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Spring and the fly likes Spring MVC using @requestbody for Jsons request not working saying Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Spring MVC using @requestbody for Jsons request not working saying "Method not allowed"" Watch "Spring MVC using @requestbody for Jsons request not working saying "Method not allowed"" New topic
Author

Spring MVC using @requestbody for Jsons request not working saying "Method not allowed"

Namrata Narula
Greenhorn

Joined: Oct 04, 2011
Posts: 4
HI,
I have Spring applications built where in I am able to retrieve the response when using simple request parameters in the request coming from UI.However when trying to replace it with @RequestBody with passing a json in the request.It gives me 405 "Method not allowed error".
Here is the code of web.xml file
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

spring_servlet.xml

<context:component-scan base-package="com.dataguise.dgcontrol.servlets" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>

<ref bean="jsonConverter" />
</list>
</property>
</bean>

<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="contentType" value="application/json"/>
</bean>

<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>

My Spring controller class has two methods
@Controller


public class DgCentralControllerServlet {

DgControlRepository repo = new DgControlRepository();


///Method 1
@RequestMapping(value ="/LoadDiscoverExpression")
public @ResponseBody List<DgPolicyRegexPatternsUI> getMovie(@RequestParam("id") Integer id ,@RequestParam("source") String source, HttpServletResponse response,
HttpServletRequest request) throws DgException{

List<DgPolicyRegexPatternsUI> dgRegexPatternsList = repo.loadPolicyRegexPatternsTest(id,source, "All");

return dgRegexPatternsList;
}

/// Method 2
@RequestMapping(value ="/LoadDiscover", method=RequestMethod.POST, headers={"Accept=*/*", "Content-Type=application/json"})
public @ResponseBody DgDiscoverExpressionPol getexp(@RequestBody DgDiscoverExpressionPol pol,Model model) throws Exception{

DgDiscoverExpressionPol returnpol = new DgDiscoverExpressionPol();
returnpol.setSource(pol.getSource());
return returnpol;
}

Method 1 works and gives me response when running the URL on the browser using RESTCLIENT addon on mozilla
http://localhost:8080/dgControl/LoadDiscoverExpression?id=0&source=structured

However when using the Method 2 on the URL
http://localhost:8080/dgControl/LoadDiscover?json={"source":"structured"}

It gives me 405 Method not allowed error
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 418
    
    4
What method did you set? Did you select the POST method?
Bill Gorder
Bartender

Joined: Mar 07, 2010
Posts: 1648
    
    7

In the future please UseCodeTags <- click

H Paul wrote:What method did you set? Did you select the POST method?


What Paul said is correct. The error code you get is because you are issuing a GET to a method that requires a POST. When you do a POST your body ?json={"source":"structured"} will not be part of the URL.

In the RequestClient add-on for Mozilla that you are using you should be selecting POST. The URL should be http://localhost:8080/dgControl/LoadDiscover and the JSON body should go into the body box.


[How To Ask Questions][Read before you PM me]
Namrata Narula
Greenhorn

Joined: Oct 04, 2011
Posts: 4
Hi Paul,
Yes..I did use the Rest Client where in I could specify the request to go as POST .Also I gave the "json={"source":"structured"}" as the part of the requestbody.
I am still getting the same error.Let me know if you need any more data from me.

Thanks in advance
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 418
    
    4
2 things:

1. check your data string? is that correct json format?
2. make sure you also send/set the request header tag Content-Type=application/json.

Again, look at your method 2

namratajan narula
Greenhorn

Joined: Feb 21, 2013
Posts: 3
Json seems to be correct form..I have used the same format when implementing simple rest web service without spring.It seem to work fine there.
For point 2.I did expliclty added the header contenttype as appplication/json when sending the request through the RESTclient.
Also noticed the console seem to be giving me the following error in tomcat logs



Any idea ???
Do i need to implement some mapping class to indicate my POJO to JSON conversion.??
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 418
    
    4
2 things:

1. you can validate your json data using this link http://jsonlint.com/

2. Debugger is your best friend now (More than Google :-D).

Set a break on DispatcherServlet and any class that you use for JSON purpose

MappingJacksonHttpMessageConverter
MappingJacksonJsonView
and see why such error occured.

(Remember you use Spring jar which also depends on other jars like Jackson Json. Do they have correct version?)
namratajan narula
Greenhorn

Joined: Feb 21, 2013
Posts: 3
Thanks for the input...I could solve "java.lang.NoSuchMethodError: org.codehaus.jackson.type.JavaType.isConcrete()Z " issue as it seems I was using @EnableWebMvc annotation which when removed seem to resolve that error.But the "Method not allowed" error doesnt seem to go .By the way, DispatcherServlet is class file that is provided by spring and we dont deal with source code of it directly.Secondly, I did applied the debugger points but the control doesnt seem to enter in the @controller class at first place.
I did check on the jsonlint site to confirm the format of json.It seems to be valid json.
I havent implemented any jackson class as such , Just included the following jars and gave the entry in web.xml

com.springsource.org.codehaus.jackson.mapper-1.4.2.jar
com.springsource.org.codehaus.jackson-1.0.0.jar
jackson-core-2.0.2.jar
jackson-core-asl-1.9.7.jar
jackson-datatype-json-org-2.0.2.jar
jackson-mapper-asl-1.9.7.jar
org.springframework.asm-3.0.1.RELEASE-A.jar
org.springframework.beans-3.0.1.RELEASE-A.jar
org.springframework.context-3.0.1.RELEASE-A.jar
org.springframework.context-sources-3.1.0.M1.jar

Do I have to implement any of these classes???
MappingJacksonHttpMessageConverter
MappingJacksonJsonView
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 418
    
    4
When the POST request comes, it will go thru DispatcherServlet. It will call a handler to process the POST request.
If your method DgDiscoverExpressionPol did not get called. It means there is no matching between your POST request and
@RequestMapping of DgDiscoverExpressionPol.

That's why I asked you to debug starting from DispatcherServlet and do a step by step
You can download source code for any third party like Spring or Jackson. You have to understand the flow before you can take care of the how/where/why.

Look at these threads. It should help
http://www.coderanch.com/t/605299/Spring/HttpMessageConverter-RequestBody-ResponseBody
http://www.coderanch.com/t/605202/Spring/Spring-mvc-request-mapping-POST
http://www.coderanch.com/t/605222/vc/Eclipse-IDE-set-break-Spring
namratajan narula
Greenhorn

Joined: Feb 21, 2013
Posts: 3
HI Paul,
Thanks for the reply.I looked at the POST however still have confusion for attaching the source code.I followed all the steps given in the thread but could see the error as

|org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver:resolveException(106) | Resolving exception from handler [com.dataguise.dgcontrol.servlets.DgCentralControllerServlet@1b963c4]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported

I saw in Thread 2 that you have a class as RequestMappingHandlerAdapter .I am not sure if I need to implement it as I am already giving entry in web.xml.(posted in first message).Don't know if I need any more class to be implemented.
Can you recommend me some basic level book that contain the complete sample code that needs to be done for implementing JSON in spring MVC as I am pretty new to Spring MVC architecture.

Thanks for all your help though


Thanks
Namrata
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 418
    
    4
Download the latest spring framework api: Spring Framework 3.2.1.RELEASE
It has documentation. Read slowly section Spring MVC where it explains the MVC aspect.

Also read http status code.
Bill Gorder
Bartender

Joined: Mar 07, 2010
Posts: 1648
    
    7

You are either not doing a post or the handler mapping that your are resolving to is not expecting a POST. Are you sure that you are not actually matching a different @RequestMapping method than the one you think?

You need the @EnableWebMvc annoation if you are using Java config so that your Jackson libraries are correctly initialized. The error you were getting java.lang.NoSuchMethodError: org.codehaus.jackson.type.JavaType.isConcrete()Z " was more likely due to having conflicting versions of the jackson libs on the classpath. I would add that annotation back in and fix that problem first. There is a good chance after removing that annotation that your Jaxson type converter is not even being registered anymore.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Spring MVC using @requestbody for Jsons request not working saying "Method not allowed"