2

Hi all I know this is an common error you will get while returning JSON response from controller using @ResponseBody annotation. I googled and tried to implete all the solutions given in all the following links but failed to solve this error so finally decided to post the question.

Solutions that I tried out

Solution 1 & Solution 2

previously I was using /jobsearch.htm request in my AJAX call url but as per mentioned in this answer I have removed the *.htm and after that I am getting 404 request not mapped error.

Solution 3

I tried to set MappingJacksonHttpMessageConverter but getting error

Build path is incompelete can not find class file com/fastxml/jackson/core/JsonProcessingException

Solution 4

accoring to this blog I have added content negotiation manager but still not able to solve this error.

Still I can not able to solve this error followng is my code

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/root-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <beans:bean id="contentManager"
            class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
            <beans:property name="favorPathExtension" value="true"/>
            <beans:property name="ignoreAcceptHeader" value="true" />
            <beans:property name="mediaTypes">
             <beans:map>
                 <beans:entry key="json" value="application/json" />
                 <beans:entry key="xml" value="application/xml" />
             </beans:map>
            </beans:property>
    </beans:bean>   
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven  content-negotiation-manager="contentManager"/>
    <resources mapping="/resources/**" location="/resources/" />

    <!-- NOT WORKING 
    <beans:bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></beans:bean>
    <beans:bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <beans:property name="messageConverters">
            <beans:list>
                <beans:ref bean="jsonConverter" />
            </beans:list>
        </beans:property>
    </beans:bean> 
    -->

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:annotation-config/>
    <context:component-scan base-package="com.myproject" />

    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>

    <!-- here we enable @Transactional support -->
    <!-- Add this tag to enable annotations transactions -->
    <tx:annotation-driven  transaction-manager="transactionManager"/>
</beans:beans>

home.jsp

<h4>Welcome User  ${user.firstName} </h4>
<div class="search-container">
        <div class="ui-widget">
                <input type="text" id="search" name="search" class="search" />
        </div>
</div>

<script type="text/javascript">
   $( document ).ready(function() {
   $("#search").autocomplete({
           source: function(request,response) {
               $.ajax({
                   url: "/myproject/jobsearch",
                   type: "GET",
                   dataType: "json",
                   data: { term: request.term },
                   success: function (data) {
                       response($.map(data, function (item) {
                           return { label: item.email, value: item.password };
                       }))
                   }
               })
           },
           messages: {
               noResults: "", results: ""
           }
       });
   });
</script>

JobSearchController.java

@Controller
public class JobSearchController {

    private static final Logger logger = LoggerFactory
            .getLogger(JobSearchController.class);

    @RequestMapping(value = "/jobsearch", method = RequestMethod.GET,
            headers = "Accept=application/json, text/javascript, */*;",
            produces="application/json")
    public @ResponseBody List<LogInForm> getJobs(@RequestParam("term") String query,
            HttpServletRequest request, HttpServletResponse response) {
        logger.info("Job Search controller");
        List<LogInForm> list = new ArrayList<LogInForm>();
        list.add(new LogInForm("ashish","ashish"));
        list.add(new LogInForm("B","B"));
        list.add(new LogInForm("Yogesh","Yogesh"));
        list.add(new LogInForm("Shailesh","Shailesh"));
        list.add(new LogInForm("Mahendra","Mahendra"));
        list.add(new LogInForm("Swapnli","Swapnli"));
        list.add(new LogInForm("Mahesh","Mahesh"));
        return list;
    }// End of getJobs() Method.
}// End of JobSearchController Class.

LogInForm.java

public class LogInForm {

    private String email;

    private String password;

    public LogInForm() {
        super();
    }

    public LogInForm(String email, String password) {
        super();
        this.email = email;
        this.password = password;
    }

    //setter && Getters 
}   

UPDATE

pom.xml

<!-- Jackson -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

Error

 GET http://localhost:8080/myproject/jobsearch?term=A 406 Not Acceptable 3ms    
jquery-1.10.2.js (line 8706)

Response Header

Content-Language    en
Content-Length  1110
Content-Type    text/html;charset=utf-8
Date    Mon, 12 Jan 2015 11:07:03 GMT
Server  Apache-Coyote/1.1

Request Header

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Cookie  JSESSIONID=27A0C06010F0D41A0CD7841F8C0E3B1E
Host    localhost:8080
Referer http://localhost:8080/edgeowt/login.htm
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0
X-Requested-With    XMLHttpRequest

Please help me to find out the solution for the same. also I want to migrate Angular JS with JSON later

What i'm doing wrong? I know, there is a lot of questions about such cases, but i can't fix it for lat 7 days...

Community
  • 1
  • 1
Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45
  • Did you include Jackson in your project? – a better oliver Jan 12 '15 at 21:20
  • The `headers` parameter in your mapping is pretty useless. The same is true for the uncommented "not working" section and most likely for the configuration of the `contentManager` bean. I'd remove that and see if things work. `org.codehaus.jackson` is the old branch of Jackson which is deprecated since Spring 4 (it's still somewhat supported, though). – a better oliver Jan 13 '15 at 08:33

0 Answers0