有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在SpringMVC中使用ajax从服务器端获取到jsp的集合


我检索Collection(or ArrayList) from a Controller to jsp using ajax in Spring MVC时遇到问题
控制器代码为: 项目控制器。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;

}

}

其中,公司(Azienda)是我的DBMS中的POJO类和实体

以及调度程序servlet。xml是:

<?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>

JSP代码中的ajax是: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>

我不知道为什么我不能在ajax中检索公司的列表。我在Chrome控制台中调试了它,错误是GET http://localhost:8060/Project/companyList.htm 404 (Not Found)

有人能帮我解决这个问题吗

谢谢


共 (3) 个答案

  1. # 1 楼答案

    谢谢大家的回答。。我使用另一个JSP页面(test.JSP)来获取包含公司列表的集合,从而解决了这个问题。此页面是ajax代码中的回调,并从公司列表中追加<option> </option>。jsp添加项目中。jsp

    这是项目控制器。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";
    
     } 
    }
    

    以及测试。jsp是:

        <%@ 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>
    

    最后在添加项目中。jsp是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>
    

    就这些。再见,谢谢

  2. # 2 楼答案

    如果您的Spring MVC配置正确,我建议您执行以下操作:

    1. 删除headers属性并尝试在浏览器中访问URL。如果这样做有效,那么您的请求映射就可以了。如果没有,MVC配置和/或servlet映射就有问题

    2. 如果第一步成功,您可以尝试再次添加标题,但如下所示:

       headers = "x-requested-with=XMLHttpRequest"
      

      设置此项的结果是:普通浏览器无法访问URL。预计将设置请求头“x-requested-with”。(请注意)

    玩得开心

  3. # 3 楼答案

    这里有几件事

    首先,请参阅这篇关于JSON响应的406篇文章,这将帮助您理解它的全部内容:What is "406-Not Acceptable Response" in HTTP?

    其次,我忍不住注意到以下代码:

    public @ResponseBody Object getCompanyList_AJAX() {
    

    你回来了:

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

    我在406中遇到的个人问题是,声明的类型与实际返回变量的类型不同

    换成

    public @ResponseBody Collection<Company> getCompanyList_AJAX() {
    

    最后,您还可以在ajax调用中删除数据类型:“text”,并让它根据API文档https://api.jquery.com/jQuery.ajax/智能地确定它

    试一试,如果它仍然不起作用,那么我们必须进一步深入了解您的配置