3

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.

LGAP
  • 2,151
  • 14
  • 47
  • 68

2 Answers2

13

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
  • 19,611
  • 2
  • 55
  • 64
  • 3
    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 Sep 13 '10 at 22:25
  • yeah... I will do the same as instructed ! – LGAP Sep 13 '10 at 22:31
  • 1
    Another example: http://stackoverflow.com/questions/2370960/how-to-generate-html-response-in-a-servlet/2371656#2371656 – BalusC Sep 13 '10 at 22:57
0

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

just use

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

and write html code there.

Xavier Guihot
  • 32,132
  • 15
  • 193
  • 118
  • This question is seven years old and it already has a seven-year old answer. As much as we accept all answers that get the OP going in the right direction, make sure your answer has a viable alternative. The answer can be “don’t do that”, but it should also include “try this instead”. – baduker Mar 30 '18 at 06:37
  • @baduker,yes i gave an alternative."just use request.getRequestDispatcher("name.jsp").forward(request, response); and write html code there. "...here is my alternative. – rajarshi basak Apr 02 '18 at 05:35