如何处理servlet java程序中的HTML标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3704822/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 03:42:25  来源:igfitidea点击:

How to handle HTML tags in servlet java program?

javahtmljsp

提问by LGAP

1) In my servlet program, I have a statement which will be printed using the code as follows,

1) 在我的 servlet 程序中,我有一个语句,将使用如下代码打印出来,

    out.println("<b>This is servlet output</b>");

Instead of getting printed in bold, it just gets printed with the tag in the broswer itself.

它不是以粗体打印,而是与标签一起打印 在浏览器本身。

How to rectify the same?

一样怎么改?

2) Also, in the servlet page after the submission of a jsp form, I want to add the below HTML tag inside the java code of the servlet program.

2)另外,在提交jsp表单后的servlet页面中,我想在servlet程序的java代码中添加以下HTML标签。

    <a href="upload.jsp">Go to JSP form</a>

How to achieve the same? Please advise.

如何实现相同的?请指教。

采纳答案by Vivien Barousse

1) The browser is interpreting your output like text, try adding

1)浏览器正在像文本一样解释您的输出,请尝试添加

response.setContentType("text/html");

This line tells the browser that you're sending HTML and that it should be interpreted that way.

这一行告诉浏览器您正在发送 HTML 并且应该以这种方式解释它。

2) The same as bold text

2) 与粗体文本相同

out.println("<a href=\"upload.jsp\">Go to JSP form</a>");


On a related note, I'd suggest that none of your Servlet class directly write HTML content to the response page. Servlet are made to handle forms, and aren't easy to use when it comes to write HTML responses.

在相关说明中,我建议您的 Servlet 类都不要直接将 HTML 内容写入响应页面。Servlet 是用来处理表单的,在编写 HTML 响应时不容易使用。

Once thing you can try is to write the response in a JSP page, then forwarding the request to the JSP so it can handle user output.

您可以尝试将响应写入 JSP 页面,然后将请求转发到 JSP,以便它可以处理用户输出。

Here is a sample:

这是一个示例:

1) servet_output.jsp

1)servet_output.jsp

<b>My bold test</b>
<a href="upload.jsp">Go to JSP form</a>

2) Your servlet redirects to the JSP page:

2) 您的 servlet 重定向到 JSP 页面:

request.getRequestDispatcher("servlet_output.jsp").forward(request, response);

This way, your servlet handles the request, and the JSP takes care of writing the response to the browser.

这样,您的 servlet 处理请求,而 JSP 负责将响应写入浏览器。

回答by rajarshi basak

Don't use servlets for html.jsp is the right place to use that.

不要将 servlet 用于 html.jsp 是使用它的正确位置。

just use

只是使用

request.getRequestDispatcher("name.jsp").forward(request, response);

and write html code there.

并在那里编写 html 代码。