网页上的新行 - Java servlet [英] New Line on a web page- Java servlet
问题描述
代码运行完美;我想要UserName和FullName显示在单独的新行上,我不能通过在println()函数中使用/ n来实现。
这是我的POST查询代码。
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
// TODO自动生成的方法stub
response.setContentType(text / html);
PrintWriter out = response.getWriter();
String User_name = request.getParameter(UserName);
String Full_name = request.getParameter(FullName);
out.println(\\\
Hello from POST method!);
out.println(\YY UserName is:+ User_name);
out.println(\你的全名是+ Full_name);
}
\\\
是文本的换行符。在浏览器中查看源代码,您将看到
\\\
正在为HTML源代码提供换行符。问题是,浏览器不会在呈现的HTML中显示
\\\
作为换行符。这是因为要在HTML中创建一个换行符,您可以使用
< br />
进行换行,或将您的行包装到以 p>
,以< / p>
结尾。如果你要做JSP / Servlet开发,你需要学习HTML的基础知识。
所以:
< / p>);
out.println(< p> Your UserName is:+ User_name +< / p>);
或
out.println(你好POST程序!);
out.println(< br /> Your UserName is:+ User_name);
它也不建议直接在这样的servlet中打印HTML。您应该设置一个请求属性并转发给作为视图的JSP。这在 Servlets信息页面中有很好的解释。
只需未来的提示:在服务器上更改某些内容(保存到数据库或其他任何内容)的帖子后,您将需要执行服务器端重定向以防止双重发布。
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.
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);
}
\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.
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.
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.
这篇关于网页上的新行 - Java servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!