valor una texto resultado mostrar formularios formulario enviar ejemplos correo contacto con caja java jquery ajax jsp encoding

java - una - ¿Cómo puedo hacer que este código envíe un textarea de formulario UTF-8 con jQuery/Ajax?



mostrar resultado en input javascript (6)

Tuve el mismo problema y lo solucioné al degradar a mysql-connector-odbc-3.51.16.

Tengo problemas para enviar formularios que contienen cadenas UTF-8 con Ajax. Estoy desarrollando una aplicación web Struts que se ejecuta en un servidor Tomcat . Este es el entorno que configuré para trabajar con UTF-8:

  • He agregado los atributos URIEncoding="UTF-8" useBodyEncodingForURI="true" en la etiqueta Connector al archivo conf/server.xml Tomcat.

  • Tengo una base de datos utf-8_general_ci

  • Estoy usando el siguiente filtro para asegurar que mi solicitud y respuestas estén codificadas en UTF-8

    package filters; import java.io.IOException; import javax.servlet.*; public class UTF8Filter implements Filter { public void destroy() {} public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } }

  • Uso este filtro en WEB-INF / web.xml

  • Estoy usando el siguiente código para mis respuestas JSON:

    public static void populateWithJSON(HttpServletResponse response,JSONObject json) { String CONTENT_TYPE="text/x-json;charset=UTF-8"; response.setContentType(CONTENT_TYPE); response.setHeader("Cache-Control", "no-cache"); try { response.getWriter().write(json.toString()); } catch (IOException e) { throw new ApplicationException("Application Exception raised in RetrievedStories", e); } }

Todo parece funcionar bien (el contenido procedente de la base de datos se muestra correctamente y puedo enviar formularios que se almacenan en UTF-8 en la base de datos). El problema es que no puedo enviar formularios con Ajax . Uso jQuery, y pensé que el problema era la falta del campo contentType en la solicitud de Ajax. Pero estaba equivocado. Tengo una forma muy simple de enviar comentarios que contiene una identificación y un cuerpo. El campo del cuerpo puede estar en diferentes idiomas, como español, alemán o lo que sea.

Si envío mi formulario con el texto del cuerpo que contiene la contraseña , Firebug me muestra:

Encabezados de solicitud

  • Host localhost: 8080
  • Accept-Charset ISO-8859-1, utf-8; q = 0.7; * q = 0.7
  • Content-Type application / x-www-form-urlencoded; juego de caracteres UTF-8

Si ejecuto Copiar ubicación con parámetros en Firebug, la codificación parece ser incorrecta:

http://localhost:8080/Cerepedia/corporate/postStoryComment.do?&body=contrase%C3%B1a&id=88

Este es mi código jQuery:

function addComment() { var comment_body = $("#postCommentForm textarea").val(); var item_id = $("#postCommentForm input:hidden").val(); var url = rooturl+"corporate/postStoryComment.do?"; $.post(url, { id: item_id, body: comment_body } , function(data){ /* Do stuff with the answer */ }, "json"); }

Una presentación de un formulario con jQuery está causando el siguiente lado del servidor de errores (tenga en cuenta que estoy usando Hibernate ).

javax.servlet.ServletException: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505) at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) ... 26 more Caused by: java.sql.BatchUpdateException: Incorrect string value: ''/xF1a'' for column ''body'' at row 1 at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) ... 44 more 26-ago-2008 19:54:48 org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() para servlet action lanzó excepción java.sql.BatchUpdateException: Incorrect string value: ''/xF1a'' for column ''body'' at row 1 at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeBatch(NewProxyPreparedStatement.java:1723) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.cerebra.cerepedia.item.dao.ItemDAOHibernate.addComment(ItemDAOHibernate.java:505) at com.cerebra.cerepedia.item.ItemManagerPOJOImpl.addComment(ItemManagerPOJOImpl.java:164) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) javax.servlet.ServletException: java.lang.NumberFormatException: null at org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:520) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:427) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NumberFormatException: null at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) ... 26 more 26-ago-2008 20:13:25 org.apache.catalina.core.StandardWrapperValve invoke GRAVE: Servlet.service() para servlet action lanzó excepción java.lang.NumberFormatException: null at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.valueOf(Unknown Source) at com.cerebra.cerepedia.struts.item.ItemAction.addComment(ItemAction.java:120) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.apache.struts.actions.MappingDispatchAction.execute(MappingDispatchAction.java:166) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:425) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:228) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.security.AuthorizationFilter.doFilter(AuthorizationFilter.java:78) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.cerebra.cerepedia.hibernate.HibernateSessionRequestFilter.doFilter(HibernateSessionRequestFilter.java:30) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at filters.UTF8Filter.doFilter(UTF8Filter.java:14) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source)


intenté agregar lo siguiente antes de la llamada:

$.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8" });

Las opciones se explican aquí .

contentType: cuando envíe datos al servidor, use este tipo de contenido. El valor predeterminado es "application / x-www-form-urlencoded", que está bien para la mayoría de los casos.

scriptCharset: solo para solicitudes con tipo de datos ''jsonp'' o ''script'' y tipo GET. Obliga a la solicitud a interpretarse como un cierto conjunto de caracteres. Solo es necesario para las diferencias de caracteres entre el contenido remoto y el local.


Como la excepción es un error jdbc, su mejor enfoque es capturar la entrada antes de enviarla a la base de datos.

java.sql.BatchUpdateException: Valor de cadena incorrecto: ''/ xF1a'' para la columna ''cuerpo'' en la fila 1

Un solo personaje está causando la excepción.

Es posible que deba sobrescribir algunos caracteres manualmente. Cuando trabaje con idiomas que no sean del alfabeto latino (como yo), encontrará que es un dolor común.


Veo este problema mucho. El meta no funciona siempre en las operaciones de datos de PHP, así que simplemente escríbalo al principio:

<?php header(''Content-type: text/html; charset=utf-8''); ?>


Estoy teniendo el mismo problema. Vi que Internet Explorer 8 envía este encabezado:

content-type = application/x-www-form-urlencoded

mientras que Firefox envía esto:

content-type = application/x-www-form-urlencoded; charset=UTF-8

Mi solución fue forzar a jQuery a usar el tipo de contenido de Firefox:

$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8" });


También tuve el mismo problema y lo solucioné de esta manera:

En PHP, antes de almacenar los datos en la base de datos, utilicé la función htmlentities() . Y al mostrar los datos, utilicé la función html_entity_decode() . Esto funcionó. Espero firmemente que esto también funcione para ti.