how to display a PDF through an xhtml - java

I'm trying to display a PDF report on a webApp, I've been following this tutorial here
and it creates the pdf file fine, but I'm having trouble trying to display it in the browser. In my xhtml I have a button, once that button is clicked, a function calling the servlet is called. it goes into the servlet and created a pdf document fine. but I can't seem to figure out how to display it on the screen. is there a way to show the document on a new browser window, or new tab? or even the same one.
I'm working with Java Server faces 2.0 in Eclipse. and have a Tomcat 7.0 server.
on my webxml I added the following code specified in the example:
<servlet>
<servlet-name>PdfServlet</servlet-name>
<servlet-class>com.bravo.servlets.PdfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PdfServlet</servlet-name>
<url-pattern>/PdfServlet</url-pattern>
</servlet-mapping>
and my servlet looks like this ( pretty much the same as the example):
#WebServlet("/PdfServlet")
public class PdfServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Font font = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
/**
* Default constructor.
*/
public PdfServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
invokePDFViewer(response);
Document document = new Document();
try{
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
addContent(document);
document.close();
}catch(DocumentException e){
e.printStackTrace();
}
}
private void invokePDFViewer(HttpServletResponse response){
response.setContentType("application/pdf");
}
private void addContent(Document document)throws DocumentException {
PdfPTable table = new PdfPTable(2);
Paragraph paragraph = new Paragraph ("Este es un parrafo en celda 1", font);
table.addCell(paragraph);
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
}
}
the xhtml I'm calling the servlet from looks like this:
....
function callPdfServlet(){
$.ajax({
type: 'POST',
cache: 'false',
data: 'codeType=notUsed',
url: '/miloWeb/PdfServlet',
async: false,
success: function(data){
},
error: function (xhr, ajaxOptions, thrownError){
alert(ajaxOptions);
}
});
}
.....
<h:commandButton id="reportButton" action=" " styleClass="button" value="get Report" onclick="callPdfServlet();"></h:commandButton>
So at the end, all it does right now is I go into the xhtml in my browser, click on the button, and it hits the servlet, goes through the code, and then thats it. my browser just reloads the screen and nothing else happens. so i need to show the pdf I just created. Thanks in advance for your help!
//************************************************************************************
EDIT 01/02/12:
after reading this and this
I can see that the action in the commandButton will take me to the "response".xhtml with "response" being a string that I either hardcode in, or is returned by an action in a Managed Bean. that response ( if not put in my faces-config file ) will take me to the page IF it's in the same folder as my current page.
so I believe that when I put "miloWeb/PdfServlet" as a response for the action, It looks for the page in the same folder ( which it's not) and since it doesn't find anything just reloads the page. And since I have a break point In the servlet, I am 100% sure it's not hitting it.
so my question is: How do I redirect my page to miloWeb/PdfServlet??
to clarify, it works fine if I put the name of another xhtml in the same folder. so it is working that way.
//This is what I tried just for reference:
Instead of going through the ajax call I've changed the button to
<h:commandButton id="reportButton" action="/miloWeb/PdfServlet" styleClass="button" value="get Report"></h:commandButton>
but it Just reloads the page and doesn't take me to the Servlet.
so another thing I tried was tried to go thought the action of the button calling a Managed Bean:
public String actionPdf(){
return "/miloWeb/PdfServlet";
}
again,same thing, the function returns the string, but it still doesn't take me to the servlet.

Just post a regular form rather than posting in AJAX, and the browser will load the response from your PDF servlet in the page rather than loading it from JavaScript and ignoring it completely:
<form method="post" action="/miloWeb/PdfServlet">
<input type="hidden" name="codeTyped" value="notUsed"/>
<input type="submit" value="Show PDF"/>
</form>

in the action of the commandButton, I had to type this in:
public String doThis(){
String url = "url of your servlet";
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().dispatch(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
return "";
}
So with this, I get the context root and redirect it there. url being /PdfServlet

Related

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:
And below is the image of the code that is working well inside eclipse browser
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() {
}
}
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");

java: create and submit form from servlet and move to the target url

One of the webservices I am trying to connect requires me to submit a form to an url, lets say LINK_A.
I have a form view VIEW_A, I submit VIEW_A to my own servlet called SERVLET_A. Here in SERVLET_A from the form params, I generate a signature key, which is required by the webservice.
Then I need to submit to LINK_A programmaticaly from my servlet, BUT they told me that I need to submit it and redirects to LINK_A, so unlike what I've known so far (using httpclient httppost and getting the response data), I need to do something like a redirect with post data to their link.
So in summary:
1. from my view, submit a form
2. modify post data from servlet
3. submit the form to the webservice link and move to that link (as if the form from the view submit directly to the webservice link)
How can i do this?
If you need the form to be submitted from the browser (not from within your servlet using httpclient) your servlet needs to return a self-submitting form. E.g. use document.getElementById('myForm').submit() on documentReady.
If your form params can be submitted via GET you might also respond with a HTTP 302 redirect containing all params in the query string.
mean if you want collect request from previous form and check in servlet class and forward to new form den check this logic if its help
form code within servlet
rotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<html body=\"red\"> <center>");
pw.println("<form action=\"./NewFile.do\" method=\"get\">");
pw.println("<h2>enter the name </h2> <input type=\"text\" name=\"username\">");
pw.println("<h2>enter the password </h2> <input type=\"text\" name=\"passward\">");
pw.println("<input type=\"submit\" value=\"login\">");
pw.println("</form>");
pw.println("<center></body></html> ");
}
this below code to check and initialize path, before that you have to configure web.xml for this servlet class to behave as controller.
public class ServletControl extends HttpServlet {
#Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside the servlet");
String servletpath=request.getServletPath();
String path = null;
if(servletpath.equalsIgnoreCase("/NewFile.do")){
path="NewFile.jsp";
}
if(path!=null){
RequestDispatcher dis=request.getRequestDispatcher(path);
dis.forward(request, response);
}
}
}

Render HTML response from remote call to the client

I have a working servlet wich originates back from this template:
http://www.objectdb.com/tutorial/jpa/eclipse/web/servlet
So the basic rountrip works.
I added a new feature where I POST data to the servlet, construct a call/request out of the data to a remote http server, retrieve the response-html-string (the content of the website I requested) and want to show this HTML String now as response to my original POST call.
I tried it like this:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
boolean showDetails = Boolean.valueOf(request.getParameter("showDetails"));
if (showDetails) {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
return; // <----------------- if showDetails then this is the end of doPost
}
// Display the list of guests:
doGet(request, response);
}
When I press the link that creates the POST event I see in the logfile, that "loadDetails" has succesfully loaded the content from the remote server, but the browser window does not refresh. Why?
PS: a simple redirect to the other side is not possible for technical reasons.
Try making a ajax request to your servlet which gives to html content as string sent it back to ajax call and set it to innerHTML of a div element.
I changed to use GET instead of POST and I used a separate Servlet for this kind of call. This solved my problem.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String details = detailsLoader.loadDetails(String.valueOf(request.getParameter("value1")),
String.valueOf(request.getParameter("value2")));
response.getWriter().println(details);
response.getWriter().flush();
response.getWriter().close();
}

Server Sent Event HTML5 error(the resource from this url is not text)

I wrote this Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter printWriter=response.getWriter();
printWriter.write("Hello!");
}
and also this java script in index.jsp:
<script>
var resource = new EventSource("/servlet");
resource.onmessage = function (e) {
document.getElementById("container").innerHTML = e.data;
}
</script>
in order to create demo on server-sent events in html5. I inspected the jsp page in firefox and I got this error: the resource from this url is not text and nothing shows up. by the way request status is 200, OK. What is wrong with that?
Try to change the response header
response.setContentType("text/event-stream");

I can't retrieve responseText from servlet using AJAX

I have a servlet file called NewServlet.java. This servlet is called by my AJAX script to retrieve the response.
I have verified the servlet by testing it in a browser.
But when I call it from my AJAX script it gives me a blank responseText and an error that says
XMLHttpRequest cannot load
http://localhost:8084/WebApplication1/NewServlet.
Origin null is not allowed by
Access-Control-Allow-Origin
NewServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<option value='1'>one</option>");
out.println("<option value='2'>two</option>");
out.println("<option value='3'>three</option>");
out.println("<option value='4'>four</option>");
out.println("<option value='5'>five</option>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
test.html
<html>
<head>
<script language = "javascript">
var xmlDoc = 0;
var xhttp = 0;
function reciveData()
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = redirectUser;
xhttp.open("GET","http://localhost:8084/WebApplication1/NewServlet",true);
xhttp.send();
}
function redirectUser()
{
if (xhttp.readyState == 4)
{
log = 0;
xmlDoc = xhttp.responseText;
alert(xmlDoc);
}
}
</script>
</head>
<body onload="reciveData()">
</body>
</html>
Can some one point me in a right direction ?
Thanks.
That's on the browser side...the security model only allows AJAX requests to the same host/port that you fetched the page from. Make sure that you've fetched your page via the server (e.g. http://localhost:8084/test.html) and not loaded it via the filesystem. Then you should be good to go...or at least continue debugging. ;)
This can indeed happen when the servlet runs on a different port than where the ajax request is coming from. This violates the Same Origin Policy for ajax requests and thus the browser won't process the ajax response. Apart from hosting the servlet behind the same port, other solutions are to return JSONP instead or to let the servlet set the HTTP Access-Control headers.
response.setHeader("Access-Control-Allow-Origin", "*");
You however need to keep in mind that this way your servlet is by Ajax accessible to everyone. If the servlet returns sensitive information, then this is a security hole. But if it does not and it is supposed to be a public webservice, then it's safe.
in my experience, if you want to load data with ajax, send your request to a jsp file, and get your response text from that jsp file. it is a lot easier to handel. see this example if you like
EDITED<<
==========================
ajax_load.js :
var xmlhttp;
function loadAdminRight(category){
xmlhttp = GetXmlHttpObject();
if (xmlhttp == null) {
alert("Your browser does not support Ajax HTTP");
return;
}
var url = "load.jsp";
url = url + "?category="+category;
xmlhttp.onreadystatechange = getLoad;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function getLoad(){
if (xmlhttp.readyState == 4) {
document.getElementById("right_content").innerHTML = xmlhttp.responseText;
//or what you want to do
}
}
===========================
load.jsp :
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String l_category = request.getParameter("category");
if(l_category.equals("article")){
out.write("You have choosen article category");
out.write("<br/>");
}
}else if(l_category.equals("news")){
out.write("You have choosen article category");
out.write("<br/>");
}
%>
and to make the ajax going you just need to call the .js function from where you want, for example on a button click action :
onClick="loadAdminRight("article");"
and you can import your java classes in a jsp file with adding <%page import="" %> to the top of your jsp page for example :
<%#page import="com.omicc.classes.Article"%>
write your own load.jsp file which handles the response, then use out.write in your jsp file to write the response text.
i wish it helps you
This will solve your issue..
// Ajax response
res.setContentType("text/javascript");
res.setCharacterEncoding("UTF-8");
res.setHeader("Cache-Control", "no-cache");
PrintWriter out = res.getWriter();
out.print("GRANTED");
out.close();

Categories