一尘不染

在Java字符串中获取Textarea换行符

jsp

我有以下表格:

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

进入联系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消息中获得书面的换行符?


阅读 1335

收藏
2020-06-10

共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);
}
2020-06-10