Primavera MVC – Azulejos

Spring proporciona funcionalidad para la integración con el marco Apache Tiles. Con la ayuda de Spring Tiles, podemos administrar fácilmente el diseño de la aplicación Spring MVC.

Beneficios de la compatibilidad con Tiles de Spring MVC:

Los siguientes son algunos de los principales beneficios de Spring MVC Tiles 3 Integration:

  • Reutilización: un solo componente, como el encabezado y el pie de página, se puede reutilizar en varias páginas.
  • Control centralizado: Podemos controlar el diseño de la página desde una única página de plantilla.
  • Modifique el diseño fácilmente: podemos cambiar el diseño de la página en cualquier momento usando una sola página de plantilla. Como resultado, las nuevas tecnologías como bootstrap, jQuery y otras pueden integrarse fácilmente en su sitio web.

Proyecto de ejemplo

Estructura del proyecto:

Project structure

Vamos a crear un ejemplo de trabajo con el IDE de Eclipse, que incluirá los siguientes pasos:

  1. Cree un proyecto llamado SpringEx con el paquete com.geeksforgeeks. Esto debería estar en la carpeta src de su proyecto recién formado.
  2. Con las opciones Agregar JAR externos, agregue las bibliotecas Spring que se requieren.
  3. Con index.jsp, puede crear una página de índice.
  4. Cree HelloWorldController.java, ContactController.java y Contact.java en el paquete creado anteriormente.
  5. En la carpeta src, cree los archivos de configuración web.xml, tile.xml y spring-servlet.xml.
  6. Cree todo el código de los componentes de View.
  7. Finalmente, escriba el código para todos los archivos Java y el archivo de configuración de Bean, luego ejecute la aplicación como se indica.

Paso 1: actualice el archivo pom.xml para incluir dependencias

pom.xml

Puede descargar las dependencias requeridas de las URL proporcionadas en los comentarios del programa.

XML

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javatpoint</groupId>
  <artifactId>SpringMVCTiles</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCTiles Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
      
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.1.RELEASE</version>
    </dependency>
      
      <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>  
        <groupId>javax.servlet</groupId>  
        <artifactId>servlet-api</artifactId>  
        <version>3.0-alpha-1</version>  
    </dependency>
      
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
      
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper</artifactId>
        <version>9.0.12</version>
  </dependency>
      
   <!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-jsp -->
  <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-jsp</artifactId>
        <version>3.0.5</version>
  </dependency>
      
    <!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-servlet -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-servlet</artifactId>
        <version>3.0.5</version>
    </dependency>
      
    <!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-core -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-core</artifactId>
        <version>3.0.5</version>
    </dependency>
      
    <!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-el -->
    <dependency>
        <groupId>org.apache.tiles</groupId>
        <artifactId>tiles-el</artifactId>
        <version>3.0.5</version>
    </dependency>
      
  </dependencies>
  <build>
    <finalName>SpringMVCTiles</finalName>
  </build>
</project>

Paso 2: Crear la clase de bean

Contacto.java

Java

package com.geeksforgeeks.form;
public class Contact {
    
    private String firstname;
    private String lastname;
    private String email;
    private String telephone;
      
    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

Paso 3. Crea la clase de controlador

HolaMundo.java

Java

package com.geeksforgeeks.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
  
@Controller
public class HelloWorld 
{
    @RequestMapping("/hello")
    public String helloWorld(Model m) 
    {
        String message = "Hello geeksforgeeks";
        m.addAttribute("message", message);
        return "hello"; 
    }
}

ContactController.java

Java

package com.geeksforgeeks.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.geeksforgeeks.form.Contact;
  
@Controller
@SessionAttributes
public class ContactController 
{
    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")    Contact contact, BindingResult result) 
    {
        // write the code here to add contact
        return "redirect:contact.html";
    }
      
    @RequestMapping("/contact")
    public String showContacts(Model m) 
    {
        m.addAttribute("command", new Contact());
        return "contact";
    }
}

Paso 4. Proporcione una entrada de controlador en el archivo web.xml

web.xml

XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <display-name>SpringTiles</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

Paso 5. Crea la página solicitada

índice.jsp

HTML

<a href="hello.html">Hello geeksforgeeks </a>  | 
<a href="contact.html">Contact us page</a>

Paso 6. Cree los otros componentes de la vista

hola.jsp

HTML

<html>
<head>
    <title>Spring MVC Example</title>
</head>
<body>
    <h1>Welcome to GeeksForGeeks</h1>
</body>
</html>

contacto.jsp

HTML

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring Tiles Contact Form</title>
</head>
<body>
<center>
<h1> GFG Contact Manager</h1>
<form:form method="post" action="addContact.html">
  
    <table>
    <tr>
        <td><form:label path="firstname">Enter your firstname</form:label></td>
        <td><form:input path="firstname" /></td> 
    </tr>
    <tr>
        <td><form:label path="lastname">Enter your lastname</form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Enter your email</form:label></td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Enter your mobile.no</form:label></td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>    
      
</form:form>
</center>
</body>
</html>

encabezado.jsp

HTML

<h2>GEEEKSFORGEEKS</h2>
<hr/>

pie de página.jsp

HTML

<hr/>
  
<p>Thank you for visiting this site</p>

menú.jsp

HTML

<p>Menu 1</p>
  
  
<p>Menu 2</p>

diseño.jsp

HTML

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
</head>
<body>
        <div><tiles:insertAttribute name="header" /></div>
        <div style="float:left;padding:10px;width:15%;"><tiles:insertAttribute name="menu" /></div>
        <div style="float:left;padding:10px;width:80%;border-left:3px solid black;">
        <tiles:insertAttribute name="body" /></div>
        <div style="clear:both"><tiles:insertAttribute name="footer" /></div>
  
</body>
</html>

Producción:

Después de hacer clic en el enlace «Hola geeksforgeeks», se mostrará la siguiente página

Output

Y después de hacer clic en contáctenos, se mostrará esta página

Output

Publicación traducida automáticamente

Artículo escrito por sanketnagare y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *