PDA

View Full Version : [JAVA EE] Funzionamento Spring MVC


oNaSsIs
03-07-2011, 22:16
Ragazzi non riesco a capire il funzionamento dell'implementazione del pattern MVC utilizzando il framework Spring.
Quello che vorrei realizzare ora è molto semplice, creare una pagina web con un link, dove cliccando si passa ad un'altra pagina.
Io ho creato un Web Project con Netbeans specificando l'utilizzo del framework MVC Spring, di conseguenza lui mi ha generato automaticamente i seguenti file:
dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />

<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />

</beans>



applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!--bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" /-->

<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>



Io invece ho modificato il file index.html in questo modo:
index.html

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Welcome to Spring Web MVC project</title>
</head>

<body>

<a href="http://localhost:8080/TestPresentation/showApartmentsList.jsp?action=showApartmentsList">
Visualizza Appartamenti
</a>
</body>
</html>



e creato anche la view e il controller:
ApartmentController.java

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ApartmentController implements Controller{

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView("showApartmentsList.jsp");
}

}



showApartmentsList.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Lista Appartamenti</h1>
</body>
</html>

Ora credo che sia necessario modificare opportunamente il file dispatcher-servlet.xml, ma non so come, perchè non riesco ad interpretare correttamente il suo significato. Qualcuno potrebbe consigliarmi su come proseguire l'implementazione?

Mixmar
03-07-2011, 22:49
A occhio e croce, l'errore è qui:


<a href="http://localhost:8080/TestPresentation/showApartmentsList.jsp?action=showApartmentsList">
Visualizza Appartamenti
</a>


Non dovresti puntare il file jsp direttamente nel link, ma puntare all'URL "mappata" da Spring sul controller. Siccome hai configurato il ControllerClassNameHandlerMapping , e il controller si chiama ApartmentController, l'URL dovrebbe essere qualcosa come "apartmentController": questo dovrebbe "attivare" l'esecuzione del metodo doGet che ritorna la vista, cioè il file jsp.

Se posso permettermi un consiglio, non riferirti all'URL del controller in termini assoluti, ma in modo relativo, così:


<a href="showApartments">
Visualizza Appartamenti
</a>


Infatti, il riferimento al protocollo, all'host, alla porta e al contesto (TestPresentation) sono automatici: così avrai meno problemi quando farai il deployment in un'altra configurazione.

Btw, non devi indicare l'estenzione jsp della vista, è già specificato nell'dispatcher-servlet.xml; il codice diventerebbe così.


return new ModelAndView("showApartmentsList");

oNaSsIs
04-07-2011, 08:10
Allora, io ho corretto i file index.jsp e ApartmentController.java come da te suggerito. I codici risultanti sono i seguenti:
index.html

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Welcome to Spring Web MVC project</title>
</head>

<body>

<a href="showApartmentsList">
Visualizza Appartamenti
</a>

</body>
</html>



ApartmentController.java


package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ApartmentController implements Controller{

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView("showApartmentsList");
}

}



Il problema però persiste, perchè io ho come l'impressione che il controller non sia ancora registrato nel file di configurazione di Spring e quindi le richieste che arrivano non vengono gestite. Mi sbaglio?

oNaSsIs
04-07-2011, 09:58
Sono riuscito a risolvere il problema finalmente mappando le pagine nel dispatcher-servlet.xml e modificando la pagina index.jsp. Quello che segue è il codice funzionante, volevo chiedervi se è formalmente corretto:

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
<prop key="showApartmentsList.htm">apartmentController</prop>
<prop key="insertApartment.htm">apartmentController</prop>
<prop key="deleteApartment.htm">apartmentController</prop>
</props>
</property>
</bean>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />

<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />

<bean name="apartmentController" class="controller.ApartmentController"/>

</beans>


index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Homepage Amministratore</title>
</head>

<body>
<h1>Homepage Amministratore</h1>
<a href="showApartmentsList.htm?action=showApartmentsList">
Visualizza Appartamenti
</a>
<br>
<a href="insertApartment.htm?action=insertApartment">
Inserisci Appartamento
</a>
<br>
<a href="deleteApartment.htm?action=deleteApartment">
Cancella Appartamento
</a>

</body>
</html>


ApartmentController.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
*
* @author luca
*/
public class ApartmentController implements Controller{

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String actionName;

actionName = (String) request.getAttribute("action");
return new ModelAndView(actionName);
}

}

oNaSsIs
04-07-2011, 11:03
Ora che sono riuscito a procedere con lo sviluppo dell'applicazione ho un altro dubbio.
Il mio controller invoca un servizio che gli restituisce una lista di oggetti da me creati, e che il controller aggiunge al Model. Ma se io li aggiungo direttamente sono costretto ad aggiungere del codice Java all'interno della pagina JSP cosa che io vorrei evitare. Come potrei fare?