【问题标题】:JSP Not Suppported by UTF-8 EncodingUTF-8 编码不支持 JSP
【发布时间】:2013-09-16 09:22:29
【问题描述】:

当我试图在我的 JSP 页面中显示中文字符时,它会显示垃圾字符。

我做错了什么?

我已在顶部的 JSP 中包含以下行,即使现在,问题也没有得到解决:

<%@page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page import="java.util.*"%>
<%@ page import="com.hp.sales.om.workflow.c2c.config.model.Organization"%>
<%@ page import="com.hp.sales.om.workflow.c2c.config.model.ClassificationL1"%>
<%@ page import="com.hp.sales.om.workflow.c2c.config.model.ClassificationL2"%>
<%@ page import="com.hp.sales.om.workflow.c2c.config.model.TaskConfig"%>

 <script type="text/javascript" language="javascript"
src="/integration/r5/hpr/js/jquery-1.3.2.js"></script>

<script language="JavaScript">
//Javascript code here...
</script>

<%
String taskId = (String) request.getAttribute("taskId");
if (taskId == null || taskId.trim().equals("")) {
    taskId = ""; 
%>
<jsp:include page="/Header.jsp" />
<%@ taglib uri="http://xmlns.oracle.com/bpel/workflow/worklist-taglib.tld" prefix="worklist"%>
<link rel="stylesheet" type="text/css" href="/integration/r5/hpr/css/homepages-v5.css" />
<%
Map links = new LinkedHashMap();
    links.put("Select Task", request.getContextPath()
            + "/SelectTask");
    String disableCondition = "";
%>

<worklist:navLinks linkMap="<%=links%>" styleClass="customBreadCrumbNav"
separator=" > " prefixHTML="<strong>" suffixHTML="</strong>"
disableConditionBasedOn="<%=disableCondition%>" />
<!-- border table -->
 <TABLE WIDTH="100%" BORDER="0">
 <TR>
     <TD>
        <TABLE WIDTH="100%" BORDER="1">
             <TR>
                        <TD>
                            <%
                                } else {
                             %>
                    <html>
 <head>
 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
 <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>Select Task</title>
 </head>
 <body>
<%
    }
%>
<br />
<form STYLE="display: inline;" method="POST" name="SelectTask"
    action="<%=request.getContextPath()%>/SelectTask">

    <input type="hidden" name="method" id="method" value='' /> <input
        type="hidden" name="method" id="method" value='' /> <input
        type="hidden" name="taskId" id="taskId" value='<%=taskId%>' />

    <!-- jQuery Ajax stuff for new way of create task, page not be refresh when choose organization -->
    <script type="text/javascript">
     var servletContextPath = <%=request.getContextPath()%>
        ";"
        $(document)
                .ready(
                        function() {

                            $(window).load(function() {
                                                $.ajax({
                                                            url : servletContextPath
                                                                    + "/OrganizationLoadServlet",
                                                            cache : false,
                                                            beforeSend : function() {
                                                                //alert(this.url == 'myUrl');
                                                                //timeout setting 30second
                                                                ajax_timeout = setTimeout(
                                                                        function() {
                                                                            //alert('Request is taking a long time.');
                                                                                                            },
                                                                        30000);
                                                                //
                                                            },
                                                            success : function(
                                                                    xmlResponse) {
                                                                var count = 0;
                                                                $(xmlResponse)
                                                                        .find('ITEMS')
                                                                        .each(function() {
                                                                                    count++;
                                                                                });
                                                                if (count == 1) {
                                                                    $(xmlResponse).find('ITEMS')
                                                                            .each(function() {
                                                                                                                                });
                                                                    $.ajax({
                                                                                type : "GET",
                                                                                url : servletContextPath
                                                                                        + "/OrganizationProcessHandler",
                                                                                data : {
                                                                                    orgId : $params
                                                                                },
                                                                                cache : false,
                                                                                beforeSend : function() {
                                                                                    ajax_timeout2 = setTimeout(
                                                                                            function() {
                                                },
                                                                                            30000);
                                                                                },
                                                                                success : function(xmlResponse) {
                                        $(xmlResponse).find('ITEMS')
                                                                                            .each(function() {
                                                        });
                                                                                    //timeout calling
                                                                                    if (ajax_timeout2) {
                                                                                        clearTimeout(ajax_timeout2);
                                                                                    }
                                                                                }
                                                                            });

                                                                } else {
                                                                    $(xmlResponse).find('ITEMS')
                                                                            .each(function() {
                                                                                    });
                                                                }
                                                                //timeout calling
                                                                if (ajax_timeout) {
                                                                    clearTimeout(ajax_timeout);
                                                                }
                                                                //
                                                            },
                                                            complete : function() {
                                                                //alert(this.async == true);
                                                            }
                                                        });

                                            });

                            //Business Process choicebox
                            $("#orgId").change(function() {
                                                $.ajax({
                                                            type : "GET",
                                                            url : servletContextPath
                                                                    + "/OrganizationProcessHandler",
                                                            data : {
                                                                orgId : $params
                                                            },
                                                            cache : false,
                                                            beforeSend : function() {
                                                                //alert(this.url == 'myUrl');
                    //timeout setting 30second
                                                                ajax_timeout = setTimeout(
                                                                        function() {
                                                                            //alert('Request is taking a long time.');
                            },
                                                                        30000);
                                                                //
                                                            },
                                                            success : function(xmlResponse) {
                                                                $(xmlResponse).find('ITEMS')
                                                                        .each(function() {
                                                                                                                                                                        });
                                                                //timeout calling
                                                                if (ajax_timeout) {
                                                                    clearTimeout(ajax_timeout);
                                                                }
                                                                //
                                                            },
                                                            complete : function() {
                                                                //alert(this.async == true);
                                                            }
                                                        });

                                            });

                            //Task Group handler
                            $("#processId").change(function() {
                                                if ($processId.length != 0) {
                                                    $.ajax({
                                                                type : "POST",
                                                                url : servletContextPath
                                                                        + "/TaskGroupsForOrgAndProcessHandler",
                                                                data : {
                                                                    orgId : $orgId,
                                                                    processId : $processId
                                                                },
                                                                cache : false,
                                                                beforeSend : function() {
                                                                    //alert(this.url == 'myUrl');
                        //timeout setting 30second
                                                                    ajax_timeout = setTimeout(
                                                                            function() {
                                                                                //alert('Request is taking a long time.');
                                                                            },
                                                                            30000);
                                                                    //
                                                                },
                                                                success : function(xmlResponse) {
                                                                    $(xmlResponse).find('ITEMS')
                                                                            .each(function() {
                                                                                        //alert("Task Group === "+valTxt);
                                                                                        $('<option value="' + valTxt + '">'
                                                                                                        + labelTxt
                                                                                                        + '</option>')
                                                                                                .appendTo("#taskGrpId");
                                                                                    });
                                                                    //timeout calling
                                                                    if (ajax_timeout) {
                                                                        clearTimeout(ajax_timeout);
                                                                    }
                                                                    //

                                                                },
                                                                complete : function() {
                                                                    //alert(this.async == true);
                                                                }
                                                            });
                                                }
                                            });

                            //Task handler
                            $("#taskGrpId").change(function() {
                                                if ($taskGrpId.length != 0) {
                                                    $.ajax({
                                                                type : "POST",
                                                                url : servletContextPath
                                                                        + "/TaskConfigsHandler",
                                                                data : {
                                                                    orgId : $orgId,
                                                                    processId : $processId,
                                                                    taskGrpId : $taskGrpId
                                                                },
                                                                cache : false,
                                                                beforeSend : function() {
                                                                    ajax_timeout = setTimeout(
                                                                            function() {
                                                                                //alert('Request is taking a long time.');
                                                                            },
                                                                            30000);
                                                                    //
                                                                },
                                                                success : function(
                                                                        xmlResponse) {
                        $(xmlResponse).find('ITEMS')
                                                                            .each(function() {
                                                                                                                                                                            });
                                                                    //timeout calling
                                                                    if (ajax_timeout) {
                                                                        clearTimeout(ajax_timeout);
                                                                    }
                                                                    //

                                                                },
                                                                complete : function() {
                                                                    //alert(this.async == true);
                                                                }
                                                            });
                                                }
                                            });

                        });
    </script>
    <!-- endless -->

    <!-- Layer for during do submition -->
    <script type="text/javascript">
        $(document)
                .ready(
                        function() {
                            $("#Save").click(
                                            function() {
                                                var taskConfigId = document
                                                        .getElementById("taskConfigId").value;
                                                if (taskConfigId == null
                                                        || taskConfigId == ''
                                                        || taskConfigId == -4
                                                        || taskConfigId.length == 0) {
                                                    alert('Please select task');
                                                } else {
                                                    getBackToTaskCreationForm();
                                                    //Get the screen height and width
                                                    var maskHeight = $(document).height();
                                                    var maskWidth = $(window).width();

                                                    //alert("taskConfigId== " +taskConfigId);
                                                    //Set heigth and width to mask to fill up the whole screen
                                                    $('#mask').css({
                                                                        'width' : maskWidth,
                                                                        'height' : maskHeight
                                                                    });

                                                    //transition effect     
                                                                                            }
                                            });

                        });
    </script>

    <style>

代码继续如下:

    <!-- endless -->

    <table width="100%" border="0" class="HeaderPane" cellpadding=0
        cellspacing=0 height="44" bordercolor="#000000">
        <tr width="100%">
            <td width="100%" class="customContentText"><strong>Organization:</strong>
                <select id="orgId" name="orgId">
                    <option VALUE='-1'>------------ Select Organization
                        ------------</option>
            </select></td>
        </tr>
        <tr width="100%">
            <td width="100%" class="customContentText">
                <p id="loading" style="margin-left: 80px;">
                    <img src="/integration/r5/hpr/images/ajax-loader.gif"
                        alt="loading" /> <br />Please wait....
                </p>
                <p id="done"></p>


                <p id="warning" style="margin-left: 80px;">
                    <img src="img/warnsign.gif" alt="warning" width="16" height="16" />
                    <br />Your request has timed out. Please try again. If this
                    condition continues, please contact your administrator.
                </p>  <br />
            </td>
        </tr>
        <tr width="100%">
            <td width="100%" class="customContentText">
                <table width="100%" align="center" class="HeaderPane" id="table1">
                    -------
                </table>
            </td>
            </form>
    </table>

    <!-- Mask to cover the whole screen -->
    <div id="mask">
        <center>
            <img src="/integration/r5/hpr/images/ajax-loader.gif" alt="loading" />
            <br />
            <font color="White" size="4"> Please wait....</font>
        </center>
    </div>


    <%
        if (taskId == null || taskId.trim().equals("")) {
    %>

                </TD>
            </TR>
        </TABLE>
    </TD>
</TR>
</TABLE>
<jsp:include page="/Footer.jsp" />
<%
        } else {
%>
</body>
</html>
<%
        }
%>

这是我的 web.xml 文件:

<?xml version = '1.0' encoding = 'GBK'?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns  /javaee/web-app_2_5.xsd"
     version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">

</web-app>

小服务程序:

public class OrganizationLoadServlet extends HttpServlet {
    private static Logger log = Logger.getLogger(OrganizationLoadServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        Organization[] orgs = (Organization[])session.getAttribute(WorklistappConstants.SESS_ATTR_PREFS_ORGANIZATIONS);

        if (orgs == null) {
            orgs = getFilteredOrgs(request);
            session.setAttribute(WorklistappConstants.SESS_ATTR_PREFS_ORGANIZATIONS, orgs);
        }

        log.info("Before: " + response.getCharacterEncoding());//Here I am getting "iso-8859-1"
        StringBuffer sb = new StringBuffer();
        String dislayName = null;
        for (int i = 0; i < orgs.length; i++) {
            Organization org = orgs[i];
            dislayName = org.getOrgDisplayName();

            sb.append("<ITEMS>");
            sb.append("<LABEL><![CDATA[" + dislayName + "]]></LABEL>");
            sb.append("<VALUE><![CDATA[" + org.getOrgId() + "]]></VALUE>");
            sb.append("</ITEMS>");
        }

        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><ITEM>" + sb.toString() + "</ITEM>");
        log.info("After: " + response.getCharacterEncoding());//Here I am getting "iso-8859-1"

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    private Organization[] getFilteredOrgs(HttpServletRequest request) {
    //code
    return orgs;

    }

    private Organization[] filterOrganizationsByUserOrgs(Organization[] orgs, List<Long> userOrgIdList) {
        //code

        return filteredOrgs;
    }

    private List<Long> getUserOrgIdList(String userId) throws Exception {
    //code

        return userOrgIdList;
    }

    private String getUserID(HttpServletRequest request) throws IOException {

    //code
        return wfCtx.getUser();
    }

}

请参阅 Servlet 类中的 cmets。如果我将iso-8859-1 更改为utf-8,那么我将无法访问该应用程序。

为什么会出现这个问题?

【问题讨论】:

  • 你在哪些浏览器上测试过这个?
  • 使用真正的浏览器并确保您的数据正确地从数据库中输出。
  • 真正意义上的浏览器?? Mozilla 还是 Chrome ???
  • 在 chrome、firefox、opera、safari 等中试一试,并确保在 jsp 文件中只包含一次此标记
  • 您能否为不工作的页面发布 JSP 代码。也许有些东西丢失或放错了地方。

标签: jsp servlets utf-8 character-encoding jdeveloper


【解决方案1】:

试试这个

  1. 添加中文字符后将 JSP 保存为 UTF-8 编码而不是将其保存为 ISO-8859-1
  2. 尝试添加此行 &lt;%@ page contentType="text/html; charset=UTF-8" %&gt; 在您的 JSP 标头中

希望对你有帮助。

【讨论】:

  • 嗨,Holla,我会试试这个......我已经这样做了,除了第一点我做了同样的事情。无论如何,我也会尝试..非常感谢..
【解决方案2】:

这里的问题在于CDATA。在 Servlet 中,我们使用iso-8859-1 以 xml 格式发送 xml 响应。当我们尝试使用UTF-8 时,没有生成 xml 格式的响应。因此,我们没有将 xml 响应从 servlet 发送到 jsp,而是将响应以 html 格式发送并在 jsp 页面上显示为 html 响应。这有助于解决我的问题。

在我们修改的Servlet中

sb.append("<option value="+org.getOrgId()+">"+dislayName+"</option>");
    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    response.getWriter().write(sb.toString());

JSP

$('#orgId').html("<option value=\'-1\'>------------ Select Organization ------------</option>"+xmlResponse);

【讨论】:

    【解决方案3】:

    您是否尝试过为您的页面使用lang 属性?

    类似这样的:

    &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xml:lang="zh"&gt;

    【讨论】:

    • 嗨@Zeinab,它适用于所有其他jsp页面,但如果我们在web.xml文件中提到这是整个应用程序,对吧???
    • 我想是的。主应用程序正在那里运行。
    • 是的,其余页面运行正常,但我们正在从这个jsp页面进行ajax cal,req将由servlet处理。在那个 servlet 中有一些错误。这就是这里的问题。
    • 感谢您的解释,我认为这个链接 (stackoverflow.com/questions/3029401/…) 和这个 (xyzws.com/Javafaq/…) 很有用。
    • 另外这个 (zetcode.com/tutorials/jeetutorials/servlets) 是一个很好的教程,并且有一个与您的代码类似的示例。希望它会有所帮助。
    【解决方案4】:

    您使用的 JSP 标头是正确的。
    但是,我认为问题可能出在项目的编码设置
    UTF-8 不是 jsp 中的默认内容类型。所以你必须改变 项目的文本文件编码为 utf-8

    我对 JDeveloper 没有任何想法...... 但是在 Eclipse 你可以改变这种方式。

    Right Click In Project --> Properties --> Under Resource(Text File Encoding should be selected in "Inherited from Container(UTF-8)"
    

    【讨论】:

    • 中文变成垃圾字符了。什么时候出现问题?在工作区(IDE)中保存期间或在浏览器中显示期间?请澄清
    • 仅在浏览器中显示期间。还有一件事是来自jsp的ajax调用,请求将由“OrganizationLoadServlet”处理
    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2013-02-02
    • 2014-01-03
    相关资源
    最近更新 更多