从 h:inputTextarea 起服务器端不保留换行符

Newline characters are not preserved on server side from h:inputTextarea

我有一个使用 JSF h:inputTextarea 的表单,如下所示:

index.xhtml:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head></h:head>
    <h:body>
        <div id="ContentFrame">

            <h:form enctype="multipart/form-data">

                <h:inputTextarea
                    id="termineesText"
                    value="#{controller.text}"/>

                <h:commandButton
                    value="Upload and Continue" 
                    type = "submit"
                    action="#{controller.respond}"/>

            </h:form>
        </div>
    </h:body>
</html>

result.xhtml:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head></h:head>
    <h:body>
        <div id="ContentFrame">

            <h:form enctype="multipart/form-data">

                <h:inputTextarea
                    id="termineesText"
                    value="#{controller.text}"/>

                <h:outputText value="#{controller.containsNewline}"/>

            </h:form>
        </div>
    </h:body>
</html>

有了这个支持 bean:

controller.java:

package main;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named("controller")
@SessionScoped
public class Controller implements Serializable {
    private static final long serialVersionUID = 1L;
    private String text;
    private boolean containsNewline = false;

    public String respond() {
        return "result.xhtml";
    }

    public void setText(String value) {
        if (value.contains("\n") || value.contains("\r")) {
            containsNewline = true;
        }
        text = value;
    }
    public String getText() {return text;}
    public String getContainsNewline()
    {
        return String.valueOf(containsNewline);
    }
}

当用户输入多行文本(通过按回车键)并提交表单时,换行符在 result.xhtml 的文本区域中消失。例如,如果用户输入:

abc
abc

result.xhtml 的文本区域为 "abcabc",输出文本计算为 false。当表单提交到服务器时,换行符似乎丢失了,这可以使用控制器中的 containsNewLine 布尔值看到。

我读过很多关于为什么当文本来自服务器端时网络浏览器上不显示换行符的帖子,但我的情况恰恰相反,由于某种原因,换行符没有从支持 bean 的文本区域。

我试过的

我试过了:

<pre><h:inputTextarea id="termineesText" styleClass="termineesTextInput" onchange="enableDisableSubmitBtn()" value="#{controller.termineesText}"/></pre>

在CSS中:

.termineesTextInput { white-space: pre; }

我正在使用的技术

JSF 2.2 和 CDI 1.2 运行 在 Websphere Application Server 上,我已经使用 Chrome 隐身 window.

完成了大部分测试

如何让换行符转移到后台 属性?

@Kukeltje 指出的问题是我对 enctype="multipart/form-data" 的使用。出于某种原因,这会导致在将表单提交到服务器时丢失换行符。如果您能够删除该编码并使用正常的 enctype="application/x-www-form-urlencoded",那么这将为您解决问题。希望这对某人有所帮助。

对我来说,删除它不是一个选项,因为我在需要使用 multipart/form-data 的表单上使用文件上传控件。为了解决这个问题,我提出了一个新问题: Newline characters lost when using enctype="multipart/form-data" in html form