I have a web app that must get the city's name by an API request, it should give the foirecast for that city. But in the JSP file I am not able to get a variable with getAttribute()
from the setAttribute()
in the servlet. Don't know why.
Servlet:
package package1;//Librerie da Importareimport jakarta.servlet.ServletException;import java.util.Date;import java.text.SimpleDateFormat;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.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.Scanner;import com.google.gson.Gson;import com.google.gson.JsonObject;import java.io.PrintWriter;// Definisce la servlet con nome "MyServlet" e specifica il l'indirizzo dell'URL a cui andare@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})public class MyServlet extends HttpServlet{ //Variabile identificatore della versione attuale per la serializzazione private static final long serialVersionUID = 1L; //Costruttore che chiama il costruttore della superclasse public MyServlet() { super(); } //Metodo che processa ogni richiesta fatta, dicendo che la risposta deve essere di tipo HTML protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); } //Metodo per le richieste HTTP Get protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); } //Metodo per le richieste HTTP Post protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Chiave Personale dell’API OpenWeatherMap String chiaveAPI = "47da379d1f4d98cfb31a7fa10a00c010"; //Stringa per la variabile della città da cercare String città = request.getParameter("città"); //URL creato, da inviare per la API request String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=" +città+"&appid="+ chiaveAPI; try { //Integrazione con l’API //Oggetto di tipo URL con l'URL dell'API. URL url = new URL(apiUrl); //Apre una connessione HTTP all'URL HttpURLConnection connessione = (HttpURLConnection)url.openConnection(); //Setta il metodo della richiesta HTTP a Get connessione.setRequestMethod("GET"); //Legge i dati dalla rete; //Prende il flusso di input dalla connessione aperta InputStream inpStream = connessione.getInputStream(); //InputStreamReader per leggere dal flusso di input InputStreamReader reader = new InputStreamReader(inpStream); //Salva i dati presi nella stringa definita, con uno StringBuilder StringBuilder risposta = new StringBuilder(); //Crea un’oggetto scanner per prendere in input dal reader Scanner scanner = new Scanner(reader); while(scanner.hasNext()) { risposta.append(scanner.nextLine()); } scanner.close(); //La risposta prodotta dalla API produce un file in formato JSON //Deserializzazione del file JSON in un oggetto //Crea un oggetto gson Gson gson = new Gson(); //Converte la stringa JSON in un oggetto JsonObject JsonObject oggettoJSON = gson.fromJson(risposta.toString(), JsonObject.class); //Stampa l'oggetto System.out.println(oggettoJSON); //Parte per estrarre i dati dal JSON e salvarli //Temperatura double temperaturaKelvin = oggettoJSON.getAsJsonObject("main").get("temp").getAsDouble(); int temperatura = (int)(temperaturaKelvin - 273.15); //Umidità int umidità = oggettoJSON.getAsJsonObject("main").get("humidity").getAsInt(); //Velocità del Vento double velocitàVento = oggettoJSON.getAsJsonObject("wind").get("speed").getAsDouble(); //Visibiltà int visibilitàMetri = oggettoJSON.get("visibility").getAsInt(); int visibilità = visibilitàMetri / 1000; //Condizioni Meteo Generali String condizioni = oggettoJSON.getAsJsonArray("weather").get(0).getAsJsonObject().get("main").getAsString(); //Copertura Nuvole int nuvole = oggettoJSON.getAsJsonObject("clouds").get("all").getAsInt(); //Tempo e Data Attuali al momento della richiesta //Estrae il formato dell'ora della data dalla risposta JSON. long x = oggettoJSON.get("dt").getAsLong() * 1000; //Crea un SimpleDateFormat per formattare la data SimpleDateFormat y = new SimpleDateFormat("MMM dd yyyy"); //Converte il timestamp in una stringa di data formattata String data = y.format(new Date(x)); //Formato dell’ora //Crea un SimpleDateFormat per formattare l'ora SimpleDateFormat z = new SimpleDateFormat("HH:mm"); //Ottiene l'ora formattata String ora = z.format(new Date()); //Setta i dati presi dal JSON per mandarli alla pagina JSP request.setAttribute("date", data); request.setAttribute("city", città); request.setAttribute("visibility",visibilità); request.setAttribute("temperature", temperatura); request.setAttribute("weatherCondition", condizioni); request.setAttribute("humidity", umidità); request.setAttribute("windSpeed", velocitàVento); request.setAttribute("cloudCover", nuvole); request.setAttribute("currentTime", ora); request.setAttribute("weatherData", risposta.toString()); request.setAttribute("pisello", 1); //Chiusura della connessione HTTP connessione.disconnect(); } catch (IOException e) { e.printStackTrace(); } request.setAttribute("pisello", "funzionaOK"); //Manda la richiesta al file JSP per elaborare i dati da mostrare request.getRequestDispatcher("index.jsp").forward(request, response); }}
JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><html><head><meta charset="UTF-8"><title>Web App Meteo - Dettagli</title><link rel="stylesheet" href="jsp-style.css" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"></head><body><div class="container"><h1>Dettagli Meteo</h1><div class="weather-image-container"><img id="weather-icon" src="immagine/img1.png" alt="Weather Image"><div class="temp-city"><h2><i class="fas fa-city"></i> ${city}</h2><h2><i class="fas fa-thermometer-half"></i> ${temperature}°C</h2></div></div><div class="weather-info"><p><i class="fas fa-calendar-alt"></i> Data: ${date}</p><p><i class="fas fa-calendar-alt"></i> Prova: ${pisello}<%=request.getSession().getAttribute("pisello")%></p><p><i class="fas fa-clock"></i> Ora Attuale: ${currentTime}</p><p><i class="fas fa-cloud-sun"></i> Condizioni: ${weatherCondition}</p><p><i class="fas fa-eye"></i> Visibilità: ${visibility}km</p><p><i class="fas fa-wind"></i> Velocita del Vento: ${windSpeed}km/hr</p><p><i class="fas fa-cloud"></i> Copertura delle Nuvole: ${cloudCover}%</p></div><div class="container"><h2>Esegui una nuova ricerca rapida da qui</h2><form id="formMeteo" action="MyServlet" method="post"><input type="text" id="city" name="city" placeholder="Es. Roma, New York, Londra"><button type="submit">Cerca</button><p id="messaggioErrore" style="color: red; padding: 6px 6px; display: none;">Inserisci il nome di una città</p></form></div></div><script src="script.js"></script></body><footer><div class="footer-container"><p>Realizzato dal Gruppo di Lavoro: D.Salvatore, D.Tirro, M.Picciuto, D. Tamilia - 5BI</p></div></footer></html>
HTML:
<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Web App Meteo - Home</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"><link rel="stylesheet" href="style.css" /></head><body><div class="container"><h1>Web App Meteo</h1><form id="formMeteo" action="MyServlet" method="post"><div class="input-wrapper"><input type="text" id="city" name="city" placeholder="Inserisci il nome della città"><button type="submit"><i class="fas fa-search"></i> Cerca</button><p id="messaggioErrore" style="color: red; padding: 6px 6px; display: none;">Please enter the name of the place.</p></div></form></div><script src="script.js"></script></body><footer><div class="footer-container"><p>Realizzato dal Gruppo di Lavoro: D.Salvatore, D.Tirro, M.Picciuto, D. Tamilia - 5BI</p></div></footer></html>
JS:
document.getElementById('formMeteo').addEventListener('submit', function(event){ event.preventDefault(); //Per prevenire l'invio del form nello stato di default/predefinito var cittàInput = document.getElementById('city'); var messaggioErrore = document.getElementById('messaggioErrore'); if (cittàInput.value.trim() === '') { messaggioErrore.style.display = 'block'; //Mostra messaggio di errore } else { messaggioErrore.style.display = 'none'; //Nascondi il messaggio this.submit(); //invia il form }});
The JSP should get the value from the Servlet and show the value of the variable in a HTML page without problem, but my variable is null
.