【问题标题】:newline character within script tags脚本标签中的换行符
【发布时间】:2013-11-15 19:21:25
【问题描述】:

我正在学习 servlet,并尝试创建这个基本计算器。我试图将所有异常添加到字符串中,并将该字符串作为错误消息打印在网页上。我只包括代码的基本部分

public class Calculator extends HttpServlet{
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String x = request.getParameter("x");
        String y = request.getParameter("y");
        DecimalFormat df = new DecimalFormat("#,###.##");
        String errorMsg = "";
                if (x != null && y == null) {
            errorMsg = errorMsg.concat("Y cannot be blank\n");
        }
        else if (x == null && y != null) {
            errorMsg = errorMsg.concat("X cannot be blank");
        }
                out.println("<!doctype html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Calculator</title>");
        out.println("</head>");
        out.println("<body>");
        if (!errorMsg.equalsIgnoreCase("")) {
            out.println("<h2>"+errorMsg+"</h2>");
        }

        out.println("<form>");
        out.println("<table border='1' style='background-color:#999'>");
        out.println("<tr><td>X </td> <td><input type='text' id='xValue' name='x' /></td></tr>");
        out.println("<tr><td>Y </td> <td><input type='text' id='yValue' name='y' /></td></tr>");
        out.println("<tr><td colspan='2'>");
        out.println("<input type='submit' id='plusButton' value='+' name='add' />");
        out.println("<input type='submit' id='minusButton' value='-' name='sub' />");
        out.println("<input type='submit' id='mulButton' value='*' name='mul' />");
        out.println("<input type='submit' id='divButton' value='/' name='div' />");
        out.println("</table>");
        out.println("</form></body></html>");

    }
}

如果我在 X 和 Y 文本字段中输入字母,我应该会收到一条错误消息。更具体地说,我应该在两个单独的行上收到两个错误消息。但是我让他们都在同一条线上。在命令行上,我将它们放在不同的行上。我在这里做错了什么?

【问题讨论】:

  • 好而清晰的问题,欢迎来到 StackOverflow!

标签: java html servlets


【解决方案1】:

新行字符(\n\r 或两者)不会在 HTML 中呈现为新行。

为了在 HTML 中查看新行,您需要使用指定的换行标记

<br> 

例如

    String errorMsg = "";
    if (x != null && y == null) {
        errorMsg = errorMsg.concat("Y cannot be blank<br>");
    }
    else if (x == null && y != null) {
        errorMsg = errorMsg.concat("X cannot be blank");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2010-10-03
    • 2022-01-14
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多