0


i have a problem to retrieve the Collection(or ArrayList) from a Controller to jsp using ajax in Spring MVC.
The Controller code is: ProjectController.java

@Controller
public class ProjectController {

protected final Logger log = Logger.getLogger(ProjectController.class);

@Autowired
private AziendaService service;

@RequestMapping(value ="/companyList", method = RequestMethod.GET,headers = "application/javascript")
public @ResponseBody Object getCompanyList_AJAX() {

    log.info("initiale getCompanyList_AJAX method.....");

    Collection<Company> collection = service.getAllCompany();

    return collection;

}

}

where Company(Azienda) is Class POJO and Entity in my DBMS.

and the dispatcher-servlet.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<mvc:annotation-driven /> 

<context:property-placeholder location="classpath:properties/*.properties"/>

<context:component-scan base-package="spring.hibernate"/>

<tx:annotation-driven />

<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${connection.driver_class}" />
    <property name="url" value="${connection.url}" />
    <property name="username" value="${connection.username}" />
    <property name="password" value="${connection.password}" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="datasource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>spring.hibernate.model.Account</value>
            <value>spring.hibernate.model.Assegnazione</value>
            <value>spring.hibernate.model.Attivita</value>
            <value>spring.hibernate.model.Azienda</value>
            <value>spring.hibernate.model.Comune</value>
            <value>spring.hibernate.model.Dipendente</value>
            <value>spring.hibernate.model.Persona</value>
            <value>spring.hibernate.model.Progetto</value>
            <value>spring.hibernate.model.Provincia</value>
            <value>spring.hibernate.model.Regione</value>
            <value>spring.hibernate.model.Timesheet</value>
            <value>spring.hibernate.model.Workpackage</value>
        </list>
    </property>
</bean>

<bean id="accountDAO" class="spring.hibernate.dao.AccountDAOImpl">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

<bean id="aziendaDAO" class="spring.hibernate.dao.AziendaDAOImpl">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

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

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

and The ajax in JSP code is: addProject.jsp

    <script type="text/javascript">

      $(window).load(function () {
        $.ajax({
            type: 'GET',
            url: 'companyList.htm',
            datatype:'text',
            success: function(response, status, xhr) {
                if(xhr.readyState == 4 &&(xhr.status == 200 || xhr.status == 0)) {
                    var values = [];
                    values = response;
                    $.each(values, function( index, value ) {
                           alert( index + ": " + value );
                        });
                    document.getElementById("loaderCompany").style.display = "none";
                }
                else if(xhr.readyState < 4) {
                    document.getElementById("loaderCompany").style.display = "inline";
                }
            }
    </script>

I don't know why i can't retrieve the list of company in ajax. I debugged it in Chrome console and the error is GET http://localhost:8060/Project/companyList.htm 404 (Not Found).

Someone Can help me to resolve the problem??.

Thanks.

Melis
  • 33
  • 8

3 Answers3

0

In case your Spring MVC configuration is correct I recommend to do the following:

  1. Remove the headers attributes and try to reach the URL within the browser. If this works, your Request Mapping is ok. If not there is something wrong with your MVC config and/or the servlet mapping.

  2. In case the first step is successful, you can try to add the headers again, but like this:

     headers = "x-requested-with=XMLHttpRequest"
    

    The consequence of setting this is header: The URL is not reachable by a normal browser GET. The request header "x-requested-with" is expected to be set. (just a note)

Have fun!

Christian Müller
  • 869
  • 10
  • 17
  • i make everything u tell me to do.. but nothing. i put the `headers = "x-requested-with=XMLHttpRequest"` in the Controller but nothing and now the chrome console make this error: `GET http://localhost:8060/Project/companyList.htm 406 (Not Acceptable) ` – Melis Apr 16 '14 at 20:24
  • Was the first step successful? – Christian Müller Apr 17 '14 at 11:28
0

There are couple things here.

Firstly refer to this post about 406 regarding JSON responses that will help you understand what it is all about: What is "406-Not Acceptable Response" in HTTP?

Secondly i couldn't help notice the following piece of code:

public @ResponseBody Object getCompanyList_AJAX() {

and you are returning:

Collection<Company> collection = service.getAllCompany();

    return collection;

Personal issues that i have had with 406 is due to declaration not having same type as actual return variable.

Change it to

public @ResponseBody Collection<Company> getCompanyList_AJAX() {

Finally you can also in your ajax call remove the datatype: 'text', and let it determine it intelligently as per API documentation https://api.jquery.com/jQuery.ajax/

Give that a go and if it still doesn't work then we have to dig into your configuration further.

Community
  • 1
  • 1
Aeseir
  • 7,754
  • 10
  • 58
  • 107
0

Thanks everybody for the answer.. i resolved the problem using another JSP page(test.jsp) to get my collection which contain the list of company. This page is callback in the ajax code and append <option> </option> from companyList.jsp in addproject.jsp

This is ProjectController.java:

@Controller
public class ProjectController {

protected final Logger log = Logger.getLogger(ProjectController.class);

@Autowired
private AziendaService service;

@RequestMapping(value ="/addProject", method = RequestMethod.GET)
public String addProject(HttpServletRequest request) {
    log.info("initiale createProject method.....");

    HttpSession session = request.getSession();

    if(session.getAttribute("username") == null){
        log.info("la session è expire....");
        return "sessionExpired";
    }
    return "addProject";        
}

@RequestMapping(value ="/companyList", method = RequestMethod.GET)
public String getCompanyList_AJAX(WebRequest request) {

    log.info("initiale getCompanyList_AJAX method.....");

    Collection<Company> collection = service.getAllCompany();
    request.setAttribute("modelList", collection,WebRequest.SCOPE_REQUEST);

    return "companyList";

 } 
}

and the Test.jsp is:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
       <select>
          <c:forEach items="${modelList}" var="model">
              <option value="${model.ragione_sociale}">${model.ragione_sociale}</option>
         </c:forEach>
       </select>
    </body>
    </html>

and finally in addProject.jsp part of ajax:

<script type="text/javascript">

    $(window).load(function () {
        $.ajax({
            type: 'GET',
            url: 'companyList.htm',
            success: function(response, status, xhr) {
                if(xhr.readyState == 4 &&(xhr.status == 200 || xhr.status == 0)) {
                    var html = $(response).filter('select').html();
                    $('#company').append(html);
                }
            }
        });
    });     

</script>

And That's all. See and thx again.

Melis
  • 33
  • 8