0

I'm tryng to convert JSON into a java class using Spring. When I execute the code I get 400 bad request. If I replace User java object (@RequestBody final **User** user) with generic java Oject (@RequestBody final **Object** user), I get the json string as parameter.

Here's my code.

Javascript:

register : function(usr,pwd) {
    var user = {username : usr, password: pwd}
    return $http({
        method: 'POST',
        url: '/SpringSecurityRememberMeAnnotationExample/newuser',
        contentType: "application/json",
        data:user
    });
    /*
    return $http.post('/SpringSecurityRememberMeAnnotationExample/newuser', user).then(function(response) {
        return response.data;
    });
    */
},

Controller:

@Controller
@Scope("request")
public class HomeController {

    @RequestMapping(value = "/newuser", method = RequestMethod.POST)
    @ResponseBody public User SaveUser(@RequestBody final User user){
        System.out.println("username: ");// + user.username);
        System.out.println("password: ");// + user.password);
        return null;
    }

spring-mvc.xml

<mvc:annotation-driven/>
<mvc:default-servlet-handler/>

<!-- Login Interceptor -->
<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**"/>
        <bean class="com.websystique.springsecurity.interceptor.LoginInterceptor"/>
    </mvc:interceptor>
    <!-- workaround to fix IE8 problem -->
    <bean id="webContentInterceptor"
          class="org.springframework.web.servlet.mvc.WebContentInterceptor">
        <property name="cacheSeconds" value="0"/>
        <property name="useExpiresHeader" value="true"/>
        <property name="useCacheControlHeader" value="true"/>
        <property name="useCacheControlNoStore" value="true"/>
    </bean>
</mvc:interceptors>

<!-- i18n -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="useCodeAsDefaultMessage" value="true"/>
    <property name="basename" value="WEB-INF/i18n"/>
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="fileEncodings" value="UTF-8" />
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
    <property name="defaultLocale" value="it"/>
    <property name="useCodeAsDefaultMessage" value="true"/>
</bean>

<!-- Exception handler -->
<bean id="exceptionResolver"
      class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  <property name="exceptionMappings">
    <props>
      <prop key="LoginRequiredException">          
        public/loginRequired
      </prop>
      <prop key="ResourceNotFoundException">          
        public/notFound
      </prop>
    </props>
  </property>
  <property name="defaultErrorView" value="rescues/general" />
</bean>

<!-- View Handler -->
<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
    <property name="order" value="0" />
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>

Thank you!

Adding POM.XML config, json part

<!-- JSon -->
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
11
  • 1
    Remove the jacksonMessageConverter and the org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter. Those are configured automatically. Commented Dec 18, 2015 at 11:09
  • 1
    @francesco can you show me the User class I think you dont have propper setter getters. Commented Dec 18, 2015 at 11:09
  • 1
    @FrancescoDiPasquantonio i have answered it, so accept it so that other users can also get benefit for such problem. thanks Commented Dec 18, 2015 at 11:36
  • 1
    The user class inside the controller shouldn't matter if it would be a static class and not a class. Commented Dec 18, 2015 at 11:54
  • 1
    A non-static interclass requires an instance of the enclosing class to be created before it itself van be created. This is not the case with a static inner class. Commented Dec 19, 2015 at 14:03

5 Answers 5

4

Recheck the setters/getters for the fields and make sure there is a no-argument constructor. (If you have no constructor, Java will generate a default no-arg one, but if you have added a constructor with arguments yourself, you must take care to implement a no-arg one as well).

Sign up to request clarification or add additional context in comments.

Comments

1

Main Problem was on the User class embedded on the controller code. Once I created User.java file on it's own package all goes smoothly.

Comments

0

You are passing malformed json object i guess. you should pass user json data like below.

var user = {"username" : "<username>", "password": "<password>"};

And makes sure User.java has setters/getters for the fields and default constructor.

2 Comments

I tryed to build string as you suggested but doesn't works. var user = {username : '<' + usr + '>', password: '<' + pwd + '>'}
names in json data should be enclosed with double quotes. i.e. var user={"username": usr, "password":pwd}; before invoking the rest service try to print data in alert dialog and see.
0

Please make sure following two jars are present in your application

1. Jackson - core
2. Jackson - mapper

Both Java API are used by spring for XML/JSON processing.

1 Comment

I put my pom.xml, I updated jackson lib to the latest version since I'm using spring 4, but still not working.
0

put var user = {"username" : usr, "password": pwd}; in java script, and do confirm that your User class is right having proper setter getter and proper access to your calling class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.