为什么Servlet程序按原样输出HTML文本? [英] Why Servlet program outputting HTML text as it is?

查看:64
本文介绍了为什么Servlet程序按原样输出HTML文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,该程序使用servlet在浏览器上打印欢迎来到我们的网站"文本.在eclipse默认浏览器中它可以正常工作,但是当我将该URL用于其他浏览器时,它将显示以下文本:

下面是在Eclipse浏览器中运行良好的代码的图像

我的代码如下:

 公共类WelcomePage扩展HttpServlet {@Override公共无效init()引发ServletException {}@Override受保护的无效服务(HttpServletRequest req,HttpServletResponse res)抛出ServletException,IOException {PrintWriter out = res.getWriter();out.println(< h3>欢迎来到我们的网站< h3>"));out.println(< form>");out.println(</form>");}@Override公共无效destroy(){} 

}

解决方案

添加res.setContentType(text/html);问题已解决:)

在将数据发送到客户端之前(由客户端计算机上的浏览器显示),Servlet容器通知客户端浏览器当前正在发送什么类型的数据.可以发送的数据可以是简单的纯文本,html形式,xml形式,gif或jpg类型的图像形式,excel表格等.要发送此信息,Servlet容器使用带有setContentType()方法的响应对象.

一些示例:

  response.setContentType("text/html");response.setContentType("text/plain");response.setContentType("text/css");response.setContentType("application/html");response.setContentType("image/gif");response.setContentType("application/zip");response.setContentType("application/pdf"); 

I created one program that prints 'Welcome to our site' text on browser using servlet. It works fine inside the eclipse default browser but when I use that URL to other browser it displays text as below:

And below is the image of the code that is working well inside eclipse browser

And my code is as follows:

public class WelcomePage extends HttpServlet {
@Override
public void init() throws ServletException {

}
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    PrintWriter out = res.getWriter();
    out.println("<h3>Welcome to our site<h3>");
    out.println("<form>");
    out.println("</form>");
}
@Override
public void destroy() {

}

}

解决方案

After adding res.setContentType(text/html); problem resolved :)

Before sending data to client (displayed by Browser on client machine), the Servlet container informs the client browser of what type of data is being sent now. The data that can be sent may be simple plain text, html form, xml form, image form of type gif or jpg, excel sheet etc. To send this information, the Servlet container uses response object with the method setContentType().

Some examples :

response.setContentType("text/html");           
response.setContentType("text/plain");  
response.setContentType("text/css");            
response.setContentType("application/html");
response.setContentType("image/gif");
response.setContentType("application/zip");
response.setContentType("application/pdf");

这篇关于为什么Servlet程序按原样输出HTML文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆