Esempio di gestione dei moduli Spring MVC

L'esempio seguente mostra come scrivere una semplice applicazione basata sul Web, che utilizza moduli HTML utilizzando il framework Spring Web MVC. Per cominciare, disponiamo di un IDE Eclipse funzionante e intraprendiamo i seguenti passaggi per sviluppare un'applicazione Web dinamica basata su form utilizzando Spring Web Framework:

Passi Descrizione
1 Crea un progetto Web dinamico con un nome HelloWeb e crea un pacchetto com.tutorialspoint nella cartella src nel progetto creato.
2 Trascina e rilascia la molla indicata di seguito e altre librerie nella cartella WebContent / WEB-INF / lib .
3 Creare una classe Java Student e StudentController nel pacchetto com.tutorialspoint .
4 Crea i file di configurazione Spring Web.xml e HelloWeb-servlet.xml nella cartella WebContent / WEB-INF .
5 Crea una sottocartella con un nome jsp nella cartella WebContent / WEB-INF . Crea una visualizzazione dei file student.jsp e result.jsp in questa sottocartella.
6 Il passaggio finale consiste nel creare il contenuto di tutti i file sorgente e di configurazione ed esportare l'applicazione come spiegato di seguito.

Ecco il contenuto di Student.java file

package com.tutorialspoint;

public class Student {
   private Integer age;
   private String name;
   private Integer id;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

Di seguito è riportato il contenuto di StudentController.java file

package com.tutorialspoint;

import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import org.springframework.ui.ModelMap;

@Controller
public class StudentController {
   @RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "command", new Student());
   }
   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
      public String addStudent(@ModelAttribute("SpringWeb")Student student, 
   
   ModelMap model) {
      model.addAttribute("name", student.getName());
      model.addAttribute("age", student.getAge());
      model.addAttribute("id", student.getId());
      
      return "result";
   }
}

Ecco il primo metodo di servizio student(), abbiamo superato uno spazio vuoto Studentoggetto nell'oggetto ModelAndView con il nome "comando" perché il framework Spring si aspetta un oggetto con il nome "comando" se si utilizzano i tag <form: form> nel file JSP. Cosi quandostudent() metodo viene chiamato, ritorna student.jsp Visualizza.

Il secondo metodo di servizio addStudent() verrà chiamato contro un metodo POST su HelloWeb/addStudentURL. Preparerai il tuo oggetto modello in base alle informazioni inviate. Infine verrà restituita una vista "risultato" dal metodo del servizio, che risulterà nel rendering di result.jsp

Di seguito è riportato il contenuto del file di configurazione di Spring Web web.xml

<web-app id = "WebApp_ID" version = "2.4"
   xmlns = "http://java.sun.com/xml/ns/j2ee" 
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
   <display-name>Spring MVC Form Handling</display-name>
 
   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
 
</web-app>

Di seguito è riportato il contenuto di un altro file di configurazione Spring Web HelloWeb-servlet.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package = "com.tutorialspoint" />

   <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name = "prefix" value = "/WEB-INF/jsp/" />
      <property name = "suffix" value = ".jsp" />
   </bean>
 
</beans>

Di seguito è riportato il contenuto del file di visualizzazione Spring student.jsp

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>

   <body>
      <h2>Student Information</h2>
      <form:form method = "POST" action = "/HelloWeb/addStudent">
         <table>
            <tr>
               <td><form:label path = "name">Name</form:label></td>
               <td><form:input path = "name" /></td>
            </tr>
            <tr>
               <td><form:label path = "age">Age</form:label></td>
               <td><form:input path = "age" /></td>
            </tr>
            <tr>
               <td><form:label path = "id">id</form:label></td>
               <td><form:input path = "id" /></td>
            </tr>
            <tr>
               <td colspan = "2">
                  <input type = "submit" value = "Submit"/>
               </td>
            </tr>
         </table>  
      </form:form>
   </body>
   
</html>

Di seguito è riportato il contenuto del file di visualizzazione Spring result.jsp

<%@page contentType = "text/html;charset = UTF-8" language = "java" %>
<%@page isELIgnored = "false" %>
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>

   <body>
      <h2>Submitted Student Information</h2>
      <table>
         <tr>
            <td>Name</td>
            <td>${name}</td>
         </tr>
         <tr>
            <td>Age</td>
            <td>${age}</td>
         </tr>
         <tr>
            <td>ID</td>
            <td>${id}</td>
         </tr>
      </table>  
   </body>
   
</html>

Infine, di seguito è riportato l'elenco di Spring e di altre librerie da includere nella tua applicazione web. Devi semplicemente trascinare questi file e rilasciarliWebContent/WEB-INF/lib cartella.

  • commons-logging-x.y.z.jar
  • org.springframework.asm-x.y.z.jar
  • org.springframework.beans-x.y.z.jar
  • org.springframework.context-x.y.z.jar
  • org.springframework.core-x.y.z.jar
  • org.springframework.expression-x.y.z.jar
  • org.springframework.web.servlet-x.y.z.jar
  • org.springframework.web-x.y.z.jar
  • spring-web.jar

Una volta terminata la creazione dei file sorgente e di configurazione, esporta l'applicazione. Fare clic con il pulsante destro del mouse sulla propria applicazione e utilizzare il fileExport > WAR File opzione e salva il tuo SpringWeb.warfile nella cartella webapps di Tomcat .

Ora avvia il tuo server Tomcat e assicurati di essere in grado di accedere ad altre pagine web dalla cartella webapps utilizzando un browser standard. Ora prova un URLhttp://localhost:8080/SpringWeb/student e dovresti vedere il seguente risultato se tutto va bene con la tua applicazione Web Spring.

Dopo aver inviato le informazioni richieste, fare clic sul pulsante Invia per inviare il modulo. Dovresti vedere il seguente risultato se tutto va bene con la tua applicazione Web Spring.