集成Spring MVC,Jquery,Ajax和Tiles

时间:2020-11-29 11:25:16

I'm trying to implement an ajax functionality into my weapp, I'm using Spring MVC and Tiles, for Ajax call I'm using jquery.

我正在尝试在我的weapp中实现ajax功能,我正在使用Spring MVC和Tiles,对于Ajax调用我正在使用jquery。

Everything works fine except ajax functionality

除了ajax功能外,一切正常

The related code are next:

相关代码如下:

Tiles Configuration:

<beans:bean class="org.springframework.js.ajax.AjaxUrlBasedViewResolver" id="tilesViewResolver">
        <beans:property name="viewClass" value="org.springframework.js.ajax.tiles2.AjaxTilesView"/>
    </beans:bean>

<beans:bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
    <beans:property name="definitions">
        <beans:list>
            <beans:value>/WEB-INF/plantilla/plantilla.xml</beans:value>
            <!-- Scan views directory for Tiles configurations -->
            <beans:value>/WEB-INF/views/**/vistas.xml</beans:value>
        </beans:list>
    </beans:property>
</beans:bean>

My Controller:

@RequestMapping(value = "clientes/listarProvincias", method = RequestMethod.GET,headers="Accept=*/*")
public @ResponseBody List<Provincia> listarProvincias(@RequestParam(value = "departamento", required = true)String codigoDepartamento){
    logger.info("Ingresando al Metodo Listar Provincias con Ajax");
    Integer codDep = Integer.parseInt(codigoDepartamento);
    return this.provinciaDAO.listarProvinciaPorDepartamento(codDep);
}

My JSP

   <script type="text/javascript">
$(document).ready(function() { 
    $('#departamento').change(
            function() {
                $.getJSON('clientes/listarProvincias', {
                    departamento : $(this).val(),
                    ajax : 'true'
                }, function(data) {
                    alert("Ingresando a JSON");
                    var html = '<option value="">Departamento</option>';
                    var len = data.length;
                    for ( var i = 0; i < len; i++) {
                        html += '<option value="' + data[i].name + '">'
                                + data[i].name + '</option>';
                    }
                    html += '</option>';

                    $('#provincias').html(html);
                });
            });
});
</script>

Part of the form

部分表格

 <p>
                        <label>Departamento</label>
                        <span class="field">
                            <form:select path="departamento.codDpto" id="departamento">
                                <form:option value="" ></form:option>
                                <c:forEach items="${departamentos}" var="departamento">
                                    <form:option value="${departamento.codDpto}">${departamento.descripcion}</form:option>
                                </c:forEach>
                            </form:select>
                            <label class="error">
                                <form:errors path="estaReg" cssClass="error"></form:errors>
                            </label>
                        </span>
                    </p>

                    <p>
                        <label>Provincia</label>
                        <span class="field">
                            <form:select path="provincia.codprovincia" id="provincias">
                                <form:option value="" ></form:option>
                                <c:forEach items="${provincias}" var="provincia">
                                    <form:option value="${provincia.codprovincia}">${provincia.descripcion}</form:option>
                                </c:forEach>
                            </form:select>
                            <label class="error">
                                <form:errors path="estaReg" cssClass="error"></form:errors>
                            </label>
                        </span>
                    </p>

Google Chomre Tools shows:

Google Chomre工具显示:

GET http://localhost:8080/sictem/clientes/listarProvincias?departamento=5&ajax=true 404 (No Encontrado)

Logs

    DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 1 of 10 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 2 of 10 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 3 of 10 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 4 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 5 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 6 of 10 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 7 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG: org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 8 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG: org.springframework.security.web.session.SessionManagementFilter - Requested session ID46A28166F0557A3A00BB916481349AC8 is invalid.
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 9 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true at position 10 of 10 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
DEBUG: org.springframework.security.web.util.AntPathRequestMatcher - Checking match of request : '/clientes/listarprovincias'; against '/*'
DEBUG: org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Public object - authentication not attempted
DEBUG: org.springframework.security.web.FilterChainProxy - /clientes/listarProvincias?departamento=6&ajax=true reached end of additional filter chain; proceeding with original chain
DEBUG: org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG: org.springframework.security.web.access.ExceptionTranslationFilter - Chain processed normally
DEBUG: org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed

I don't know what I'm doing wrong. Best Regards,

我不知道我做错了什么。最好的祝福,

1 个解决方案

#1


0  

Check if you need change your controller declaration as well

检查您是否还需要更改控制器声明

  @RequestMapping(value = "json", headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> listJson(@RequestParam String nombre) {
        HttpHeaders headers = new HttpHeaders();

        // PAY ATTENTION TO THIS:
        headers.add("Content-Type", "application/json; charset=utf-8");

        List<Medico> result = null;
        if (org.apache.commons.lang3.StringUtils.isEmpty(nombre)) {
            result = Provincia.findProvinciaEntries(0, 10);
        } else result = Provincia.findProvinciaEntries(0, 10);


        // NEED TO CREATE JSON ARRAY
        String data = "{\"items\":" + Provincia.toJsonArray(result) + " }";
        return new ResponseEntity<String>(data, headers, HttpStatus.OK);
    }

Hope this help you

希望这对你有所帮助

#1


0  

Check if you need change your controller declaration as well

检查您是否还需要更改控制器声明

  @RequestMapping(value = "json", headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> listJson(@RequestParam String nombre) {
        HttpHeaders headers = new HttpHeaders();

        // PAY ATTENTION TO THIS:
        headers.add("Content-Type", "application/json; charset=utf-8");

        List<Medico> result = null;
        if (org.apache.commons.lang3.StringUtils.isEmpty(nombre)) {
            result = Provincia.findProvinciaEntries(0, 10);
        } else result = Provincia.findProvinciaEntries(0, 10);


        // NEED TO CREATE JSON ARRAY
        String data = "{\"items\":" + Provincia.toJsonArray(result) + " }";
        return new ResponseEntity<String>(data, headers, HttpStatus.OK);
    }

Hope this help you

希望这对你有所帮助