Foros del Web » Programación para mayores de 30 ;) » Java »

spring combos dependientes

Estas en el tema de spring combos dependientes en el foro de Java en Foros del Web. Wenas, aqui comparto como se puede hacer combos dependientes mediante Spring MVC usando jax y jquery , espero le sirva a alguien formulario contacto.jsp Código ...
  #1 (permalink)  
Antiguo 08/07/2013, 13:02
 
Fecha de Ingreso: mayo-2010
Mensajes: 99
Antigüedad: 14 años, 6 meses
Puntos: 5
spring combos dependientes

Wenas, aqui comparto como se puede hacer combos dependientes mediante Spring MVC usando jax y jquery , espero le sirva a alguien

formulario contacto.jsp

Código PHP:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%@ 
taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ 
taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@
taglib prefix "c" uri "http://java.sun.com/jsp/jstl/core" %>
<%@ 
page isELIgnored="false" %> 
<!
DOCTYPE html>
<
html >

<
head>
<
meta charset="utf-8"/>
<
meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>

<
title></title>

<
meta name="description" content="HTML 5 CSS 3 Spring Form"/>
<
meta name="viewport" content="width=device-width,initial-scale=1"/>

</
head>

<
body>
    <
div id="container">
         <
form  method="post" action="tabs.htm">

            <
h1>Formulario test...</h1>

            <
fieldset id="user-details">
               <
div id="cont1">
                <
label for="name" >Name: </label
                <
input type="text" name="name"
                    
value="" id="name" placeholder="Your Name" required="required"
                    
autofocus="autofocus"  /> 
                <
label for="email" >Email: </label>
                <
input type="email" name="email" value="" id="email" placeholder="[email protected]required="required"  /> 
                </
div>
                <
div id="cont2">
                <
label for="phone" >Phone:</label
                <
input type="text" name="phone" value=""  />
                <
label for="website" >Website:</label
                <
input type="url" name="website" value=""  />
                </
div>
            </
fieldset>
            <!--
end user-details-->
            
            <
fieldset id="user-message">

                <
label for="message" >Your Message: </label>
                <
textarea name="message" rows="0" cols="0" ></textarea>

            
        <
div id="combo1">
        <
select name="paises" id="paises" >
            <
option value="-1">--Select your country--</option>
            <
c:forEach items="${listCountries}" var="city">
                <
option value="<c:out value="${city.idcity}" />"><c:out value="${city.city}" /></option>
            </
c:forEach>
        </
select>
        </
div>    
        <
div id="combo2">
        <
select name="states" id="states" disabled="disabled" >
        <
option>--Select state--</option>
        </
select>    
        </
div>
            </
fieldset>
            <
br>
            <
input type="submit" value="Submit Message" name="submit"
                    
class="submit" />
         </
form>  
        
                
    </
div>
    <!--! 
end of #container -->

<script type="text/javascript" language="javascript">

jQuery(document).ready(function() {

var 
contexPath "<%=request.getContextPath() %>";

    $(
'#paises').change( function(e) {
    
    if(
jQuery(this).val()!="-1"){
     $(
'#states').find('option').remove().end()
     .
append('<option value="-1">--Select state--</option>');
   
        
e.preventDefault();
        var 
val = $(this).val();
        
jQuery("#states").removeAttr("disabled");
        
        
alert(val);
            
//$('#othstate').val('').hide();
            
$.ajax({
               
type"POST",
               
url:  contexPath '/loadcities.htm',
               
dataType'json',
               
data: { idpais val },
               
success: function(data) {
               
alert(data.lstStates);
               
showUsers(data.lstStates);
                  
// $('#states').html( data.lstStates );
               
},
               
error:
               function(
e){
             
alert('Error: ' e);
             } 
            });
        }
        else {
           $(
"#states").attr("disabled","disabled");
        $(
'#states').find('option').remove().end()
           .
append('<option value="-1">--Select state--</option>');
        }
    });

    function 
showUsers(data) {
 
        for ( var 
0len data.lengthlen; ++i) {
            var 
msajax data[i];
            $(
'#states').append("<option value=\"" +msajax.idciudad "\">" msajax.ciudad"</option>");
        }
    }

});
</script>

</body>
</html> 
controlador: inventoryControlador.java

Código PHP:
package com.controlador;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
.........................

@
Controller
@SessionAttributes({"menu","perfilspring","user"})
public class 
inventoryControl {
    
    protected final 
Log logger LogFactory.getLog(getClass());
    @
Autowired
    
@Qualifier("searchService")
    private 
searchService service;
    
    @
RequestMapping(value="/contacto",method RequestMethod.GET)
    public 
String onlog(usuario us,HttpServletRequest request,HttpServletResponse responseModelMap model) {
    
//public String onlog(usuario us,@ModelAttribute ("perfilspring") String p) {
    //public @ResponseBody Map<String,Object> onlog(HttpServletRequest request,HttpServletResponse response)
    //throws Exception{
         
logger.info("entro inventorycontrolador");
         
ArrayList<catalogBeanlst = new ArrayList<catalogBean>(); 
         
lst.add(new catalogBean("MX","Mexico"));
         
lst.add(new catalogBean("BRA","Brasil"));
         
lst.add(new catalogBean("COL","Colombia"));
         
lst.add(new catalogBean("MY","Malaysia"));
         
lst.add(new catalogBean("CHINA","China"));
         
lst.add(new catalogBean("SG","Singapore"));
         
lst.add(new catalogBean("US","USA"));

        
         List 
countries = new ArrayList();
            
countries.add(new countries("IND","INDIA"));
            
countries.add(new countries("US","USA"));
            
countries.add(new countries("AU","AUSTRALIA"));
            
countries.add(new countries("MX","MEXICO"));
            
countries.add(new countries("COL","COLOMBIA"));
            
            
model.addAttribute("listCountries",countries);
          
         return 
"contacto";
         }
    
    
/*
     * para submit de form
     */
    
@RequestMapping(value="/tabs",method=RequestMethod.POST)
    
//public String tabs(usuario us,@ModelAttribute ("perfilspring") String p, @RequestParam(value="name",required=true) String nombre, Map<String, Object> model)
    
public String tabs(@RequestParam("name"String text,@RequestParam("paises"String idpais,@RequestParam("states"String states)
    {
        
logger.info("entro tabs");
        
logger.info("parametro caja ::"+text "combocountry eleg :"+idpais+" combocities eleg:"+states);
        
        return 
"tabs";
    }
    
    
    
/*
     * Probado jala ok para cargar combo hijo
     */
    
@RequestMapping(value="/loadcities")
    public @
ResponseBody Map<String,ObjectgetCiudades(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="idpais",required=trueString idcity)
    
throws Exception{
        
logger.info("cargando lista ciudades..");
        
logger.info("parametro combo ::"+idcity);
        
logger.info("idp >>"+request.getParameter("idpais"));
      
Map<String,Objectmap = new HashMap<StringObject>();

      List 
bus_list = new ArrayList();
      
bus_list service.getEstados(idcity);
      
      
map.put("lstStates"bus_list);
     
    return 
map;
    }
    
    

la capa servicio

Código PHP:

package com
.servicio;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
................................

@
Component
@Qualifier("searchService")
@
Service
public class searchService implements serviceInterface  {

........................

@
SuppressWarnings("unchecked")
    public List 
getEstados(String idcity)
    {
        List  
cities = new ArrayList();
        if(
idcity.equalsIgnoreCase("MX")){
            
cities.add(new citiesBean("MORMX","Morelos"));
            
cities.add(new citiesBean("CANMX","Cancun"));
            
cities.add(new citiesBean("VERMX","Veracruz"));
        }
        else if(
idcity.equalsIgnoreCase("US")){
            
cities.add(new citiesBean("MS","Masachusets"));
            
cities.add(new citiesBean("SF","San Francisco"));
            
cities.add(new citiesBean("HT","Houston"));
        }
        else if(
idcity.equalsIgnoreCase("COL")){
            
cities.add(new citiesBean("BOG","Bogota"));
            
cities.add(new citiesBean("MED","Medellin"));
            
cities.add(new citiesBean("CTG","Cartagena"));
        }
        else if(
idcity.equalsIgnoreCase("IND")){
            
cities.add(new citiesBean("YAK","Yakarta"));
            
cities.add(new citiesBean("BOY","Bombay"));
            
cities.add(new citiesBean("NDL","New Delhi"));
        }
        else if(
idcity.equalsIgnoreCase("AU")){
            
cities.add(new citiesBean("SYD","Sydney"));
            
cities.add(new citiesBean("MEL","Melbourne"));
            
cities.add(new citiesBean("AYR","Ayres Rock"));
        }
        return 
cities;
    } 

Etiquetas: combos, dependientes, html, jsp, servlet, spring, string
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:46.