Last active
December 20, 2015 14:49
-
-
Save juliozuppa/51fda01bb712664c52cd to your computer and use it in GitHub Desktop.
Exemplo de uma servlet que lê e retorna uma imagem. Salvar as imagens como: banner0.jpg, banner1.jpg, banner(...).jpg, na pasta web (junto com index.jsp)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@page contentType="text/html" pageEncoding="UTF-8"%> | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<title>The Banner Example</title> | |
</head> | |
<body> | |
<h1>Welcome!</h1> | |
<br> | |
<br> | |
<img alt="banner" src="BannerServlet" width="30%" height="30%"/> | |
<br> | |
<br> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.InputStream; | |
//import java.io.PrintWriter; | |
import java.util.Random; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServlet; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
/** | |
* | |
* @author zuppa | |
*/ | |
public class BannerServlet extends HttpServlet { | |
// Pode ser exibida assim: | |
// <img alt="banner" src="BannerServlet" width="30%" height="30%"/> | |
protected void processRequest(HttpServletRequest request, HttpServletResponse response) | |
throws ServletException, IOException { | |
// exemplo de uma servlet que lê e retorna uma imagem | |
// salvar as imagens como: banner0.jpg, banner1.jpg, banner(...).jpg | |
// na pasta web (junto com index.jsp) | |
// envia cabeçalho de imagem para o navegador | |
response.setContentType("image/jpeg"); | |
// criar objeto gerador de numero randomico | |
Random rand = new Random(); | |
// gerar numero aleatorio de acordo com as quantidades de imagens | |
String theRand = String.valueOf(rand.nextInt(5)); | |
// variável para comparar os numeros gerados e armazenados na sessão | |
// de modo que troque a imagem a cada atualização da página | |
String savedRand; | |
// se o atributo da sessão já estiver definido | |
if (request.getSession().getAttribute("banner") != null) { | |
// armazenar o valor do atributo na variável | |
savedRand = request.getSession().getAttribute("banner").toString(); | |
// gerar outro numero aleatório que não seja igual ao armazenado | |
while (theRand.equals(savedRand)) { | |
theRand = String.valueOf(rand.nextInt(5)); | |
} | |
} | |
// definir o novo valor gerado na variável da sessão | |
request.getSession().setAttribute("banner", theRand); | |
// gerar entrada de fluxo para a leitura da imagem | |
InputStream banner = getClass().getClassLoader().getResourceAsStream("../../banner" + theRand + ".jpg"); | |
// gerar um buffer de 4KB para leitura da imagem | |
byte[] buffer = new byte[4096]; | |
// se a entrada de fluxo tiver sido gerada ok | |
if(banner != null) { | |
// fazer leituras sucessivas no tamanho do buffer definido | |
while ((banner.read(buffer)) != -1) { | |
// exibir a imagem de 4 em 4KB até o fim do arquivo | |
response.getOutputStream().write(buffer); | |
} | |
} | |
// limpar o fluxo de saída | |
response.getOutputStream().flush(); | |
/*PrintWriter pr = new PrintWriter(response.getOutputStream()); | |
pr.print(request.getServletContext().getRealPath(getClass().getName()) + "/banner" + theRand + ".jpg"); | |
pr.close();*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment