tags:

views:

34

answers:

2

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

    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.

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

How to achieve the same? Please advise.

+2  A: 

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

response.setContentType("text/html");

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

2) The same as bold text

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.

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.

Here is a sample:

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:

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.

Vivien Barousse
Big +1 for the related note. Do not use Servlets for HTML, use JSPs for HTML (and the other way round: do not use JSPs for Java code, use Servlets for Java code). Keep the responsibilities cleanly separated.
BalusC
yeah... I will do the same as instructed !
LGAP
Another example: http://stackoverflow.com/questions/2370960/how-to-generate-html-response-in-a-servlet/2371656#2371656
BalusC
A: 

1) I suspect that the servlet is not setting the "Content-type" header. So the browser has no way to tell that it's receiving HTML content, and displays it as plain text.

2) Sorry, I don't understand the question.

Mike Baranczak