Bloque 3: Parte servidora (backend)
DISEÑODEAPLICACIONESWEB
TEMA3.2:APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
Disclaimer
• Estematerialestábasadoenunmaterialoriginalde:§ BoniGarcía([email protected])
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
2
Índice de contenidos
1. SpringMVC2. Thymeleaf3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
3
Índice de contenidos
1. SpringMVC§ Introducción
§ Controladores
§ Vistas
§ Ejemplo2. Thymeleaf3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
4
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
1. Spring MVC
Controladores• Loscontroladores(Controllers)sonclasesJavaencargadasdeatenderlaspeticionesweb.
• Procesanlosdatosquelleganenlapetición(parámetros).• Hacenpeticionesalabasededatos,usandiversosservicios,etc…
• Definenlainformaciónqueserávisualizadaenlapáginaweb(elmodelo).
• DeterminanquevistaserálaencargadadegenerarlapáginaHTML.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
6
1. Spring MVC
Vistas• LasvistasenSpringMVCseimplementancomoplantillasHTML.
• GeneranHTMLpartiendodeunaplantillaylainformaciónquevienedelcontrolador(modelo).
• ExistendiversastecnologíasdeplantillasquesepuedenusarconSpringMVC:JSP,Thymeleaf,FreeMarker,etc…
• NosotrosusaremosThymeleaf.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
7
1. Spring MVC
Ejemplo• EstructuradelaaplicaciónvistadesdeEclipse:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
8
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
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
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
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
Índice de contenidos
1. SpringMVC2. Thymeleaf
§ Introducción§ Ejemplo§ Manejandotexto§ Condicionales§ Iteraciones
3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
13
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/
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>
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
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()}
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)
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
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); } }
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
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
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
Índice de contenidos
1. SpringMVC2. Thymeleaf
3. Envíodeinformaciónalservidor§ Envíomedianteformulario
§ EnvíomedianteURL
§ URLsenThymeleaf4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
24
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
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); } }
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
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
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 }
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}
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
Í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
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
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
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
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"); }
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
4. Gestión de datos de sesión
ObjetoHttpSession • Ejemplo:
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
38
Guardalainformaciónenlaunatributodelasesiónyenunatributodelcontrolador
Recuperalainformacióndelasesión(usuario)ydelcontrolador(compartida)
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); } }
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
4. Gestión de datos de sesión
GestióndelasesiónenSpring• EnSpringexisteunaformademásaltonivelparaasociarinformaciónalusuario.
• Consisteencrearun@Componentespecialqueseasociaráacadausuarioyhacer@Autowire delmismoenelcontroladorqueseutilice.
• InternamenteSpringhacebastantemagiaparaquelainformaciónsegestionedeformaadecuada.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
41
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
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); } }
4. Gestión de datos de sesión
ObjetoHttpSessionvssesiónSpring• Ambastécnicassepuedencombinar.
• ElobjetoHttpSessionseutilizaráparacontrolarelciclodevidadelasesión(siesnueva,invalidarla,etc…).
• Elcomponenteseusaráparagestionarlainformaciónasociadaalusuario.
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
44
Índice de contenidos
1. SpringMVC2. Thymeleaf3. Envíodeinformaciónalservidor4. Gestióndedatosdesesión5. Soportedeinternacionalización(I18N)
APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
45
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
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
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
5. Soporte de internacionalización (I18N) APLICACIONESWEBCONSPRINGMVCYTHYMELEAF
49