eclipse 网页上的新行 - Java servlet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27301462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New Line on a web page- Java servlet
提问by Nik_stack
I am new to learning Java Servlet. I am trying to pass parameters through POST query(Apache Tomcat v8.0) using a simple html form that generates two input fields 'UserName' and 'FullName'. The code is running perfectly however; I want 'UserName' and 'FullName' to display on separate new line and I cannot do it by using "/n" inside println() function. Here is my POST query code.
我是学习 Java Servlet 的新手。我正在尝试使用生成两个输入字段“用户名”和“全名”的简单 html 表单通过 POST 查询(Apache Tomcat v8.0)传递参数。然而,代码运行良好;我希望 'UserName' 和 'FullName' 显示在单独的新行上,我不能通过在 println() 函数中使用“/n”来实现。这是我的 POST 查询代码。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String User_name = request.getParameter("UserName");
String Full_name = request.getParameter("FullName");
out.println("\nHello from POST method!");
out.println("\nYour UserName is: " +User_name);
out.println("\nYour FullName is: " +Full_name);
}
回答by developerwjk
\n
is newline for text. View source in browser, and you'll see the \n
is giving you a newline in the HTML source. The problem is, browsers don't display that \n
as a newline in the rendered HTML. That's because to make a newline in HTML you use either <br />
for linebreak, or wrap your line into a paragraph beginning with <p>
and ending with </p>
. If you're going to be doing JSP/Servlet development, you need to learn the basics of HTML.
\n
是文本的换行符。在浏览器中查看源代码,您将看到\n
在 HTML 源代码中为您提供了一个换行符。问题是,浏览器不会\n
在呈现的 HTML 中将其显示为换行符。那是因为要在 HTML 中创建换行符,您可以使用<br />
换行符,或者将您的行换行到以 开头<p>
和结尾的段落中</p>
。如果您打算进行 JSP/Servlet 开发,则需要学习 HTML 的基础知识。
So:
所以:
out.println("<p>Hello from POST method!</p>");
out.println("<p>Your UserName is: " + User_name + "</p>");
or
或者
out.println("Hello from POST method!");
out.println("<br />Your UserName is: " + User_name);
Its also not recommended to print HTML directly in a servlet like this. You should rather set a request attribute and forward to a JSP that acts as a view. This is explained well in the Servlets info page.
也不建议像这样直接在 servlet 中打印 HTML。您应该设置请求属性并转发到充当视图的 JSP。这在Servlets 信息页面中有很好的解释。
Just a hint for the future: After a post which has changed something on the server (saved to db or whatever) you will want to do a server-side redirect to prevent double posting.
只是对未来的一个提示:在更改服务器上的某些内容(保存到 db 或其他任何内容)的帖子之后,您将需要进行服务器端重定向以防止重复发布。