【问题标题】:Get Textarea Line breaks in a Java String获取 Java 字符串中的 Textarea 换行符
【发布时间】:2016-02-10 08:55:18
【问题描述】:

我有以下表格:

<form method="post" action="./Contact">
    <input type="text" name="Problem"><br>
    <textarea name="message"></textarea>
    <input type="submit" value="Send Problem">
</form>

进入Contact Servlet代码:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String b = request.getParameter("Problem");
        String a = request.getParameter("message");
        request.setAttribute("message", a);
        request.setAttribute("problem", b);
        request.getRequestDispatcher("./index.jsp").forward(request, response);
    }

只是测试消息,进入 index.jsp 代码:

<p> Problem: ${problem}</p>
<p> Message: ${message}</p>

它正在工作,但我遇到了一个问题,如果书面消息是: "这是一条信息;

这是一个新的消息行。

我要断线了。”

打印出来的信息是: “这是一条信息;这是一条新的信息。我要断线了。”

如何使用字符串从 textarea 消息中获取书面换行符?

【问题讨论】:

    标签: java html forms jsp servlets


    【解决方案1】:

    像这样使用StringBuffer

     protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String b = request.getParameter("Problem");
       // String a = request.getParameter("message");
    
        StringBuffer text = new StringBuffer(request.getParameter("message"));
    
        int loc = (new String(text)).indexOf('\n');
        while(loc > 0){
            text.replace(loc, loc+1, "<BR>");
            loc = (new String(text)).indexOf('\n');
       }
    
        request.setAttribute("message", text);
        request.setAttribute("problem", b);
        request.getRequestDispatcher("./index.jsp").forward(request, response);
    }
    

    【讨论】:

    • Ty,正是我需要的
    • 使用System.lineSeparator()而不是'\n'会更好吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2013-09-19
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    相关资源
    最近更新 更多