JSP页面中的UTF-8编码

时间:2012-10-04 08:33:43

标签: java jsp utf-8

我有一个页面编码为JSP的{​​{1}}页面。这个JSP页面有一个问题答案博客。我希望在Q / A发布期间包含特殊字符。

问题是JSP不支持ISO-8859-1编码,即使我已将其从UTF-8更改为ISO-8859-1。这些字符(UTF-8~%&)正在出现问题。当我单独或使用任何字符的组合发布这些字符时,它在数据库中是storinh +,当我在发布应用程序时删除这些字符时它工作正常。

任何人都可以建议一些解决方案吗?

14 个答案:

答案 0 :(得分:59)

您应该在应用程序的所有图层上使用相同编码来避免此问题。添加filter来设置编码非常有用:

public void doFilter(ServletRequest request,
                     ServletResponse response,
                     FilterChain chain) throws ServletException {
   request.setCharacterEncoding("UTF-8");
   chain.doFilter(request, response);
}

要仅在JSP页面上设置编码,请将此行添加到它们:

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

将数据库配置为使用相同的char编码。

如果您需要转换字符串的编码,请参阅:

我不建议在您的数据库中存储HTML编码文本。例如,如果您需要生成PDF(或HTML以外的任何内容),则需要先转换HTML编码。

答案 1 :(得分:28)

完整的JSP标记应该是这样的,请注意pageEncoding:

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

一些旧的浏览器也搞乱了编码。您可以使用HTML标记

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

此外,文件应以UTF-8格式记录,如果您使用Eclipse左键单击文件 - &gt;属性 - &gt;签出 - &gt;文本文件编码。

答案 2 :(得分:12)

我也遇到了显示“ṀŮ”等问题的问题。我在web.xml中添加了以下内容。

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

这解决了除标题之外的页面中的问题。试过很多方法解决这个问题,在我的案例中没有任何效果。标题的问题是标题jsp页面包含在另一个jsp中。所以给了导入的编码,这解决了我的问题。

<c:import url="/Header1.jsp" charEncoding="UTF-8"/>

由于

答案 3 :(得分:5)

您必须确保文件已使用UTF-8编码保存。 您可以使用几个纯文本编辑器来完成。使用Notepad ++,您可以在菜单Encoding - &gt; Encode in UTF-8中进行选择。即使使用Windows的记事本(Save As - &gt;编码UTF-8),您也可以执行此操作。 如果您使用的是Eclipse,则可以在文件的属性中设置它。

另外,检查问题是否必须转义这些字符。作为你的问题并不奇怪,因为其中一个角色是&

答案 4 :(得分:5)

此主题可以帮助您: Passing request parameters as UTF-8 encoded strings

基本上:

request.setCharacterEncoding("UTF-8");
String login = request.getParameter("login");
String password = request.getParameter("password");

或者你在jsp文件上使用javascript:

var userInput = $("#myInput").val();            
var encodedUserInput = encodeURIComponent(userInput);
$("#hiddenImput").val(encodedUserInput);

在课堂上恢复后:

String parameter = URLDecoder.decode(request.getParameter("hiddenImput"), "UTF-8");

答案 5 :(得分:5)

我使用的编码过滤器解决了我的所有编码问题...

 package com.dina.filter;

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;

    /**
     *
     * @author DINANATH
     */
    public class EncodingFilter implements Filter {

        private String encoding = "utf-8";

        public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
            request.setCharacterEncoding(encoding);
    //                response.setContentType("text/html;charset=UTF-8");
                    response.setCharacterEncoding(encoding);
            filterChain.doFilter(request, response);

        }

        public void init(FilterConfig filterConfig) throws ServletException {
            String encodingParam = filterConfig.getInitParameter("encoding");
            if (encodingParam != null) {
                encoding = encodingParam;
            }
        }

        public void destroy() {
            // nothing todo
        }

    }
web.xml中的

    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>
        com.dina.filter.EncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

答案 6 :(得分:5)

这会对你有帮助。

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>

答案 7 :(得分:4)

这是一个常见问题。

最简单的解决方法之一是检查特殊字符是否到达操作层内部,然后修改java代码中的特殊字符。

如果您能够在Action中或您选择的任何其他java层(如业务层)中查看此角色,只需使用StringEscapeUtils.html#escapeHtml

替换具有相应HTML字符的字符

做完逃跑。使用新字符串保存到数据库。

答案 8 :(得分:3)

这是html中的特殊字符。为什么不编码呢? 看看:http://www.degraeve.com/reference/specialcharacters.php

答案 9 :(得分:1)

我在JSP上使用特殊字符作为分隔符时遇到了同样的问题。当特殊字符被发布到servlet时,它们都搞砸了。我通过使用以下转换解决了这个问题:

reset_index

答案 10 :(得分:0)

我添加此shell脚本以从IS

转换jsp文件
#!/bin/sh

###############################################
## this script file must be placed in the parent  
## folder of the to folders "in" and "out"
## in contain the input jsp files
## out will containt the generated jsp files
## 
###############################################

find in/ -name *.jsp | 
    while read line; do 
        outpath=`echo $line | sed -e 's/in/out/'` ;
        parentdir=`echo $outpath | sed -e 's/[^\/]*\.jsp$//'` ;
        mkdir -p $parentdir
        echo $outpath ;
        iconv -t UTF-8 -f ISO-8859-1 -o $outpath $line ;
    done 

答案 11 :(得分:0)

感谢所有提示。使用Tomcat8我还添加了像@Jasper de Vries这样的过滤器。但是在现在较新的Tomcats中,已经实现了一个过滤器,可以在Tomcat web.xml中使用resp只是取消注释:

<filter>
    <filter-name>setCharacterEncodingFilter</filter-name>
    <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <async-supported>true</async-supported>
</filter>
...
<filter-mapping>
    <filter-name>setCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

和所有其他人一样;我将URIEncoding="UTF-8"添加到Apache中的Tomcat连接器。这也有帮助。

重要的是,Eclipse(如果你使用它)有一个web.xml的副本并覆盖Tomcat-Settings,如下所述:Broken UTF-8 URI Encoding in JSPs

答案 12 :(得分:0)

页面编码或其他无关紧要。 ISO-8859-1是UTF-8的子集,因此您无需将ISO-8859-1转换为UTF-8,因为ISO-8859-1已经是UTF-8,是UTF-8的子集,但仍然是UTF- 8。 另外,如果您在某处使用双重编码,那么所有这些都不意味着什么。 这是我所有与编码和字符集相关的东西的“治愈方法”:

        String myString = "heartbroken ð";

// String是双重编码的,请首先解决。

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

答案 13 :(得分:0)

JSR315将默认的JSP文件编码指定为ISO-8859-1。这是JSP引擎用来读取JSP文件的编码,与servlet请求或响应编码无关。

如果JSP文件中包含非拉丁字符,请将JSP文件另存为带有BOM的UTF-8或在JSP页面的开头设置pageEncoding

<%@page pageEncoding="UTF-8" %>

但是,您可能希望将所有JSP页面的缺省值都全局更改为UTF-8。可以通过web.xml完成:

<jsp-config>
    <jsp-property-group>
        <url-pattern>/*</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

或者,在将{strong> Spring Boot 与(嵌入式)Tomcat结合使用时,可通过TomcatContextCustomizer

@Component
public class JspConfig implements TomcatContextCustomizer {
    @Override
    public void customize(Context context) {
        JspPropertyGroup pg = new JspPropertyGroup();
        pg.addUrlPattern("/*");
        pg.setPageEncoding("UTF-8");
        pg.setTrimWhitespace("true"); // optional, but nice to have
        ArrayList<JspPropertyGroupDescriptor> pgs = new ArrayList<>();
        pgs.add(new JspPropertyGroupDescriptorImpl(pg));
        context.setJspConfigDescriptor(new JspConfigDescriptorImpl(pgs, new ArrayList<TaglibDescriptor>()));
    }
}

要使JSP与Spring Boot一起使用,请不要忘记包括以下依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

并制作一个“可运行的” .war文件,将其重新打包:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
   . . .