Posts in servlet

Download file with GWT

marzo 29th, 2013 Posted by gwt, java, servlet 0 thoughts on “Download file with GWT”

Esta es una manera fácil de enviar desde GWT archivos al navegador para que los usuarios se los puedan descargar.

1. Hay que agregar un frame oculto en el HTML de la hosted page:

<div id="__gwt_downloadFrame" tabIndex='-1'></div>

2. Para iniciar la descarga poner este código en la parte cliente (código GWT):


public static void download(String p_uuid, String p_filename) {
String fileDownloadURL = "/fileDownloadServlet"
+ "?id=" + p_uuid
+ "&filename=" +
URL.encode(p_filename);
Frame fileDownloadFrame = new Frame(fileDownloadURL);
fileDownloadFrame.setSize("0px", "0px");
fileDownloadFrame.setVisible(false);
RootPanel panel = RootPanel.get("__gwt_downloadFrame");
while (panel.getWidgetCount() > 0)
panel.remove(0);
panel.add(fileDownloadFrame);
}

3. Poner esto en el servlet que va a servir el archivo a descargar:


@Override
protected void doGet(HttpServletRequest p_request,
HttpServletResponse p_response)
throws ServletException, IOException {
String filename = p_request.getParameter("filename");
if (filename == null)
{
p_response.sendError(SC_BAD_REQUEST, "Missing filename");
return;
}

File file = /* however you choose to go about resolving
filename */

long length = file.length();
FileInputStream fis = new FileInputStream(file);
p_response.addHeader("Content-Disposition",
"attachment; filename="" + filename +
""");
p_response.setContentType("application/octet-stream");
if (length > 0 && length <= Integer.MAX_VALUE);
p_response.setContentLength((int)length);
ServletOutputStream out = p_response.getOutputStream();
p_response.setBufferSize(32768);
int bufSize = p_response.getBufferSize();
byte[] buffer = new byte[bufSize];
BufferedInputStream bis = new BufferedInputStream(fis,
bufSize);
int bytes;
while ((bytes = bis.read(buffer, 0, bufSize)) >= 0)
out.write(buffer, 0, bytes);
bis.close();
fis.close();
out.flush();
out.close();
}

How to get client ip in a Java Servlet

octubre 29th, 2010 Posted by java, servlet 0 thoughts on “How to get client ip in a Java Servlet”

req.getRemoteAddr();
req.getRemoteHost();

How to get user locale in a Java Servlet

septiembre 30th, 2010 Posted by java, locale, servlet 0 thoughts on “How to get user locale in a Java Servlet”

Locale locale = request.getLocale();
Enumeration locales = request.getLocales();

Copyright © 2018 programadorfreelanceargentina.com

Programador Freelance Argentina