diseÑo de aplicaciones web bloque 3: parte servidora...
TRANSCRIPT
![Page 1: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/1.jpg)
Bloque 3: Parte servidora (backend)
DISEÑODEAPLICACIONESWEB
TEMA3.2:APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
![Page 2: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/2.jpg)
Disclaimer
• Estematerialestábasadoenunmaterialoriginalde:§ BoniGarcía([email protected])
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
2
![Page 3: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/3.jpg)
Índice de contenidos
1. SpringMVC2. Thymeleaf3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
3
![Page 4: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/4.jpg)
Índice de contenidos
1. SpringMVC§ Introducción
§ Controladores
§ Vistas
§ Ejemplo2. Thymeleaf3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
4
![Page 5: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/5.jpg)
1. Spring MVC
Introducción• Elmodelovistacontrolador(MVC)separalosdatosylalógicadenegociodeuna
aplicacióndelainterfazdeusuario.
• ElesquemadelpatrónMVCenSpringes:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
5
GreetingController.java
greeting_template.html
Controlador
Vista (Plantilla)
Petición URL desde
el Navegador
http://spring.io/guides/gs/serving-web-content/
Página HTML
Modelo
![Page 6: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/6.jpg)
1. Spring MVC
Controladores• Loscontroladores(Controllers)sonclasesJavaencargadasdeatenderlaspeticionesweb.
• Procesanlosdatosquelleganenlapetición(parámetros).• Hacenpeticionesalabasededatos,usandiversosservicios,etc…
• Definenlainformaciónqueserávisualizadaenlapáginaweb(elmodelo).
• DeterminanquevistaserálaencargadadegenerarlapáginaHTML.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
6
![Page 7: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/7.jpg)
1. Spring MVC
Vistas• LasvistasenSpringMVCseimplementancomoplantillasHTML.
• GeneranHTMLpartiendodeunaplantillaylainformaciónquevienedelcontrolador(modelo).
• ExistendiversastecnologíasdeplantillasquesepuedenusarconSpringMVC:JSP,Thymeleaf,FreeMarker,etc…
• NosotrosusaremosThymeleaf.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
7
![Page 8: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/8.jpg)
1. Spring MVC
Ejemplo• EstructuradelaaplicaciónvistadesdeEclipse:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
8
![Page 9: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/9.jpg)
1. Spring MVC
Ejemplo
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
9
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.github.web</groupId> <artifactId>spring-mvc-hello-world</artifactId> <version>1.0.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.7.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project>
pom.xml
Proyectopadredelqueseheredalaconfiguración(SpringBoot)
TipodeproyectoSpringBoot
Java8
![Page 10: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/10.jpg)
1. Spring MVC
Ejemplo
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
10
package io.github.web.springmvc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class GreetingController { @RequestMapping("/greeting") public ModelAndView greeting() { return new ModelAndView("greeting_template").addObject("name", "World"); } }
SeindicalaURLconlaqueseejecutan
Seincluyelainformaciónenel
modelo
Seindicaelnombredelaplantillaquegenerarála
páginaHTML
GreetingController.java
![Page 11: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/11.jpg)
1. Spring MVC
Ejemplo• Vistas(implementadoconThymeleaf)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
11
<html xmlns:th="http://www.thymeleaf.org"> <body> <p>Hello <span th:text="${name}">Friend</span>!</p> </body> </html>
Seaccedealosobjetosqueelcontroladorhapuestoenel
modelo
Elvalordelobjetoname sustituiráalapalabraFriend cuandosegenereelHTML
greeting_template.html
![Page 12: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/12.jpg)
1. Spring MVC
Ejemplo• LaaplicaciónseejecutacomounaappJavanormal
• EnEclipse:botónderechoproyecto>Runas…>JavaApplication…
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
12
@SpringBootApplication public class SpringMvcHelloWorldApp extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(SpringMvcHelloWorldApp.class, args); } }
SpringMvcHelloWorldApp.java
![Page 13: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/13.jpg)
Índice de contenidos
1. SpringMVC2. Thymeleaf
§ Introducción§ Ejemplo§ Manejandotexto§ Condicionales§ Iteraciones
3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
13
![Page 14: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/14.jpg)
2. Thymeleaf
Introducción• SpringMVCseapoyaenalgunatecnologíadeplantillasparalageneracióndepáginasHTML:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
14
http://freemarker.org/
http://www.thymeleaf.org/
http://www.oracle.com/technetwork/java/javaee/jsp/
http://velocity.apache.org/
![Page 15: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/15.jpg)
2. Thymeleaf
Introducción• Todasestastecnologíassonconceptualmentesimilares.
§ LosficherosHTMLsegenerarconplantillasquecontienencódigoHTMLjuntoconreferenciasavariablesyfunciones.
§ EjemploimplementadoconFreeMarker:
• ThymeleafsediferenciadelasdemásenquelasplantillassonficherosHTMLválidosquepuedenverseenunnavegadorsinnecesidaddeservidorweb(naturaltemplating).
• Estacaracterísticaesidealparalaseparaciónderoles:diseñadoresydesarrolladores.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
15
<html> <body> <p>Hello ${name}!</p> </body> </html>
![Page 16: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/16.jpg)
2. Thymeleaf
Introducción• LatecnologíadeplantillasJSP(JavaServerPage)eslamásextendida• AmbaspuedenserusadasenconjunciónconSpringMVC• ThymeleafpermiterealizarlamaquetaciónHTMLsinnecesidaddeque
intervengaelservidor
• Másinformación:http://www.thymeleaf.org/doc/articles/thvsjsp.html
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
16
![Page 17: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/17.jpg)
2. Thymeleaf
Introducción• ThymeleafestátotalmenteIntegradoconSpring(MVC,Security)• Soportadostipodelenguajesdeexpresiones(EL,ExpressionLanguage)
paraelaccesoaobjetosJava:§ OGNL(Object-GraphNavigationLanguage):
§ SpringEL(SpringExpressionLanguage)
• Tutorial:http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
17
${myObject.property}
${@myBean.method()}
${myObject.method()}
![Page 18: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/18.jpg)
2. Thymeleaf
Introducción• LasintaxisdelasplantillasThymeleafsedefineenlaspáginasHTMLmediantelaetiquetath
• Losnavegadoresignoraránelespaciodenombrequenoentienden(th)conloquelapáginaseguirásiendoválida
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
18
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <p>Hello <span th:text="${name}"></span></p> </body> </html>
El atributo xmlns define el espacio de nombres (XML Namespace) para th. Un espacio de nombres permite definir nombres de elementos y atributos únicos en un documento XML (o HTML)
![Page 19: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/19.jpg)
2. Thymeleaf
Ejemplo
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
19
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.github.bonigarcia.web</groupId> <artifactId>ThymeLeafDemo</artifactId> <version>1.0.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.7.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> </project>
pom.xml
![Page 20: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/20.jpg)
2. Thymeleaf
Ejemplo
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
20
SpringMvcThymeleafApp.java
package io.github.web.thymeleaf; public class MyObject { private String name; private String description; public MyObject(String name, String description) { this.name = name; this.description = description; } public String sayHello() { return "Hello!!!"; } // Getters and setters }
MyObject.java
package io.github.web.thymeleaf; import org.springframework.boot.*; import org.springframework.web.servlet.config.annotation.*; @SpringBootApplication public class SpringMvcThymeleafApp extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(SpringMvcThymeleafApp.class, args); } }
![Page 21: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/21.jpg)
2. Thymeleaf
Manejandotexto• Paramostrartextoenlaplantillausamoslaetiquetath:text
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
21
package io.github.web.thymeleaf; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class TextController { @RequestMapping("/text") public ModelAndView text() { MyObject myObject = new MyObject("my name", "my description"); return new ModelAndView("text_page").addObject("greetings", "Hello world!").addObject("myobj", myObject); } }
TextController.java
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <p th:text="${greetings}"></p> <p th:text="${myobj.name}"></p> <p th:text="${myobj.sayHello()}"></p> <p th:text="|I say: ${myobj.description}!|"></p> </body> </html>
text_page.html
![Page 22: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/22.jpg)
2. Thymeleaf
Condicionales• Etiquetath:if
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
22
package io.github.web.thymeleaf; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class TextController { @RequestMapping("/text") public ModelAndView text() { MyObject myObject = new MyObject("my name", "my description"); return new ModelAndView("text_page") .addObject("greetings", "Hello world!") .addObject("myobj", myObject).addObject("hidden", false); } }
TextController.java
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <p th:text="${greetings}"></p> <p th:text="${myobj.name}"></p> <p th:text="${myobj.sayHello()}"></p> <p th:text="|I say: ${myobj.description}!|"></p> <p th:if="${not hidden}">This is visible!</p> </body> </html>
text_page.html
![Page 23: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/23.jpg)
2. Thymeleaf
Iteraciones• Etiquetath:each
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
23
@RequestMapping("/iteration") public ModelAndView iteration() { List<String> colors = Arrays.asList("Red", "Blue", "Green"); return new ModelAndView("iteration_template").addObject("colors", colors); }
TextController.java
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <p>Colors in list:</p> <ul> <li th:each="color : ${colors}" th:text="${color}">Color</li> </ul> <p>Colors in table:</p> <table border="1"> <tr th:each="color, it : ${colors}"> <td th:text="${it.index}">1</td> <td th:text="${color}">Color</td> </tr> </table> </body> </html>
iteration_template.html
Se puede declarar una variable adicional para guardar información de
la iteración
![Page 24: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/24.jpg)
Índice de contenidos
1. SpringMVC2. Thymeleaf
3. Envíodeinformaciónalservidor§ Envíomedianteformulario
§ EnvíomedianteURL
§ URLsenThymeleaf4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
24
![Page 25: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/25.jpg)
3. Envío de información al servidor
• Formascomunesdeenviarinformacióndelnavegadoralservidor:§ MedianteformulariosHTML:Lainformaciónlaintroducemanualmenteelusuario.
§ InsertandoinformaciónenlaURLenenlaces:Lainformaciónlaincluyeeldesarrolladorparaqueestédisponiblecuandoelusuariopulsaelenlace.
• Accesoalainformaciónenelservidor§ Lainformaciónseenvíacomopares(clave,valor).
§ Seaccedealainformacióncomoparámetrosenlosmétodosdelcontrolador.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
25
![Page 26: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/26.jpg)
3. Envío de información al servidor
Envíomedianteformulario• EjemplodeformularioHTML(partecliente)ycontrolador(parteservidor):
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
26
<!DOCTYPE html> <html> <body> <form action="processForm" method="post"> <h1>Form</h1> <label for="input">Input</label> <input type="text" name="input" id="input"> <input type="submit"> </form> </body> </html>
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller public class FormController { @RequestMapping("/processForm") public ModelAndView process(@RequestParam String input) { return new ModelAndView("result").addObject("result", input); } }
![Page 27: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/27.jpg)
3. Envío de información al servidor
EnvíomedianteURL(opción1)• LaprimeraopcióndeenviardatosmedianteURLconsisteensimularelenvíoGETdeunformulario:
§ SeincluyenalfinaldelaURLseparadoscon?(query)
§ Losparámetrosseseparanentresícon&
§ Cadaparámetrosecodificacomonombre=valor
• Ejemplo:
http://my-server.com/path?option=web&view=category&lang=es
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
27
![Page 28: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/28.jpg)
3. Envío de información al servidor
EnvíomedianteURL(opción1)• Formato:Codificacióndelosnombresylosvalores
§ Loscaracteresalfanuméricos"a"hasta"z","A"hasta"Z"y"0"hasta"9"sequedanigual
§ Loscaracteresespeciales".","-","*",y"_"sequedanigual
§ Elcarácterespacio" "esconvertidoalsigno"+"oconsuvalorhexadecimal%20
§ Todoslosotroscaracteressoncodificadosenunoomásbytes.Despuéscadabyteesrepresentadoporlacadenade3caracteres"%xy",dondexyeslarepresentaciónenhexadecimal
• Ejemplo:
http://localhost:8080/demo?parameter=hello%20world
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
28
![Page 29: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/29.jpg)
3. Envío de información al servidor
EnvíomedianteURL(opción1)• Paraaccederalainformaciónseusaelmismomecanismoqueparaleerloscamposdelformulario
• Ejemplo:
http://my-server.com/path?option=web&view=category&lang=es
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
29
@RequestMapping("/path") public ModelAndView path(@RequestParam String option, @RequestParam String view, @RequestParam String lang) { // Create and return model }
![Page 30: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/30.jpg)
3. Envío de información al servidor
EnvíomedianteURL(opción2)• LainformacióntambiénsepuedenincluircomopartedelapropiaURL,envezdecómoparámetros
• Ejemplo:
http://my-server.com/path/web/category/es
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
30
@RequestMapping("/path/{option}/{view}/{lang}")publicModelAndViewpath(@PathVariableStringoption,@PathVariableStringview,@PathVariableStringlang){//Createandreturnmodel}
![Page 31: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/31.jpg)
3. Envío de información al servidor
URLsenThymeleaf• Debidoasuimportancia,lasURLsson“ciudadanosdeprimeraclase”enThymeleafytienenunasintaxisespecial
• Losenlacestambiénsepuedenconstruirenunaplantillaconlainformacióndelmodelo
• Ejemplo:Modeloconunobjetoid :
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
31
<!-- Will produce '/order/details?orderId=3' --> <a href="details.html" th:href="@{/order/details(orderId=${id})}">view</a> <!-- Will produce '/order/3/details' --> <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${id})}">view</a>
Se usa con el símbolo @
La etiqueta th:href generará el atributo href del enlace
![Page 32: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/32.jpg)
Índice de contenidos
1. SpringMVC2. Thymeleaf3. Envíodeinformaciónalservidor
4. Gestióndedatosdesesión§ ObjetoHttpSession
§ GestióndelasesiónenSpring
§ ObjetoHttpSessionvssesiónSpring
5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
32
![Page 33: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/33.jpg)
4. Gestión de datos de sesión
• Eshabitualquelasaplicacioneswebgestioneninformacióndiferenteparacadausuarioqueestánavegando.Porejemplo:§ AmigosenFacebook.
§ ListadecorreosenGmail.
§ CarritodelacompraenAmazon.
• Sepuedegestionarlainformacióndelusuarioendosámbitosdiferentes:§ Informaciónqueseutilizadurantelanavegacióndelusuario,durantela
sesiónactual.
§ Informaciónqueseguardamientrasqueelusuarionoestánavegandoyqueserecuperacuandoelusuariovuelveavisitarlapáginaweb(informaciónpersistente).
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
33
![Page 34: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/34.jpg)
4. Gestión de datos de sesión
• Sesión:Mantenerinformaciónmientraselusuarionavegaporlaweb.§ Cuandoelusuariopasaciertotiemposinrealizarpeticionesalaweb,la
sesiónfinalizaautomáticamente(caducidad).
§ Eltiempoparaquecaducidadesconfigurable.
§ Lainformacióndesesiónseguardaenmemoriadelservidorweb.
• Informaciónpersistente:Guardarinformaciónentredistintasnavegacionesporlaweb.§ Paraquepodamosguardarinformacióndelusuarioenelservidor,es
necesarioqueelusuarioseidentifiquealaccederalapágina.
§ LainformaciónsesueleguardarenelservidorwebenunaBBDD.
§ LalógicadelaaplicacióndeterminaaquéinformacióndelaBBDDpuedeaccedercadausuario.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
34
![Page 35: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/35.jpg)
4. Gestión de datos de sesión
• Existendostécnicasprincipales:1. ObjetoHttpSession
§ EslaformabásicadegestióndesesionesenJavaEE.
§ ExisteunobjetoHttpSessionporcadausuarioquenavegaporlaweb.
§ Sepuedealmacenarinformaciónenunapeticiónyrecuperarlainformaciónenotrapeticiónposterior.
§ Esdemásbajonivel.
2. Componenteespecíficoparacadausuario.
§ CadausuarioguardasuinformaciónenunoovarioscomponentesSpring.
§ Existeunainstanciaporcadausuario(cuandolohabitualestenerunaúnicainstanciaporcomponente).
§ Esdemásaltonivel.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
35
![Page 36: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/36.jpg)
4. Gestión de datos de sesión
ObjetoHttpSession • Lasesiónserepresentacomounobjetodelinterfazjavax.servlet.http.HttpSession.
• ElframeworkSpringeselencargadodecrearunobjetodelasesióndiferenteparacadausuario.
• Paraaccederalobjetodelasesióndelusuarioqueestáhaciendounapetición,bastaincluirlocomoparámetroenelmétododelcontrolador.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
36
@RequestMapping("/mypath") public ModelAndView process(HttpSession session, ...) { Object info = ...; session.setAttribute("info", info); return new ModelAndView("template"); }
![Page 37: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/37.jpg)
4. Gestión de datos de sesión
ObjetoHttpSession • Ejemplo:
§ Laaplicaciónrecogelainformacióndeformularioylaguardadedosformas:� Atributodelcontrolador(compartida).� Atributodelasesión(usuario).
§ Unavezguardadalainformación,sepuedeaccederaellaygenerarunapágina.
§ Sidosusuariosvisitanestapáginaalavez,sepuedevercómolainformacióndelcontroladorescompartida(laqueguardaelúltimousuarioeslaquesemuestra),perolaqueseguardaenlasesiónesdiferenteparacadausuario.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
37
![Page 38: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/38.jpg)
4. Gestión de datos de sesión
ObjetoHttpSession • Ejemplo:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
38
Guardalainformaciónenlaunatributodelasesiónyenunatributodelcontrolador
Recuperalainformacióndelasesión(usuario)ydelcontrolador(compartida)
![Page 39: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/39.jpg)
4. Gestión de datos de sesión
ObjetoHttpSession • Ejemplo:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
39
@Controller public class SessionController { private String sharedInfo; @RequestMapping(value = "/processForm") public ModelAndView processForm(@RequestParam String info, HttpSession sesion) { sesion.setAttribute("userInfo", info); sharedInfo = info; return new ModelAndView("form_result"); } @RequestMapping("/showData") public ModelAndView showData(HttpSession sesion) { String userInfo = (String) sesion.getAttribute("userInfo"); return new ModelAndView("data").addObject("userInfo", userInfo).addObject("sharedInfo", sharedInfo); } }
![Page 40: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/40.jpg)
4. Gestión de datos de sesión
ObjetoHttpSession • MétodosdeHttpSession:
§ void setAttribute(String name, Object value):Asociaunobjetoalasesiónidentificadoporunnombre.
§ Object getAttribute(String name):Recuperaunobjetopreviamenteasociadoalasesión.
§ boolean isNew():Indicasieslaprimerapáginaquesolicitaelusuario(sesiónnueva)
§ void invalidate():Cierralasesióndelusuarioborrandotodossusdatos.Sivisitanuevamentelapágina,seráconsideradocomounusuarionuevo.
§ void setMaxInactiveInterval(int seconds):Configuraeltiempodeinactividadparacerrarautomáticamentelasesióndelusuario.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
40
![Page 41: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/41.jpg)
4. Gestión de datos de sesión
GestióndelasesiónenSpring• EnSpringexisteunaformademásaltonivelparaasociarinformaciónalusuario.
• Consisteencrearun@Componentespecialqueseasociaráacadausuarioyhacer@Autowire delmismoenelcontroladorqueseutilice.
• InternamenteSpringhacebastantemagiaparaquelainformaciónsegestionedeformaadecuada.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
41
![Page 42: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/42.jpg)
4. Gestión de datos de sesión
GestióndelasesiónenSpring• Ejemplo:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
42
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; @Component @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public class User { private String info; public void setInfo(String info) { this.info = info; } public String getInfo() { return info; } }
Laanotación@Scopeconestosvaloreshaceque
hayauncomponenteporcadausuario
![Page 43: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/43.jpg)
4. Gestión de datos de sesión
GestióndelasesiónenSpring• Ejemplo:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
43
@Controller public class SessionController2 { @Autowired private User user; private String sharedInfo; @RequestMapping(value = "/processForm") public ModelAndView processForm(@RequestParam String info) { user.setInfo(info); sharedInfo = info; return new ModelAndView("info_result"); } @RequestMapping("/showData") public ModelAndView showData(HttpSession sesion) { String userInfo = user.getInfo(); return new ModelAndView("data_page").addObject("userInfo", userInfo).addObject("sharedInfo", sharedInfo); } }
![Page 44: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/44.jpg)
4. Gestión de datos de sesión
ObjetoHttpSessionvssesiónSpring• Ambastécnicassepuedencombinar.
• ElobjetoHttpSessionseutilizaráparacontrolarelciclodevidadelasesión(siesnueva,invalidarla,etc…).
• Elcomponenteseusaráparagestionarlainformaciónasociadaalusuario.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
44
![Page 45: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/45.jpg)
Índice de contenidos
1. SpringMVC2. Thymeleaf3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
45
![Page 46: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/46.jpg)
5. Soporte de internacionalización (I18N) APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
46
welcome=Welcome to my web!
messages_en.properties
welcome=Bienvenido a mi web!
messages_es.properties
welcome=Bienvenue sur mon site web!
messages_fr.properties
![Page 47: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/47.jpg)
5. Soporte de internacionalización (I18N) APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
47
@SpringBootApplication public class SpringMvcI18nApp extends WebMvcConfigurerAdapter { @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH); return sessionLocaleResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor result = new LocaleChangeInterceptor(); result.setParamName("lang"); return result; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
SpringMvcI18nApp.java Nombre del fichero que contiene los mensajes de I18N
Región (locale) por defecto
Parámetro con el que cambiar la región desde URL
![Page 48: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/48.jpg)
5. Soporte de internacionalización (I18N) APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
48
package io.github.web.springmvc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class I18NController { @RequestMapping("/i18n") public ModelAndView i18n() { return new ModelAndView("i18n_page"); } }
I18NController.java
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <p th:text="#{welcome}">Default greetings</p> </body> </html>
i18n_page.html
El símbolo # hace que la plantilla se rellene con los datos de I18N
![Page 49: DISEÑO DE APLICACIONES WEB Bloque 3: Parte servidora ...laurel.datsi.fi.upm.es/_media/docencia/asignaturas/daw/daw-tema3.2.pdf · 1. Spring MVC Controladores • Los controladores](https://reader033.vdocuments.site/reader033/viewer/2022041910/5e671e3e2546aa16ca3d952b/html5/thumbnails/49.jpg)
5. Soporte de internacionalización (I18N) APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
49