Java/JSP output a text file - java

I need to make a "text" file available on my site so that a partner can read the data daily. I'd like this "text" file to be generated dynamically. We use JSPs and Java Servlets for of our pages
Is there a way to dynamically generate a text file dynamically to be downloaded when the user visits my JSP or a Java Servlet url?
I have tried using a JSP without any html in it. It does put some text on the page, but I can't seem to include line breaks in the output so I think it may be better to just serve it as a file to be downloaded.

To generate some text and download it, you can use something like this:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet( name = "TextOutputServlet", urlPatterns = { "/servlets/giveMeSomeText" } )
public class TextOutputServlet extends HttpServlet {
protected void processRequest( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
response.setContentType( "text/plain;charset=UTF-8" );
response.setHeader( "Content-Disposition", "attachment;filename=MyTextFile.txt" );
PrintWriter out = response.getWriter();
try {
out.println( "Some content..." );
out.println( "Some more..." );
} finally {
out.close();
}
}
#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 );
}
}

Related

NetBeans/Java - breakpoint can't catch exception

In NetBeans / Java - exception breakpoint (for Throwable) does not catch exceptions (RuntimeException in code of library for servlet). If you search tediously, you can find a purple stop line but without looking into the state of variables, etc. VS.NET does not have such ailments - it stops where you need it and everything is clear.
Is this a NetBeans problem or Java? How to get rid of breakpoint problems?
In here example would give you basic understanding of Exception Handling in Servlet
Actually putting a break point you can not catch a servlet exception because of it is happening before reaching the end point then you have to do something like this
When a servlet generates an error developers can handle those exceptions in various ways
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/SampleExceptionHandler")
public class SampleExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
private void exceptionProcessor(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
}
}

Java Servlets set urlPattern from database

I have been practicing java Servlets. Can I set urlPattern from database?
#WebServlet(name = "PatternServlet", urlPatterns = "/pattern")
The following servlet creates html pages getting information from postgres, so content is dynamic. However url address is remaining same each time.
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
#WebServlet(name = "PatternServlet", urlPatterns = "/pattern")
public class PatternServlet extends HttpServlet {
String title;
String content;
List<String> headerItems;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
initializeFields();
//Dynamically creates pages with a given information
PageMaker pageMaker = new PageMaker(title, headerItems, out);
pageMaker.setContent(content);
pageMaker.makePage();
}
public void initializeFields(){
//initializes field from database
}
}
Can I do something to solve this issue? Thank you!
I hope I understand your question correctly. First the urlPatterns are static once the servlet is created. You can use some fancy stuff to give it a name when it starts, but this cannot be changed once set.
But you can use wildcards
#WebServlet(urlPatterns = "/dbcontent/*")
call your servlet with
http://yourserver/dbcontent/dbRef
and then
#Post
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo = request.getPathInfo();
String[] pathElements = pathInfo.split("/");
// get last item (or whatever one you need)
String dbRef = pathInfo[pathInfo.lenth -1];
// check input. User could have tampered url
// do your stuff with dbRef
}
I did not test the code and there are better ways to fetch the dbRef you need, but I hope this illustrates how you can use a servlet to fetch stuff from a database.

Get the default name of the streamed pdf upon clicking on "Save As"

I have a problem that I didn't know exactly how to address, I hope that this will explain it as good as you would need to understand:
I have a streamed pdf file that is previewed on Internet Explorer 11, when I click on "Save as", the default name for the file to be downloaded is the page name where this pdf is streamed, my concern is how I can find a way to set this page's name on response so this pdf plugin would grap and put it in the dialogue box
Thanks
In your HttpResponse, you need to set the Content-Disposition header like this:
Content-Disposition: inline; filename="myfile.txt"
In addition to have the default PDF viewer recognized the file type, you need to set the Content-Type response header to: application/pdf like:
Content-Type: application/pdf
Here is an example servlet that does this correctly:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FileServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String pdfFileName = "pdftest.pdf";
String contextPath = getServletContext().getRealPath(File.separator);
File pdfFile = new File(contextPath + pdfFileName);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
}
}

ValidateLogin Internal Error 500

I'm attempting to create a login process using JSPs and linking them to my MySQL database. The issue I have encountered is an internal error (500) in my browser after I click "login".
I have setup my web.xml for the servlet ValidateLogin.java and I know that is not the issue. Can someone please help me here? I'll place down my code below that involves my HtmlServlet Request and Response.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateLogin extends HttpServlet {
Connection connect;
ResultSet result;
String username, password, query;
DatabaseConnection database_connection;
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UF-8");
PrintWriter out = response.getWriter();
try {
// Code Here...
#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);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Nevermind, I worked out the issue...
Change code from to...
//FROM
response.setContentType("text/html;charset=UF-8");
//TO
response.setContentType("text/html");

How to set response header in JAX-RS so that user sees download popup for Excel?

I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory.
But my goal is when user click on the button (which generate Excel .xls), I want download popup to show up asking user whether to save or open the .xls file just like any other web services doing for downloading any type of files.
According to my search, the step is:
generate Excel .xls (DONE)
write the excel to stream
in JAX-RS file, set response header to something like,
String fileName = "Blah_Report.xls";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
My question is I'm doing all of this in JAX-RS file and I don't have HttpServletResponse object available.
According to the answer from
Add Response Header to JAX-RS Webservice
He says:
You can inject a reference to the
actual HttpServletResponse via the
#Context annotation in your webservice
and use addHeader() etc. to add your
header.
I can't really figure what exactly that means without sample code..
You don't need HttpServletResponse to set a header on the response. You can do it using
javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
#Path("/resource")
class MyResource {
// one way to get HttpServletResponse
#Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(#Context HttpServletResponse servletResponse) {
// ... code
}
}
#Context ServletContext ctx;
#Context private HttpServletResponse response;
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#Path("/download/{filename}")
public StreamingOutput download(#PathParam("filename") String fileName) throws Exception {
final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
return new StreamingOutput() {
#Override
public void write(OutputStream output) throws IOException,
WebApplicationException {
Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
}
};
}
I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.
package local.test.servlet;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
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 local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;
#WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
// /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
System.out.println(templateFileUrl.getPath());
String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
String outputFileDir = "MasatoExcelHorizontalOutput";
ReportProcessor reportProcessor = new ReportProcessor();
ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);
ReportSheet outputSheet = new ReportSheet("MySheet");
outputBook.addReportSheet(outputSheet);
reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
System.out.println("wtf???");
reportProcessor.process(outputBook);
System.out.println("done!!");
}
catch(Exception e) {
System.out.println(e);
}
} //end doGet()
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}//end class
class OutputStreamExporter extends ReportBookExporter {
private HttpServletResponse response;
public OutputStreamExporter(HttpServletResponse response) {
this.response = response;
}
#Override
public String getExtention() {
return null;
}
#Override
public String getFormatType() {
return ExcelExporter.FORMAT_TYPE;
}
#Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {
System.out.println(book.getFirstVisibleTab());
System.out.println(book.getSheetName(0));
//TODO write to stream
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
book.write(response.getOutputStream());
response.getOutputStream().close();
System.out.println("booya!!");
}
catch(Exception e) {
System.out.println(e);
}
}
}//end class

Categories

Resources