简体   繁体   中英

How to handle HTML tags in servlet java program?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM