Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

java - Why Servlet program outputting HTML text as it is?

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:

enter image description here

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

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() {

}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...