Skip to content

Instantly share code, notes, and snippets.

@MuriEdu
Created April 22, 2025 20:42
Show Gist options
  • Save MuriEdu/19a1b33fd6b0b04b92af6a9c964bf1e3 to your computer and use it in GitHub Desktop.
Save MuriEdu/19a1b33fd6b0b04b92af6a9c964bf1e3 to your computer and use it in GitHub Desktop.
DSW - Exercício02
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Erro</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.error-container {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
text-align: center;
}
h1 {
color: #d32f2f;
}
a {
color: #1976d2;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="error-container">
<h1>Erro</h1>
<p>A rota solicitada <strong>__ROTA__</strong> não foi encontrada.</p>
<p><a href="listar">Voltar para o mural</a></p>
</div>
</body>
</html>
// MainServlet.java
package org.example;
import io.vavr.control.Option;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger;
@WebServlet(urlPatterns = {"/*"})
public class MainServlet extends HttpServlet {
private Mural mural = new Mural();
private static Logger logger = Logger.getLogger(MainServlet.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
public void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String rota = Option.of(req.getPathInfo()).getOrElse("");
ServletService servletService = new ServletService(mural);
if (rota.equals("/postar")) {
servletService.handlePostar(req, resp);
} else if (rota.equals("/listar")) {
servletService.handleListar(req, resp);
} else {
servletService.handleErro(rota, resp);
}
}
}
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Mural de Mensagens</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
color: #333;
}
.form-container {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
label {
display: block;
margin-top: 10px;
}
input[type="text"], textarea {
width: 100%;
padding: 8px;
margin-top: 5px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
margin-top: 10px;
}
button:hover {
background-color: #45a049;
}
.mensagens-container {
background-color: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.mensagem {
border-bottom: 1px solid #eee;
padding: 10px 0;
}
.cabecalho {
color: #666;
font-size: 0.9em;
}
.texto {
margin-top: 5px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 4px;
}
</style>
<script>
function validarFormulario() {
const texto = document.forms["mensagemForm"]["texto"].value;
if (texto.trim() === "") {
alert("Por favor, escreva uma mensagem.");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Mural de Mensagens</h1>
<div class="form-container">
<h2>Enviar Mensagem</h2>
<form name="mensagemForm" action="postar" method="post" onsubmit="return validarFormulario()">
<p for="enviadoPor">Enviado por:</p>
<input type="text" name="enviadoPor" placeholder="Seu nome">
<p for="enviadoPara">Enviado para:</p>
<input type="text" name="enviadoPara" placeholder="Destinatário">
<p for="texto">Mensagem:</p>
<textarea name="texto" rows="6" placeholder="Escreva sua mensagem aqui..."></textarea>
<button type="submit">Enviar</button>
</form>
</div>
<div class="mensagens-container">
<h2>Mensagens no Mural</h2>
__MENSAGENS__
</div>
</body>
</html>
// Mural.java
package org.example;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
public class Mural {
private static Logger logger = Logger.getLogger(Mural.class.getName());
private List<Mensagem> mensagens;
private int lastId = 0;
// construtor
public Mural() {
logger.info("Mural Construtor");
this.mensagens = new CopyOnWriteArrayList<>();
// simula 2 mensagens existentes
addMensagem("andre", "turma", "Oi pesssoal!");
addMensagem("Terminator", "John Connor", "I'll be back!");
}
public List<Mensagem> getMensagens() {
return mensagens;
}
public synchronized void addMensagem(String de, String para, String texto) {
int newId = ++lastId;
var novaMsg = new Mensagem(newId, de, para, texto, new Date());
mensagens.add(novaMsg);
}
}
package org.example;
import io.vavr.control.Option;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger;
public class ServletService {
private static final Logger logger = Logger.getLogger(ServletService.class.getName());
private final Mural mural;
public ServletService(Mural mural) {
this.mural = mural;
}
public void handlePostar(HttpServletRequest req, HttpServletResponse resp) throws IOException {
logger.info("Rota /postar");
var enviadoPor = Option.of(req.getParameter("enviadoPor")).getOrElse("");
var enviadoPara = Option.of(req.getParameter("enviadoPara")).getOrElse("");
var texto = Option.of(req.getParameter("texto")).getOrElse("");
if (enviadoPor.isEmpty()) enviadoPor = "Desconhecido";
if (enviadoPara.isEmpty()) enviadoPara = "Desconhecido";
if (texto.isEmpty()) texto = "Sem mensagem escrita.";
mural.addMensagem(enviadoPor, enviadoPara, texto);
resp.sendRedirect("listar");
}
public void handleListar(HttpServletRequest req, HttpServletResponse resp) throws IOException {
logger.info("Rota /listar");
// Carrega o template HTML
String htmlContent = Files.readString(
Path.of("/home/murilo/workspaces/personal/DSW1/muralv1/pages/mensagens.html")
);
// Constrói a lista de mensagens em HTML
StringBuilder mensagensHtml = new StringBuilder();
mural.getMensagens().forEach(mensagem -> {
mensagensHtml.append(String.format("""
<div class="mensagem">
<div class="cabecalho">
<strong>De:</strong> %s &nbsp;
<strong>Para:</strong> %s (em %s)
</div>
<div class="texto">%s</div>
</div>
<br>
""",
mensagem.enviadoPor(),
mensagem.enviadoPara(),
mensagem.timestamp(),
mensagem.texto()
));
});
htmlContent = htmlContent.replace("__MENSAGENS__", mensagensHtml.toString());
resp.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.println(htmlContent);
}
}
public void handleErro(String rota, HttpServletResponse resp) throws IOException {
logger.info("Rota não definida: " + rota);
String htmlContent = Files.readString(
Path.of("/home/murilo/workspaces/personal/DSW1/muralv1/pages/")
);
htmlContent = htmlContent.replace("__ROTA__", rota);
resp.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = resp.getWriter()) {
out.println(htmlContent);
}
}
}
@MuriEdu
Copy link
Author

MuriEdu commented Apr 22, 2025

Para resolver o desafio, a solução foi utilizar o "CopyOnWriteArrayList" já que é uma variação thread-safe do "ArrayList"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment