1

estoy desplegando un servlet java en Weblogic, pero al invocarlo desde el navegador: http://localhost:7005/busqueda/Servlet?PARAMETERS=ABDUL me imprime el hashmap con carcateres especiales:

��srjava.util.HashMap���`�F loadFactorI thresholdxp?@ wtABDULsrjava.util.ArrayListx����a�IsizexpDwXsr)com.prueba.corp.pld.Coincidencia>�˽���F porcentajeL fechaIngresotLjava/lang/String;Llistaq~Lnombreq~Lpuestoq~xpB�pppt1sq~B�pppt1sq~B�pppt1sq~B�pppt1sq~B�pppt1sq~B�pppt1sq~B�pppt1sq~B�pppt

La codificación que utilizo en el servidor de donde se extraen los datos es UTF-8. La version de Java que utilizo es la 6.

Alguna sugerencia para corregir este problema? Gracias.

El codigo del Servlet es el siguiente:

import com.corp.pld.Coincidencia;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ssa.ssase.ClieSock;
import ssa.ssautil.SSAException;

public class BusquedaServlet extends HttpServlet {
    Map camponum = new HashMap();
    private int inCharset;
    private String outCharset;
    private String hostname;
    private String rbname;
    private int hostport = -1;
    private String systemname;
    private String dateFormat;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long stamp = new Date().getTime();
        ClieSock ssaids = null;
        Object[] datosenv = (Object[]) null;
        Boolean searchStarted = new Boolean(false);

        printInfo("Iniciando peticion", stamp);
        datosenv = getArgs(request, ssaids, stamp);
        String search = (String) datosenv[0];
        String[] tempparam = (String[]) datosenv[1];
        try {
            printInfo("Creando Socket", stamp);
            ssaids = new ClieSock(this.hostname, this.hostport);
            printInfo("Abriendo Socket", stamp);
            while (ssaids.ids_system_open(this.rbname, this.systemname, "-v0", "") != 0) {
                printInfo("Falla al conectar", stamp);
            }

            ssaids.ids_set_encoding(this.inCharset);
            int[] searchCount = new int[1];
            ssaids.ids_system_searches_count(searchCount);

            String[] searches = new String[searchCount[0]];
            ssaids.ids_system_searches_get(searches, searchCount[0], 256);

            int[] searchFieldsCount = new int[1];
            ssaids.ids_search_fields_count(search, searchFieldsCount);

            String[] searchFields = new String[searchFieldsCount[0]];
            ssaids.ids_search_fields_get(search, searchFields, searchFieldsCount[0], 256);

            String[] idtName = new String[1];
            ssaids.ids_search_IDT_get(search, idtName, 32);

            int[] idtLen = new int[1];
            ssaids.ids_IDT_length_get(idtName[0], idtLen);

            int[] idtFieldCount = new int[1];
            ssaids.ids_IDT_fields_count(idtName[0], idtFieldCount);

            String[] idtNames = new String[idtFieldCount[0]];
            int[] idtLengths = new int[idtFieldCount[0]];
            int[] idtOffsets = new int[idtFieldCount[0]];
            int[] idtRepeats = new int[idtFieldCount[0]];
            String[] idtFormats = new String[idtFieldCount[0]];

            ssaids.ids_IDT_fields_desc(idtName[0], idtNames, idtFieldCount[0], 256, idtLengths, idtFieldCount[0],
                    idtOffsets, idtFieldCount[0], idtRepeats, idtFieldCount[0], idtFormats, idtFieldCount[0], 50);

            HashMap mapResultado = new HashMap();
            for (int j = 0; j < tempparam.length; ++j) {
                byte[][] parameters = new byte[1][];
                parameters[0] = tempparam[j].getBytes();
                printInfo("Realizando la busqueda", stamp);
                List respuesta = doSearch(search, parameters, idtLen[0], ssaids, stamp, searchStarted, idtFieldCount,
                        idtOffsets, idtLengths, idtNames);
                printInfo("Busqueda realizada", stamp);
                mapResultado.put(new String(parameters[0]), respuesta);
            }

            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
            oos.writeObject(mapResultado);
            oos.close();
            printInfo("Terminamos !!", stamp);
        } catch (SSAException e) {
            obtenerError(e, ssaids, stamp);
            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
            oos.writeObject("Error al conectarse a Servicio Identity");
            oos.close();
        } catch (Exception e) {
            obtenerError(e, ssaids, stamp);
            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
            oos.writeObject("Error al conectarse a Servicio Identity");
            oos.close();
        } finally {
            die(ssaids, stamp, search, searchStarted.booleanValue());
        }
    }

    private List doSearch(String searchName, byte[][] searchValues, int searchRecordLen, ClieSock ssaids, long stamp,
            Boolean searchStarted, int[] idtFieldCount, int[] idtOffsets, int[] idtLengths, String[] idtNames) {
        List respuesta = new ArrayList();
        try {
            byte[][] records = new byte[0][0];
            int[] recsFound = new int[1];
            byte[] rec = new byte[searchRecordLen];

            ssaids.ids_search_start(searchName, "", "", searchValues, rec, rec.length, "", recsFound, records);

            searchStarted = new Boolean(true);

            int[] sreps = new int[0];
            int[] freps = new int[0];
            rec = new byte[searchRecordLen];
            int[] score = new int[1];

            while (ssaids.ids_search_get(searchName, rec, rec.length, score, sreps, 0, freps, 0) == 0) {
                respuesta.add(parseRecord(rec, searchRecordLen, score[0], ssaids, stamp, idtFieldCount, idtOffsets,
                        idtLengths, idtNames));
            }

            ssaids.ids_search_finish(searchName);
            searchStarted = new Boolean(false);
        } catch (SSAException e) {
            obtenerError(e, ssaids, stamp);
        }

        return respuesta;
    }

    private Coincidencia parseRecord(byte[] record, int searchRecordLen, int score, ClieSock ssaids, long stamp,
            int[] idtFieldCount, int[] idtOffsets, int[] idtLengths, String[] idtNames) {
        Coincidencia coincidencia = new Coincidencia();

        if (this.camponum.containsKey("score")) {
            coincidencia.setPorcentaje(new Float(score).floatValue());
        }

        for (int i = 0; i < idtFieldCount[0]; ++i) {
            byte[] tempArr = new byte[searchRecordLen];
            System.arraycopy(record, idtOffsets[i], tempArr, 0, idtLengths[i]);
            String campo = idtNames[i].trim().toLowerCase();
            if (this.camponum.containsKey(campo)) {
                Object valor = null;
                try {
                    valor = transformaValor((String) this.camponum.get(campo),
                            new String(tempArr, this.outCharset).trim(), ssaids, stamp);
                    if (campo.equals("ClvLista")) {
                        coincidencia.setLista(valor.toString());
                    } else if (campo.equals("Nombre")) {
                        coincidencia.setNombre(valor.toString());
                    } else if (campo.equals("Feccarga")) {
                    //  coincidencia.setFechaIngreso((Date) valor);
                        coincidencia.setFechaIngreso(valor.toString());
                    } else if (campo.equals("Estatus")) {
                    }
                    coincidencia.setPuesto(valor.toString());
                } catch (Exception e) {
                    obtenerError(e, ssaids, stamp);
                }
            }
        }
        return coincidencia;
    }

    private Object transformaValor(String tipo, String cadena, ClieSock ssaids, long stamp) {
        Object valor = null;
        if (tipo.equals("string")) {
            valor = cadena;
        } else if (tipo.equals("int")) {
            valor = new Integer(new String(cadena).trim());
        } else if (tipo.equals("date")) {
            SimpleDateFormat sdf = new SimpleDateFormat(this.dateFormat);
            try {
                valor = sdf.parse(cadena);
            } catch (Exception e) {
                obtenerError(e, ssaids, stamp);
            }
        } else if (tipo.equals("double")) {
            valor = new Double(new String(cadena).trim());
        }
        return valor;
    }

    private void die(ClieSock ssaids, long stamp, String search, boolean searchStarted) {
        if (ssaids == null)
            return;
        try {
            if (searchStarted) {
                ssaids.ids_search_finish(search);
            }
            ssaids.ids_system_close();
            ssaids.ids_disconnect();
        } catch (SSAException e) {
            obtenerError(e, ssaids, stamp);
        }
    }

    private Object[] getArgs(HttpServletRequest request, ClieSock ssaids, long stamp) {
        printInfo("Obteniendo argumentos", stamp);
        Properties properties = new Properties();
        try {
            properties.load(BusquedaServlet.class.getResourceAsStream("BusquedaProperties.properties"));
            printInfo("Se obtuvieron las propiedades", stamp);
        } catch (Exception e) {
            obtenerError(e, ssaids, stamp);
        }

        this.dateFormat = properties.getProperty("DATEFORMAT");
        this.inCharset = Integer.parseInt(properties.getProperty("INCHARSET"));
        this.outCharset = properties.getProperty("OUTCHARSET");
        this.hostname = properties.getProperty("SERVIDOR_DEFAULT");
        this.rbname = properties.getProperty("RULEBASENAME_DEFAULT");
        this.hostport = Integer.parseInt(properties.getProperty("PUERTO_DEFAULT"));
        this.systemname = properties.getProperty("SYSTEMNAME_DEFAULT");
        String[] camposnum = (properties.getProperty("CAMPONUM") != null)
                ? properties.getProperty("CAMPONUM").split(";") : null;
        if (camposnum != null) {
            for (int i = 0; i < camposnum.length; ++i) {
                String[] columnas = camposnum[i].toLowerCase().split("@");
                this.camponum.put(columnas[0], columnas[1]);
            }
        }

        String search = request.getParameter("SEARCH_NAME");
        if ((search == null) || (search.trim().equals(""))) {
            search = properties.getProperty("BUSQUEDA_DEFAULT");
        }
        String[] tempparam = request.getParameter("PARAMETERS").trim().split(";");
        printInfo("Termino la obtencion de parametros " + search, stamp);
        for (String busq : tempparam) {
            printInfo("*" + busq, stamp);
        }
        return new Object[] { search, tempparam };
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    public String getServletInfo() {
        return "Short description";
    }

    private void obtenerError(Exception e, ClieSock ssaids, long stamp) {
        LogHelper.error("BIZ" + stamp + " ERROR) ", e);

        String[] mensajes = { "" };
        try {
            while (ssaids.ids_error_get(mensajes, 200) == 0)
                for (String msj : mensajes)
                    LogHelper.error("BIZ" + stamp + " ERROR) " + msj);
        } catch (Exception ex) {
            LogHelper.error("BIZ" + stamp + " ERROR) ", ex);
        }
    }

    private void printInfo(String message, long stamp) {
        LogHelper.info("BIZ" + stamp + ") " + message);
    }

    private void imprimeMapa(Map mapa, long stamp) {
        Iterator it = mapa.keySet().iterator();
        while (it.hasNext()) {
            String llave = (String) it.next();
            List valor = (List) mapa.get(llave);
            printInfo("RES-LLAVE: " + llave + ". RES-VALOR: " + valor, stamp);
        }
    }
}

y Este hace referencia a una Clase que busca las Coincidencias (Coincidencia):

public class Coincidencia implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 4513675267165913836L;
    private String nombre; //Nombre IIR 10.0
    private String lista; //ClvLista
    private float porcentaje; 
    private String fechaIngreso;//Feccarga string
    private String puesto; //Estatus
    /**
     * @return the nombre
     */
    public String getNombre() {
        return nombre;
    }
    /**
     * @param nombre the nombre to set
     */
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    /**
     * @return the lista
     */
    public String getLista() {
        return lista;
    }
    /**
     * @param lista the lista to set
     */
    public void setLista(String lista) {
        this.lista = lista;
    }
    /**
     * @return the porcentaje
     */
    public float getPorcentaje() {
        return porcentaje;
    }
    /**
     * @param porcentaje the porcentaje to set
     */
    public void setPorcentaje(float porcentaje) {
        this.porcentaje = porcentaje;
    }
    /**
     * @return the fechaIngreso
     */
    public String getFechaIngreso() {
        return fechaIngreso;
    }
    /**
     * @param fechaIngreso the fechaIngreso to set
     * date - string IIR 10.0
     */   
    public void setFechaIngreso(String fechaIngreso) {
        this.fechaIngreso = fechaIngreso;
    }
    /**
     * @return the puesto
     */
    public String getPuesto() {
        return puesto;
    }
    /**
     * @param puesto the puesto to set
     */
    public void setPuesto(String puesto) {
        this.puesto = puesto;
    }

    public String toString()
    {
        return "<Nombre:"+nombre+" Lista:"+lista+" Porcentaje:"+porcentaje+" Fecha:"+fechaIngreso+" Puesto:"+puesto;
    }
}
2
  • Podrías colocar el código de tu hashMap, servlet y vista donde lo invocas tal vez así podríamos ver que está pasando referente a la codificación.
    – Ventur
    el 5 abr. 2017 a las 17:16
  • Gracias por la respuesta Voiser, Edité la pregunta, agregando codigo del servlet y sus dependencias.
    – merry
    el 5 abr. 2017 a las 17:33

1 respuesta 1

0

Estás serializando el mapa a la respuesta. Lo que estás viendo son datos binarios. Si quieres devolver texto, simplemente debes escribir mapResultado.toString() a la salida. No uses un ObjectOutputStream, simplemente response.getOutputStream().write(mapResultado.toString().getBytes()).

2
  • Hola @Chochos Gracias por tu rrespuesta, hice lo que me recomendaste, pero ahora me da en el navegador la cadena a buscar, por ejemplo: localhost:7005/busqueda/BusquedaServlet?PARAMETERS=alberto ríos Resultado: {alberto rios=[ Sin embargo, si le doy en 'View source' en el navegador, me muestra los resultados que deberian aparecer normal. {alberto rios=[<Nombre:ALBERTO MAYORGA RIOS|Lista:LISTA DE PEPS|Porcentaje:97.0|Fecha:Fri Feb 05 00:00:00 CST 2016|Puesto:, Disculpa la molestia, pero la verdad soy nueva en Java. Saludos!
    – merry
    el 19 abr. 2017 a las 22:52
  • Pues es que no has dicho qué es lo que deberías devolver, solamente dijiste que estabas imprimiendo caracteres raros. La solución correcta es que codifiques el mapa al formato que te hayan especificado (xml, json, o lo que sea).
    – Chochos
    el 24 abr. 2017 a las 15:29

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.