**iam trying to generate a pdf of my page contents from doPost method. but my tomcat server fails to start each time
below is my code
#SuppressWarnings({ "deprecation", "resource" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String filename="mypdf";
PDDocument mydoc=new PDDocument();
PDPage page=new PDPage();
mydoc.addPage(page);
PDPageContentStream content=new PDPageContentStream(mydoc, page);
content.beginText();
content.setFont(PDType1Font.COURIER_BOLD, 30);
content.moveTextPositionByAmount(250, 750);
content.drawString("syllabus");
content.endText();
content.close();
mydoc.save(filename);
mydoc.close();
System.out.println("the pdf saved at"+System.getProperty("user.dir"));
}catch(IOException ie)
{
System.out.println("IOexception"+ie);
}
}
**
This worked for me. just try formatting like this.
#SuppressWarnings("javadoc")
public class Billing extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
performTask(request, response);
}
private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
//Create pdf
PDDocument document = new PDDocument();
//Create Page
PDPage page = new PDPage();
//Adding the page
document.addPage(page);
//Loading the page
File file = new File("D:/akash/my_doc.pdf");
//writing text
contentStream.beginText();
contentStream.newLineAtOffset(295, 757);
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
contentStream.showText("CHIMERA TRANSPLANT RESEARCH FOUNDATION");
contentStream.endText();
//Saving the document
document.save("D:/akash/my_doc.pdf");
//Closing the document
document.close();
}
}
Related
In my JSF application I have a #WebFilter and I'd like to, when a page forward occurs, get the URI of the destination page. Is that possible?
#WebFilter(servletNames={"Faces Servlet"})
public class MyFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
// here, can I know the URI?
chain.doFilter(request, response);
}
#Override
public void destroy() {}
#Override
public void init(FilterConfig arg0) throws ServletException {}
}
Thanks
I have a servlet api where I used to throw my own exceptions from servlets level
When I throw exception from doGet method everything works fine and exception handler catches and processed my exception. the problem ocures when I throw exception from doPost method. in this case unfortunatelly I never see error page
web.xml
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
exception handler
#WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {
private final Logger logger;
public ErrorHandler() {
logger = Logger.getLogger(ErrorHandler.class);
}
#Override
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
logger.error("occurred exception: ", throwable);
httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}
}
Servlet
#Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
throw new UserException("error message");
}
Add to your ErrorHandler
#Override
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
logger.error("occurred exception: ", throwable);
httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}
To avoid code duplication consider creating third method
private void processError(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
Throwable throwable = (Throwable) httpServletRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
logger.error("occurred exception: ", throwable);
httpServletRequest.getRequestDispatcher("/error.jsp").forward(httpServletRequest, httpServletResponse);
}
and invoke it from both doGet() and doPost()
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
processError(req, resp);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
processError(req, resp);
}
sample code shown below :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside Post");
Client client =Client.create();
WebResource webResource=client.resource("https://mondelezinternational-test.coupahost.com/api/invoices/");
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
ClientResponse resp=webResource.queryParams(queryParams).header("X-COUPA-API-KEY","53fb46e5bb0dbe7fc338f22e2d5035e52cc302fa").header("Accept","application/xml").post(ClientResponse.class);
System.out.println("Responce Body"+resp.getStatusInfo());
System.out.println("Responce Body"+resp.getStatus());
System.out.println("Responce Body"+resp.getLanguage());
System.out.println("Responce Body"+resp.getHeaders());
if (resp.getStatus()==200)
i trying to open a pdf right after i created.
I want to see the result in my browser, but i dosen't.
By the way, the programm runs on a server.
If i try to open the pdf there, no problem - all works fine.
Just the client can't see the pdf if he clicks, for example, on a button.
Here's my code:
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final int id = Integer.parseInt(request.getParameter("id"));
makePdf(request, response, "POST",id);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void makePdf(HttpServletRequest request,
HttpServletResponse response, String methodGetPost, int id)
throws ServletException, IOException {
response.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Test"));
document.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
I using the iText library.
EDIT:
Now i have change my servlet code, but still not working for me.
I can't see the pdf in my browser. Firefox and IE both are show nothing.
package de.WorldCheckCustomer.model;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
makePdf(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
makePdf(request, response);
}
public void makePdf(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set content type to application / pdf
// browser will open the document only if this is set
response.setContentType("application/pdf");
// Get the output stream for writing PDF object
OutputStream out = response.getOutputStream();
try {
Document document = new Document();
/* Basic PDF Creation inside servlet */
PdfWriter.getInstance(document, out);
document.open();
document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
document.add(new Paragraph(
"PDF Created Using Servlet, iText Example Works"));
document.close();
} catch (DocumentException exc) {
throw new IOException(exc.getMessage());
} finally {
out.close();
}
}
private static final long serialVersionUID = 6067021675155015602L;
}
This is something im trying to implement. I have written the doGet method , how do i map the doPost method now ?
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String forward="";
String act = request.getParameter("act");
if (act != null && !act.equalsIgnoreCase("null") &&
act.equalsIgnoreCase("login")) {
forward= "/Login.jsp";
} else if (act!= null && !act.equalsIgnoreCase("null") &&
act.equalsIgnoreCase("register")) {
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else {
forward = "/Login.jsp";
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
If you want to handle POST just like GET you could do
protected void doPost((HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
if you want to treat POST and GET in similar way then you can add a third method
doSomething(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
and call it from both
doGet and do Post
eg
doSomething(request,response);
This is the default code generated by Netbeans IDE.
Keep your code in common method and map it to your invoking method.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}