【问题标题】:why so many "\" s there in this code...what is the usage of it..?为什么这段代码中有这么多“\”......它的用途是什么......?
【发布时间】:2012-02-02 18:28:35
【问题描述】:

我是 servlet 的初学者..看到这段代码写在 servlet 中时,我遇到了一个问题。如果有人解释我这里有这么多“\”的用法,我将不胜感激

"<form method=\"post\" action =\"" + request.getContextPath( ) +
        "/firstservlet\" >");

out.println("<table border=\"0\"><tr><td valign=\"top\">");
out.println("Your first name: </td>  <td valign=\"top\">");
out.println("<input type=\"text\" name=\"firstname\" size=\"20\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("Your last name: </td>  <td valign=\"top\">");
out.println("<input type=\"text\" name=\"lastname\" size=\"20\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("Your email: </td>  <td valign=\"top\">");
out.println("<input type=\"text\" name=\"email\" size=\"20\">");
out.println("</td></tr><tr><td valign=\"top\">");

out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr>");
out.println("</table></form>");
out.println("</body></html>");

【问题讨论】:

  • 转义特殊字符。
  • 如果我是你。我会使用属性文件而不是使用讨厌的转义字符串。
  • 这看起来很糟糕,请尝试使用JSP查看
  • 不要阅读过时的书籍/教程。 HTML 不属于 servlet。 HTML 属于 JSP。另见stackoverflow.com/tags/servlets/info

标签: java servlets


【解决方案1】:

您必须通过编写\" 来转义字符串中的引号"。如果你不这样做,字符串会过早结束。

编辑:示例:

String thisWillNotCompile =  "This String terminates right now" and not later";

试图编译它会给你一个语法错误。

String thisWillCompile = "This String doesn't terminate right now\" but now";

这行得通。

编辑 2:更多详情请阅读Escape Sequences in the Java Tutorial

【讨论】:

  • 你能用一个小例子解释一下吗..??
  • 尝试从您提供的示例中去掉反斜杠,看看会发生什么
【解决方案2】:

是表示"这个字符不是标记字符串结尾的特殊字符,而是字符串的一部分。

【讨论】:

    【解决方案3】:

    \ 在编程语言中称为转义字符。您可以使用它来转义一些特殊字符。例如,如果您想打印一个名为

    的字符串
    Hello " World
    

    如果你指定

    system.out.println("Hello " World"); // Sorry Error :(
    

    这将产生错误,因为" 是一个特殊字符。所以你需要通过放置来逃避这个

    system.out.println("Hello \" World"); // It works :)
    

    【讨论】:

      猜你喜欢
      • 2020-11-22
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多