How to send servlet response with hardcoded html page? - java

I'd like to response to a url request with a hardcoded but dynamic html response.
Are there better ways than doing following way?
public void doGet(HttpServletRequest request,
HttpServletResponse response)
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
//
}
?

One way is just to forward the response in your servlet:
getServletContext().getRequestDispatcher("mypage.html").forward(request, response);

It's unclear what you mean by "a hardcoded but dynamic html response."
If you mean that you have some number of existing HTML files, and want to pick one based on request parameters, then your servlet can use Class.getResourceAsStream() to load the files. You'll need to package the files on the classpath, which is easy if you use a tool like Maven, little more difficult with a tool like Ant, and hard to maintain if you're just making builds from Eclipse or the command line.
If you mean that you have a single template file and want to change the content in some way, use JSP.

Related

How to have line breaks in text/plain servlet response

I have a servlet that generates some text. The purpose of this is to have a simple status page for an application that can easily be parsed, therefor I'd like to avoid html.
Everything works fine, except that linebreaks get swallowed somewhere in the process.
I tried \r \r\n \n but the result in the browser always looks the same: everything that might look like a line break just disapears and everything is in one looooong line. Which makes it next to impossible to read (both for machines and humans).
Firefox does confirm that the result is of type text/plain
So how do I get line breaks in a text/plain document, that is supposed to be displayed in a browser and generated by a servlet?
update:
Other things that do not work:
println
System.getProperty("line.separator")
in plain/text it is totally dependent on browser's word-wrap processing
for example:
in firefox
about:config
and set this
plain_text.wrap_long_lines;true
you can't handle it from server, you might want to converting it to html with plain text and line breaks or css magic
As #gnicker said, I would go for a content type of text-plain like that in your servlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/plain");
// rest of your code...
}
To output a new line, you just use the println function of your ServletOutputStream:
ServletOutputStream out = response.getOutputStream();
out.println("my text in the first line");
out.println("my text in the second line");
out.close
The new line character could be \n or \r\n though you could just stick with the println function.
Sorry, once again it was my mistake.
We have a compressing Servlet Filter configured which removed the linebreaks.
Without that filter \n works just fine.

Trying to save PDF form fields using iText (PdfAction.createSubmitForm). Losing existing javascript on jsp

I am trying to create a pdf where user fills the fields and saves the data. I created a 'save' button on pdf using iText. I am settig the action of the button using PdfAction.createSubmitForm. While I am getting the formfield values of pdf while saving, I am losing the existing javascript on my JSP due to this button. I am using PdfAction.SUBMIT_HTML_FORMAT in the save button. What am I doing wrong here?
Thanks
The issue has been resolved. If I redirect the servlet action, the JSP displayed is then working fine.
Below is the code
HttpServletResponse response ;
response.setContentType("text/html");
response.setContentLength(13);
String url = new URL(request.getScheme(),request.getServerName(), request.getServerPort(),request.getRequestURI()).toExternalForm();
String target = url+"?action="ServletAction";
response.addHeader("Refresh", new StringBuilder(target.length() + 5)
.append("0;url=").append(target).toString());
ServletOutputStream out = response.getOutputStream();
out.print("<html></html>");
I've read your answer and although it solves your problem (and clarifies the initial problem), you are solving the problem in a really bad way. You are sending an almost empty HTML file <html></html> to the browser and you're expecting that the browser will respect the Refresh header. This is so unprofessional!
Redirecting is done like this:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
String url = new URL(request.getScheme(),request.getServerName(), request.getServerPort(),request.getRequestURI()).toExternalForm();
String target = url+"?action=ServletAction";
response.sendRedirect(target);
}
Replace doGet with doPost if your code snippet was part of a doPost method.

Editing response content on doView()

I have a simple JSR 286 Portlet that displays a user manual (pure HTML code, not JSP).
Actually, my doView method, just contains this :
public class UserManualPortlet extends GenericPortlet
{
#Override
protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException
{
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(
"/html/usermanual.html");
rd.include(request, response);
}
}
This works as expected, however I'm having trouble when including images. I'm aware that the path to images should be something like :
<img src='<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/html/image.jpg")%>'/>
However, my HTML file containing the user manual is used elsewhere, so I would like to preserve it as a pure HTML file.
Is there a way to dynamically replace my classic images urls by something like the example above ? Perhaps using the PrintWriter of the response ?
If such thing is not possible, I thing I would need to generate a JSP file during my Maven build.
Any solution or ideas are welcome.
With JSR-268 portlets you have a better way of referencing resources: create ResourceURL using renderResponse.createResourceURL() and then you set the resourceID in the ResourceURL. That should give more consistent results across all portlet containers.
That said, if you want to modify the generated content from your usermanual.html but you don't want to convert it to a JSP then, instead of using a request dispatcher, I would load the file contents on my own, parse it at the same time that I do the URL replacements and then print all the contents to the portlet's response.

How should I send the response in Servlet to Front end?

I have written a Servlet something like this
public class ServletUtil extends HttpServlet {
private static final long serialVersionUID = 1571172240732862415L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
someDao dao = new someDao();
ArrayList<String> resultAutoComplete=dao.someResults(acInfo);
out.close();
}
}
I have an auto complete Object/wizard in front end and as the user types in it is making Ajax call to back end to grab the list of results. So I have written a Servlet and I am pulling the user input and getting my results from DAO layer.
My question here is how should I send this list(resultAutoComplete) to Front end in the Servlet?
I'd expect you to serialise this in some fashion such that the client understands it. e.g. perhaps using JSON or similar.
I note that your response content type is text/html. So why not simply write each element of your list to your Writer out, separated by (say) a <li> element (with the appropriate unordered/order list entities surrounding this)
Try this,
for (String str : resultAutoComplete)
{
out.println(str);
}
By serializing it to a String and writing it to out...
Seriously though, I wouldn't code at the low level Servlet spec. For this kind of return-this-pojo call I would use Spring 3's RESTful service libraries, or something similar.
No json! instead of going through a list in javascript, return a completed <li> lists and replace innerHTML of <ul>.The reason to do so is to give a better performance. Unless you want to do something more flexible, leave things to the back-end.
When do json, you gotta parse string into json object and then loop through and generate html, that's just an extra step. Keep things simple, plus, parsing string could be costly.
If you don't loop through the list and instead do out.println the list object, you would likely see the address. also, you need to generate html, so:
StringBuilder sb = new StringBuilder();
for(String option: options){
sb.append("<li>").append(option).append("</li>");
}
out.println(sb);

Is there any way to make a JSP print carriage returns (CR)?

I'm currently generating some vCards using JSP. I found out some platforms don't recognize these generated vCards unless their lines are separated by Carriage Returns (CR), and JSP seems to use just Line Feed (LF) by default to separate lines.
Do you guys know any way to tell the JSP to include a CR between each line?
I hope someone has a clue, cause I haven't found much out there...
Thanks in advance!
If you need to emit non-HTML format, then you should be using a servlet instead of a JSP. This way you're not dependent on the JspServlet and/or appserver specifics how the output is been generated. More than often you simply cannot control this.
Using a servlet is relatively simple. Create a class which extends HttpServlet and implement the doGet() method like follows:
response.setContentType("text/x-vcard");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.write("BEGIN:VCARD" + (char) 10);
// ...
Map this in web.xml on an url-pattern of /vcard/* or *.vcf or whatever and use the request servletpath/pathinfo/params to generate output dynamically based on the URL.

Categories