Spring3 MVC - 3到Spring MVC框架簡介
Spring3 MVC框架簡介
Spring MVC是Spring的框架的Web組件。 它提供了豐富的功能,為建設強大的Web應用程序。 Spring MVC框架的架構,並在這樣的高度可配置的方式,每一塊的邏輯和功能設計。 此外Spring可以毫不費力地與其他流行的Web框架,如Struts,WebWork的,的Java Server Faces和Tapestry集成。 這意味着,你甚至可以告訴Spring使用Web框架中的任何一個。 比Spring更不緊耦合的servlet或JSP向客戶端呈現視圖。 喜歡速度與其他視圖技術集成,Freemarker的,Excel或PDF現在也有可能。
Spring3.0 MVC系列
- 第1部分:到Spring 3.0 MVC框架簡介
- 第2部分:在Spring 3.0 MVC創建Hello World應用程序
- 第3部分:在Spring 3.0 MVC的形式處理
- 第4部分:Spring3 MVC的Tiles Support與Eclipse中的例子插件教程
- 第5部分:Spring3 MVC的國際化及本地化教程與范例在 Eclipse
- 第6部分:Spring3 MVC示例教程Spring主題
- 第7部分:創建Spring3 MVC Hibernate 3的示例在Eclipse中使用Maven的
在Spring Web MVC,你可以使用任何對象作為命令或表單支持對象,你不需要實現框架特定的接口或基類。 Spring的數據綁定是高度靈活的:例如,將驗證錯誤類型不作為應用系統錯誤,可以通過評估的不匹配。 因此,你不必重復你的業務對象的屬性,簡單的無類型的字符串,在表單對象僅僅是為了處理無效的意見,或正確轉換的字符串。 相反,它往往是最好直接綁定到業務對象。
請求處理生命周期
Spring的Web MVC框架是,像許多其他Web MVC框架,要求為導向,圍繞一個中心的servlet,它把請求分派給控制器,提供其他功能,有利於開發Web應用而設計的。 Spring DispatcherServlet DispatcherServlet是Spring IoC容器完全集成,並允許我們使用的每一個Spring的其他功能。
以下是Spring3.0 MVC請求流程的生命周期:
客戶端將請求發送到Web容器中的HTTP請求的形式。
這個傳入的請求被截獲由前端控制器 (DispatcherServlet的),然后它會試圖找出相應的處理程序映射 。
幫助處理程序映射,DispatcherServlet將請求派遣適當的控制器。
控制器嘗試處理請求和ModelAndView實例的形式返回到前端控制器模型和視圖對象。
前端控制器,然后試圖解決咨詢視圖解析器對象的視圖(可以是JSP,FreeMarker的,速度等) 。
選定的視圖,然后返回到客戶端呈現。
Spring3.0的特點
- Spring3.0框架支持Java 5。 它提供了注釋的配置支持。 Java 5的功能,例如泛型,注解,可以使用可變參數等在Spring。
- 正在引進一種新的表達語言The Spring 的表達語言規划環境地政局局長。 Spring的表達式語言可以使用,同時定義了基於XML和注釋的bean定義。
- Spring3.0框架支持REST Web服務。
- 數據格式可從來沒有那么容易。 Spring 3.0支持了注釋的格式。 現在,我們可以使用@ DateFimeFormat(ISO = ISO.DATE)和@NumberFormat(Style= Spring.CURRENCY)標注日期和貨幣格式轉換。
- Spring3.0已經開始支持JPA 2.0的。
配置Spring 3.0的MVC
切入點的Spring 3.0 MVC DispatcherServlet 。 DispatcherServlet的是正常的servlet的類,它HttpServlet HttpServlet的的基類。 因此,我們需要在它web.xml配置。
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
在上面的代碼片斷中,我們必須在web.xml中配置DispatcherServlet的。 請注意,我們已經映射*. HTML URL模式,例如DispatcherServlet的。 因此,任何與*. HTML模式的URL將調用Spring MVC的前端控制器。
一旦DispatcherServlet的初始化,它會查找一個文件名[servlet-name]-servlet.xml Web應用程序的WEB - INF文件夾中。 在上面的例子中,將尋找所謂example-servlet.xml servlet.xml的框架。
請注意上面的架構圖。 WebApplicationContext上圖中指定ApplicationContext平原擴展Web應用程序所需的一些額外的功能。 在WebApplicationContext是能夠解決的主題,它也與相應的servlet相關。 在WebApplicationContext在ServletContext中的約束,並通過對RequestContextUtils類的靜態方法,您可以隨時查找在WebApplicationContext。
現在,我們有關的Spring 3.0 MVC框架,其生命周期架構的想法, 在接下來的部分中,我們將創建一個工作Spring3.0的 Hello World應用程序從頭。
Spring3 MVC:在Spring 3.0 MVC創建Hello World應用程序
Spring3.0 MVC系列的第2部分。 在以前的文章中,我們經歷介紹的Spring MVC 3.0框架,其請求處理生命周期和體系結構圖。 在這篇文章中,讓我們在Spring MVC 3.0創建一個簡單的的Hello World應用程序。
對於創建的Hello World演示應用程序,我們將使用Eclipse IDE中。
我們需要的東西
之前,我們與我們的第一個Hello World Struts 2的示例開始,我們將需要一些工具。
- JDK 1.5以上( 下載 )
- 以上的Tomcat 5.x的或任何其他容器(Glassfish的中,WebSphere,JBoss的,在Weblogic等)( 下載 )
- Eclipse的3.2.x中,它上面的( 下載 )
-
Spring3.0 MVC JAR文件:( 下載 )。 以下是此應用程序所需的JAR文件的清單。
- commons-logging-1.0.4.jar
- jstl-1.2.jar
- org.springframework.asm - 3.0.1.RELEASE - A.jar
- org.springframework.beans - 3.0.1.RELEASE - A.jar
- org.springframework.context - 3.0.1.RELEASE - A.jar
- org.springframework.core - 3.0.1.RELEASE - A.jar
- org.springframework.expression - 3.0.1.RELEASE - A.jar
- org.springframework.web.servlet - 3.0.1.RELEASE - A.jar
- org.springframework.web - 3.0.1.RELEASE - A.jar
請注意,根據Spring MVC的當前版本,上述jar文件的版本號可能會改變。
我們的目標
我們的目標是創建一個基本的Spring MVC應用中使用最新的3.0版本。 將會有一個索引頁,它會顯示一個鏈接"打招呼"給用戶。 點擊此鏈接,用戶將被重定向到另一頁打招呼 ,它會顯示一條消息的"Hello World,Spring3.0!"。
入門
讓我們開始我們的第一個Spring3.0基於MVC的應用程序。
打開Eclipse轉到文件- >新建- >項目,然后選擇動態Web項目中的新建項目向導屏幕。
選擇動態Web項目后,按" 下一步"" 。
寫項目名稱。 例如Spring3MVC。 一旦做到這一點,選擇目標運行時環境(如Apache Tomcat的V6.0)。 這是在Eclipse環境中運行的項目。 在此之后按下Finish。
一旦該項目被創建,您可以在Project Explorer中看到它的結構。
現在的WebContent所有所需的JAR文件>的WEB - INF> lib文件夾中復制。 創建此文件夾,如果它不存在。
Spring控制器類
我們需要一個Spring MVC控制器類,將處理該請求,並顯示"Hello World"消息。 為此,我們將創建一個包net.viralpatel.spring3.controller的源文件夾中。 這個包將包含控制器文件。
創建一個類叫做HelloWorldController net.viralpatel.spring3.controller包並復制到它下面的內容。
文件:net.viralpatel.spring3.controller.HelloWorldController
package net.viralpatel.spring3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "Hello World, Spring 3.0!";
return new ModelAndView("hello", "message", message);
}
}
請注意,我們已經注明HelloWorldController類7行 @Controller和10行@RequestMapping("/hello") 當Spring掃描我們的包,將其識別為一個處理請求的控制器bean這個bean。 @RequestMapping注解告訴Spring,這個控制器應該處理所有請求/ URL路徑打招呼開始。 這包括/hello/*和/hello.html 。
在HelloWorld()方法返回ModelAndView對象。 ModelAndView對象,試圖解決一個名為"Hello"和數據模型是被傳遞回瀏覽器,所以我們可以在JSP訪問數據視圖。 邏輯視圖名稱解析為"/WEB-INF/jsp/hello.jsp" 我們將討論這在短期內如何的"Hello",這是在ModelAndView對象返回的邏輯名稱映射到路徑/ WEB-INF/jsp/hello.jsp。
ModelAndView對象還包含了一個關鍵的"消息"和價值的"Hello World,Spring3.0!"的消息。 這是數據,我們通過我們的觀點。 通常情況下,這將是一個價值形式的Java bean將包含要顯示的數據我們認為對象。 在這里,我們只是傳遞一個字符串。
這樣的觀點:創建JSP
要顯示Hello World消息,我們將創建一個JSP。 請注意,這個JSP是創建文件夾/ WEB-INF/jsp。 創建hello.jsp下WEB-INF/jsp目錄,並復制以下內容進去。
文件:WEB-INF/jsp/hello.jsp
<html>
<head>
<title>Spring 3.0 MVC Series: Hello World - ViralPatel.net</title>
</head>
<body>
${message}
</body>
</html>
上面的JSP只顯示一條消息,使用表達式${message} 。 請注意," message"的名稱,我們在設置一個消息字符串ModelAndView對象。
同時,我們也將需要一個index.jsp文件,這將是我們的應用程序的入口點。 創建一個WebContent文件夾下的文件在您的項目並復制以下內容的index.jsp。
文件的WebContent / index.jsp的
<html>
<head>
<title>Spring 3.0 MVC Series: Index - ViralPatel.net</title>
</head>
<body>
<a href="hello.html">Say Hello</a>
</body>
</html>
Spring MVC的映射Web.xml中
正如在以前的文章(Spring3.0 MVC)討論,Spring MVC應用的切入點將是在部署描述符(web.xml)中定義的Servlet。 因此,我們將定義在web.xml中的一個條目org.springframework.web.servlet.DispatcherServlet org.springframework.web.servlet.DispatcherServlet類。
打開web.xml文件,該文件是在WEB - INF文件夾,並復制粘貼下面的代碼。
文件:WEB-INF/web.xml中
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</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>
上面的代碼將在web.xml中映射URL模式*. HTML的DispatcherServlet。 另外請注意,我們已經定義作為歡迎文件的index.jsp。
這里有一點要注意<servlet-name>標簽在web.xml中的servlet的名稱。 DispatcherServlet的初始化后,它會查找一個文件名[servlet-name]-servlet.xml Web應用程序的WEB - INF文件夾中。 在這個例子中,該框架將稱為文件spring-servlet.xml尋找。
Spring配置文件
The Spring - servlet.xml中創建一個文件在WEB - INF文件夾,並復制到它下面的內容。
文件:WEB-INF/spring-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:context="http://www.springframework.org/schema/context"
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="net.viralpatel.spring3.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
在上面的XML配置文件,我們已經定義了一個標記<context:component-scan>。 這將允許Spring載入net.viralpatel.spring3.controller從包中的所有組件和它的所有子包。 這將載入我們HelloWorldController類。 另外,我們定義一個bean viewResolver 。 這個bean將解決意見,並添加前綴字符串/ WEB-INF/jsp /以及后綴。JSP在ModelAndView的觀點。 請注意,我們已經在我們的HelloWorldController類,返回一個ModelAndView對象的視圖名稱的"Hello"。 這將是解決路徑/ WEB-INF/jsp/hello.jsp。
這是所有Folks
您可能需要運行的應用程序現在看到的結果。 我假設你已經在Eclipse中配置Tomcat的。 所有您需要做的:
從"窗口">"顯示視圖">"服務器打開服務器視圖。 在此視圖中右鍵單擊並選擇New> Server,並添加您的服務器的詳細信息。
要運行該項目,從Project Explorer中的項目名稱上點擊右鍵並選擇>運行在服務器上運行(快捷鍵:ALT + SHIFT + X,R )
下載源代碼
在本教程中,我們創建了一個小型的Hello World應用程序,使用Spring 3.0 MVC框架。 此外,我們了解了Spring的配置和喜歡不同@Controller @RequestMapping RequestMapping的。 在下一篇文章中,我們將看到它是多么容易使用Spring 3.0的MVC來處理表單數據。
Spring3 MVC:在Spring 3.0 MVC的處理形式
Spring3.0 MVC系列的第3部分。 在以前的文章中,我們創建了一個在Spring MVC的Hello World應用程序。 我們俯身如何在web.xml中配置Spring MVC中,如何使用不同的注釋,如@控制器,@ RequestMapping的等在這篇文章中,讓我們來看看如何處理在Spring 3.0 MVC的形式。
我們將利用我們在以前的文章中創建一個基本參考,並添加在它的形式的功能框架。 另外,我們創建的應用程序將是一個聯系人管理器應用程序。
我們的目標
我們的目標是創建基本的聯系人管理器應用程序。 這個應用程序將有一個表格,從用戶的詳細聯系方式。 現在我們將只打印在日志中的細節。 我們將學習如何捕捉在Spring3 MVC的表單數據。
入門
讓我們添加的接觸形式,以Spring3 MVC Hello World應用程序。 打開index.jsp文件,並改變它,以下列:
文件的WebContent / index.jsp的
<jsp:forward page="contacts.html"></jsp:forward>
上面的代碼將重定向用戶contacts.html頁。
查看- contact.jsp
創建一個JSP文件,將顯示聯系表格給我們的用戶。
文件:/的WebContent / WEB - INF / JSP / contact.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="lastname">Telephone</form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
在這里,我們在上面的JSP顯示的形式。 請注意的形式提交給 addContact.html頁。
在Spring3添加的表格和控制器
現在我們將添加在The Spring 3的邏輯顯示的形式,並獲取它的值。 為此,我們將創建兩個Java文件。 首先Contact.java這只不過是形式顯示/檢索從屏幕上的數據和ContactController.java ContactController.java這是Spring的控制器類。
文件:net.viralpatel.spring3.form.Contact
package net.viralpatel.spring3.form;
public class Contact {
private String firstname;
private String lastname;
private String email;
private String telephone;
//.. getter and setter for all above fields.
}
上述文件是從屏幕上的數據的接觸形式持有。 請注意,我沒有表現出getter和setter方法。 您可以按ALT + SHIFT + S,R pressiong這些方法產生。
文件:net.viralpatel.spring3.controller.ContactController
package net.viralpatel.spring3.controller;
import net.viralpatel.spring3.form.Contact;
import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;
@Controller
@SessionAttributes
public class ContactController {
@RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(@ModelAttribute("contact")
Contact contact, BindingResult result) {
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "redirect:contacts.html";
}
@RequestMapping("/contacts")
public ModelAndView showContacts() {
return new ModelAndView("contact", "command", new Contact());
}
}
在上面的控制器類,請注意,我們已經創建了兩個請求映射/聯系人/ addContact的方法。 方法showContacts()時將調用用戶對一個URL contacts.html的請求。 這種方法將呈現一個模型,名為"command"。 請注意ModelAndView ModelAndView對象,我們已經通過一個名為"命令"空白的聯系對象。 Spring框架預計name命令的對象,如果您使用在你的JSP文件。
另外請注意, addContact()方法,我們有注明此RequestMapping的,並通過一個屬性的方法="RequestMethod.POST" 。 因此,該方法將被調用,只有當用戶生成一個POST方法請求URL / addContact.html。 我們已經注明@ModelAttribute與標注的參數聯系。 這將結合從請求對象聯系的數據。 在此方法中,我們只印的名字和姓氏值和重定向的視圖cotnacts.html。
這是所有Folks
現在的形式完成。 只要運行在Eclipse應用程序由pression ALT + SHIFT + X,R。它將顯示的聯系表格。 只需輸入視圖的值,然后按添加按鈕。 一旦你按下按鈕,它會打印SYSOUT日志的名字和姓氏。
下載源代碼
在這篇文章中,我們將學習如何創建一個表單,使用The Spring 3 MVC,並顯示在JSP。 此外,我們學會了如何檢索使用ModelAttribute注解的形式值。 在下一節 ,我們將通過在Spring3 MVC的表單驗證和不同的數據轉換方法。
Spring 3 MVC: Tiles Plugin Tutorial with Example in Eclipse
Spring3.0 MVC系列的第4部分。 在以前的文章中,我們看到了如何創建使用Spring MVC的表單,並顯示在JSP。 同時,我們也了解注解@ModelAttribute 。
在這一部分,我們將討論關於Tiles框架和它與Spring 3.0 MVC的集成。 我們將添加Tiles Support支持我們的HelloWorld Spring應用程序,我們在前面部分中創建的。 我強烈建議你去通過以前的文章中和下載我們的示例應用程序的源代碼。
Tiles Support2
如今,網站一般分為可重復使用的模板正在呈現不同的網頁之間的的。 例如,一個網站中包含的頁眉,頁腳,菜單等項目仍然通過了該網站相同,並給它一個共同的外觀和感覺。 這是很難很難的代碼在每一個網頁,如果以后需要改變是不是所有的頁面需要修改。 因此,我們使用模板化機制。 我們創建一個共同的頁眉,頁腳,菜單頁,其中包括在每一頁。
Tiles Support插件允許模板和組件。 事實上,這兩種機制是相似的:你定義頁面的某些部分(a "Tile")組裝建立另一部分或整頁。 A部分參數,使動態內容,並且可以在Java語言中的一種方法。 Tiles是用來保持一致的外觀和感覺整個Web應用程序的所有網頁模板系統。 增加模板的可重用性和減少代碼重復。
是指在一個中央配置文件的網站的一個共同的布局,這種布局可以延長Web應用程序的所有網頁。
我們的應用程序布局
我們的目標是我們的Spring3 HelloWorld應用程序添加頁眉,頁腳和菜單。 以下將是相同的布局。
所需的jar文件
為了增加Tiles Support到我們Spring3的應用程序的支持,我們將需要幾個jar文件。 以下是在我們的例子中的JAR名單。 在WEB-INF/lib文件夾中添加這些JAR。
在上面的列表中突出顯示的jar文件要在Tiles Support一體化項目增添了新的罐子。
在Spring MVC的配置Tiles框架
要配置Tiles,an entry for bean TilesConfigure has to be made in spring-servlet.xml。 打開WEB - INF文件夾的Spring- servlet.xml中之 間添加以下代碼<beans> </beans>標記。
文件:/的WebContent / WEB - INF /Spring- servlet.xml中
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
輸入配置文件/ WEB-INF/tiles.xml是通過在上面的bean定義的參數。 這個文件包含了我們的Web應用程序的Tiles定義。
在WEB - INF文件夾,復制下面的代碼創建的文件tiles.xml。
文件:的WebContent / WEB - INF文件/ tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="base.definition"
template="/WEB-INF/jsp/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/jsp/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/jsp/menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/jsp/footer.jsp" />
</definition>
<definition name="contact" extends="base.definition">
<put-attribute name="title" value="Contact Manager" />
<put-attribute name="body" value="/WEB-INF/jsp/contact.jsp" />
</definition>
</tiles-definitions>
這里,tiles.xml我們定義一個模板base.definition。 此布局包含的頭,標題,身體,菜單和頁腳等屬性。 布局是那么的聯系頁面的擴展和新的定義。 我們已經覆蓋默認的布局,並改變了機構和標題的內容。
創建視圖 - JSP
我們將定義為我們的web應用在所謂的layout.jsp一個JSP文件的模板。 此模板將包含網頁的不同部分(頁眉,頁腳,菜單等)。 創建4個新的JSP文件layout.jsp,header.jsp中,menu.jsp和footer.jsp和復制以下內容在他們每個人。
文件的WebContent / WEB - INF / JSP / layout.jsp
<%@ 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>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="30" colspan="2"><tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td height="250"><tiles:insertAttribute name="menu" /></td>
<td width="350"><tiles:insertAttribute name="body" /></td>
</tr>
<tr>
<td height="30" colspan="2"><tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>
文件的WebContent / WEB - INF / JSP / header.jsp中
<h1>Header</h1>
文件的WebContent / WEB - INF / JSP / menu.jsp
<p>Menu</p>
文件的WebContent / WEB - INF / JSP / footer.jsp
<p>Copyright © ViralPatel.net</p>
這是所有Folks
在Eclipse中編譯和執行應用程序和看到的標題,菜單和頁腳是正確運用。
下載源代碼
今天,我們看到了我們如何使用Spring MVC應用程序配置Tiles框架。 我們在bean定義中使用org.springframework.web.servlet.view.tiles2.TilesConfigurer類"定義的Tiles Support配置文件。 在接下來的部分我們將討論有關國際化/本地化和增加其在Spring3 MVC的支持。 我希望你喜歡這篇文章。 隨意張貼您的查詢,並在注釋部分的意見。
Spring3 MVC:國際化和本地化教程示例
Spring3.0 MVC系列的第5部分。 在以前的文章中,我們看到了如何使用Spring MVC應用程序配置Tiles框架。 我們使用org.springframework.web.servlet.view.tiles2.TilesConfigurer bean定義的類定義Tiles Support的配置文件。 這個分裂我們的HelloWorld Spring MVC的應用部分,如頁眉,頁腳等。
在這一部分,我們將討論有關國際化(I18N)和本地化(L10N)的在Spring 3.0 MVC。 我們將添加L10N我們的HelloWorld Spring應用程序,我們在本系列前面的教程中創建的i18n支持。 我強烈建議你去通過以前的文章中和下載我們的示例應用程序的源代碼。
什么是國際化和本地化?
在計算,國際化和本地化是計算機軟件,以適應不同的語言和地區差異的手段。 國際化是設計的軟件應用程序,以便它可以適應在沒有更改設計的情況下,以各種語言和地區的過程中。 本地化是適應一個特定的地區或語言的國際化軟件加入區域設置特定的組件和翻譯文本的過程。
這兩個術語經常縮寫為numeronyms I18N(其中18代表字母之間的第一次我在國際化的最后n)和本地化,由於長度的話。 L10N資本大號幫助,以區別於小寫我在I18N。
我們的目標
我們的目標是到我們的Spring MVC應用添加國際化和本地化支持。 一旦完成,我們的應用程序看起來像。
我們將添加兩個我們的應用程序語言支持:英語和德語。 根據用戶的瀏覽器的區域設置,將選擇適當的語言。 此外,用戶將可以選擇從右上角角落里的應用程序的語言。
消息Resouces文件
我們將創建兩個屬性的文件,其中將包含所有要在應用程序中顯示的消息。 這些文件都保存在所謂的"資源"源文件夾。 創建一個在您的項目的源文件夾,右鍵單擊項目名稱>"新建">"源文件夾和名稱資源。
創建兩個文件messages_en.properties和messages_de.properties在此文件夾,並復制到它下面的內容。
文件:資源/ messages_en.properties
label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.addcontact=Add Contact
label.menu=Menu
label.title=Contact Manager
label.footer=© ViralPatel.net
文件:資源/ messages_de.properties
label.firstname=Vorname
label.lastname=Familiename
label.email=Email
label.telephone=Telefon
label.addcontact=Addieren Kontakt
label.title=Kontakt Manager
label.menu=Menü
label.footer=© ViralPatel.net
在Spring MVC的配置國際化(i18n)/本地化(localization)
現在,我們已經創建了信息資源的屬性,為我們的應用程序。 我們需要在Spring配置文件中聲明這些文件。 我們將使用類org.springframework.context.support.ReloadableResourceBundleMessageSource定義消息資源。
此外,請注意,我們將為您提供一個功能,用戶將能夠選擇應用程序的語言。 這是通過使用org.springframework.web.servlet.i18n.LocaleChangeInterceptor類。 LocaleChangeInterceptor類將截獲的語言環境中的任何變化。 這些變化,然后將其保存在未來要求的Cookie org.springframework.web.servlet.i18n.CookieLocaleResolver org.springframework.web.servlet.i18n.CookieLocaleResolver類將被用來存儲在cookie中的語言環境的變化。
Spring- servlet.xml文件中添加下面的代碼。
文件:的WebContent / WEB - INF文件/The Spring - servlet.xml中
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</property>
</bean>
注意:在上述配置中,我們已經定義到CLASSPATH messageSource bean 基名屬性:消息。 受此影響,Spring,將確定的消息資源訊息: 將被用於這個應用程序。
更改視圖 - 的JSP
現在,因為我們已經創建了兩個消息資源文件和配置在Spring MVC,我們將在JSP文件中使用這些消息。 打開我們的演示應用程序的所有JSP文件,下面的代碼更新。
文件的WebContent / WEB - INF / JSP / header.jsp中
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<h3><spring:message code="label.title"/></h3>
<span style="float: right">
<a href="?lang=en">en</a>
|
<a href="?lang=de">de</a>
</span>
文件的WebContent / WEB - INF / JSP / menu.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<p><spring:message code="label.menu"/></p>
文件的WebContent / WEB - INF / JSP / footer.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<spring:message code="label.footer"/>
文件的WebContent / WEB - INF / JSP / contact.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="lastname"><spring:message code="label.email"/></form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="lastname"><spring:message code="label.telephone"/></form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message code="label.addcontact"/>"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
請注意,在上面的JSP中,我們<spring:message> <spring:message>標簽來顯示從資源包的消息。
這里,我們必須注意的一件事情是,在header.jsp中的文件,我們已經指定了兩個環節,選擇語言。 LANG =鏈接設置請求參數? 當用戶點擊這個鏈接。 注意,Spring標識使用此請求參數LocaleChangeInterceptor攔截和相應改變的地方。 另外請注意,在配置LocaleChangeInterceptorThe Spring - servlet.xml文件中,我們已經指定為"lang" property " paramName"
<property name="paramName" value="lang" />
因此Spring框架將尋找所謂的"郎"從請求參數。
這是所有Folks
這是相當多:)我們只是增加了國際化和本地化支持,我們的演示Spring 3.0 MVC應用程序中。 所有你所要做的的僅僅是執行在Eclipse的應用程序。 按Alt + Shift + X,R。
下載源代碼
今天,我們看到如何添加到Spring 3.0基於Web應用程序國際化的國際化和本地化本地化支持。 我們使用LocaleChangeInterceptor攔截的語言環境和ReloadableResourceBundleMessageSource類添加消息資源屬性的變化。 在接下來的部分我們將討論在Spring MVC,以及如何實現它的主題。 我希望你喜歡這篇文章。 隨意張貼您的查詢,並在注釋部分的意見。
Spring3例Spring教程MVC:主題
Spring3.0 MVC系列的第6部。 在以前的文章中,我們看到了如何添加到Spring 3.0基於Web應用程序國際化的國際化和本地化本地化支持。 我們使用LocaleChangeInterceptor攔截的語言環境和ReloadableResourceBundleMessageSource類添加消息資源屬性的變化。
在這一部分,我們將看到如何在Spring MVC中添加主題。 我們將創建三個不同的主題,並在我們的HelloWorldSpring項目中添加功能,用戶可以選擇任何可用的主題。 一旦用戶選擇了一個主題,我們可以在Cookie中保存它,以便它可以在不同的會話之間持久。
在Spring MVC主題簡介
主題是靜態資源,典型的樣式表和圖像,影響視覺風格的應用程序的集合。 我們可以申請的Spring Web MVC框架的主題設置的整體外觀和感覺應用,從而提高用戶體驗。
在您的Web應用程序要使用的主題,您必須設置的org.springframework.ui.context.ThemeSource接口的一個實現。 在WebApplicationContext接口擴展ThemeSource但其職責委托一個專門的實施。 默認情況下,委托將org.springframework.ui.context.support.ResourceBundleThemeSource實施,從classpath的根目錄加載的屬性文件。 要使用一個自定義的ThemeSource實現或配置的ResourceBundleThemeSource基地名稱的前綴,你可以注冊一個保留名稱themeSource的應用程序上下文的bean。 Web應用程序上下文自動檢測與這個名字的bean,並使用它。
當使用ResourceBundleThemeSource,主題是指在一個簡單的屬性文件。 屬性文件中列出的資源,彌補主題。 下面是一個例子:
我們的目標
我們的目標是要改變的Hello World春3 MVC的主題支持。 用戶將有3預定義的主題(默認情況下,黑色和藍色)的選項來選擇主題。
Spring3 MVC添加主題支持
讓我們配置Spring3 MVC應用程序中添加主題支持。 為此,我們將下面的代碼添加到The Spring - servlet.xml文件。
文件:的WebContent / WEB - INF文件/The Spring - servlet.xml中
<!-- Theme Change Interceptor and Resolver definition -->
<bean id="themeChangeInterceptor"
class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
<property name="paramName" value="theme" />
</bean>
<bean id="themeResolver"
class="org.springframework.web.servlet.theme.CookieThemeResolver">
<property name="defaultThemeName" value="default" />
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
<ref bean="themeChangeInterceptor" />
</list>
</property>
</bean>
在上述配置中,首先我們必須增加 themeSource bean 。 請注意,這個bean是一個類ResourceBundleThemeSource實例ResourceBundleThemeSource,我們也有指定的屬性與價值"為主題的 " basenamePrefix。 ResourceBundleThemeSource類加載的屬性文件包含前綴開始"為主題的主題定義"。 因此,如果我們定義了3個新主題在我們的項目(默認情況下,黑色和藍色),然后我們將創建3個屬性文件,同時將有一定的配置屬性。 此外,這些文件將被划歸項目的類路徑。
接下來,我們定義了一個攔截器,這是一個類的實例org.springframework.web.servlet.theme.ThemeChangeInterceptor bean themeChangeInterceptor 。 另外請注意在這里,我們已經指定的屬性PARAMNAME與價值主題 。 每當一個請求參數具有不同價值觀的"主題",這個攔截器被調用。
一旦themeChangeInterceptor攔截主題的變化,這些變化,然后將其存儲在使用類org.springframework.web.servlet.theme.CookieThemeResolver餅干org.springframework.web.servlet.theme.CookieThemeResolver。 我們已經在我們的Spring- servlet.xml的配置文件配置這個類。 另外請注意,我們已經指定這個bean的默認主題名稱。
現在,創建以下資源/項目文件夾的屬性文件。
文件:資源/主題default.properties
css=themes/default.css
文件:資源/主題blue.properties
css=themes/blue.css
文件:資源/主題black.properties
css=themes/black.css
針對不同主題的CSS樣式表
讓我們創建CSS樣式表將作為我們項目的主題文件。 創建以下文件夾中的WebContent /主題的CSS文件。
文件的WebContent /主題/是default.css
body {
background-color: white;
color: black;
}
文件的WebContent /主題/ blue.css
body {
background-color: #DBF5FF;
color: #007AAB;
}
文件的WebContent /主題/ black.css
body {
background-color: #888;
color: white;
}
JSP視圖的變化
我們幾乎完成剩余的變化和最后一位的是增加一個功能,為用戶選擇從UI的主題。 為此,我們將改變header.jsp中的文件,並添加不同主題的3個環節。 用戶可以點擊此鏈接的任何改變web應用的主題。
文件的WebContent / WEB - INF / JSP / header.jsp中
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h3><spring:message code="label.title"/></h3>
<span style="float: right">
<a href="?lang=en">en</a>
|
<a href="?lang=de">de</a>
</span>
<span style="float: left">
<a href="?theme=default">def</a>
|
<a href="?theme=black">blk</a>
|
<a href="?theme=blue">blu</a>
</span>
請注意,在上面的JSP的變化中,我們創建了帶參數的3個環節"?主題="。 因此,每當用戶點擊這些鏈接,將通過一個新的參數的要求與相應的主題。 Spring的請求攔截器會取這個值,並相應地改變主題。
文件的WebContent / WEB - INF / JSP / layout.jsp中
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="<spring:theme code="css"/>" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
<style>
body {
font-family: sans-serif, Arial;
}
</style>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" align="center" width="100%" >
<tr>
<td height="30" colspan="2"><tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td width="15%"><tiles:insertAttribute name="menu" /></td>
<td width="85%"><tiles:insertAttribute name="body" /></td>
</tr>
<tr>
<td height="30" colspan="2"><tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>
這是所有Folks
這是相當多吧:)我們剛剛添加主題支持我們的演示的Spring 3.0 MVC應用程序。 所有你所要做的的僅僅是執行在Eclipse的應用程序。 按Alt + Shift + X,R。
下載源代碼
創建Spring3 MVC Hibernate 3的示例在Eclipse中使用Maven的
讓我們做一個完整的終端到終端的應用程序使用Spring3.0 MVC前端技術和Hibernate作為后端ORM技術。 對於這種應用,我們也將作為數據庫使用Maven來堅持數據構建和依賴管理和MySQL。
該應用程序將是一個簡單的聯系人管理器的應用程序,這將允許用戶添加新的聯系人。 將顯示聯系人列表中,用戶將可以刪除現有的聯系人。
我們的目標
正如上面描述的,我們的目標是創建一個聯系人管理器應用程序,這將允許用戶添加聯系人,或將其刪除。 聯系人管理應用程序的基本要求是:
- 在聯系人列表中添加新的聯系人。
- 從聯系人列表中顯示所有聯系人。
- 從聯系人列表中刪除聯系人。
以下是最終應用的截圖。
應用程序體系結構
我們將有一個為我們的演示應用程序的分層架構。 該數據庫將被普遍稱為DAO層的數據訪問層的訪問。 這一層將使用Hibernate API來與數據庫交互。 DAO層將調用一個服務層。 在我們的應用程序中,我們將有一個服務接口稱為ContactService。
入門
對於我們的聯系人管理器的例子,我們將使用MySQL數據庫。 在任何MySQL數據庫創建一個表接觸。 這是非常初步的例子,因此,我們有最低的列代表聯系。 隨意延長這個例子中,創建一個更復雜的應用程序。
CREATE TABLE CONTACTS
(
id INT PRIMARY KEY AUTO_INCREMENT,
firstname VARCHAR(30),
lastname VARCHAR(30),
telephone VARCHAR(15),
email VARCHAR(30),
created TIMESTAMP DEFAULT NOW()
);
在Eclipse中創建工程
聯系人管理器應用程序將使用Maven的構建和依賴管理。 為此,我們將使用Eclipse中的Maven的動態Web項目作為我們的應用程序的基礎架構。
下載下面的源代碼:
Maven的動態Web項目 (6.7 KB)
解壓縮到您的硬盤驅動器和源代碼導入Eclipse項目。 一旦該項目是在Eclipse中導入,我們將創建一個Java源代碼的包結構。 src /main/ Java的文件夾下創建以下軟件包。
- net.viralpatel.contact.controller -這個包將包含聯系人管理器應用程序的Spring控制器類。
- net.viralpatel.contact.form -這個包將包含形式為Contact Manager應用程序的對象。 聯系的形式將一個簡單的POJO類的不同屬性,如名字,姓氏等。
- net.viralpatel.contact.service -這個包將包含我們的聯系人管理器應用程序服務層的代碼。 服務層將有一個ContactService接口和相應的實現類
- net.viralpatel.contact.dao -這是Contact Manager應用程序的DAO層。 它由ContactDAO接口和相應的實現類。 DAO層使用Hibernate API來與數據庫交互。
實體類 - Hibernate的域類
讓我們先從Contact Manager應用程序的編碼。 首先,我們將創建一個表單對象或Hibernate的POJO類來存儲聯系人信息。 這個類將是一個實體類,將與聯系人數據庫表聯系起來。
net.viralpatel.contact.form包和復制下面的代碼下創建一個Java類Contact.java。
文件:src /main/ JAVA / NET / viralpatel /contact /dao/ Contact.java
package net.viralpatel.contact.dao;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="CONTACTS")
public class Contact {
@Id
@Column(name="ID")
@GeneratedValue
private Integer id;
@Column(name="FIRSTNAME")
private String firstname;
@Column(name="LASTNAME")
private String lastname;
@Column(name="EMAIL")
private String email;
@Column(name="TELEPHONE")
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;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
你會注意到的第一件事情是,import語句導入javax.persistence,而不是一個Hibernate或者Spring包。 與Spring中使用Hibernate,標准的JPA注解很好的工作,這就是我這里使用。
- 首先,我們已經注明@Entity實體,它告訴Hibernate這個類表示一個對象,我們可以堅持。
- @Table(name = "CONTACTS")注解告訴Hibernate的表在這個類中的地圖屬 性。 在這一類的第16行的第一個屬性是我們的對象ID將是獨一無二的,持續的所有事件。 這是為什么我們帶有@Id 。
- @GeneratedValue批注說,這個值將確定源代碼。
- @Column(name = "FIRSTNAME")注解是用來映射在Contacts表中的這個屬性FirstName列。
數據訪問(DAO)層
Contact Manager應用程序的DAO層包括一個ContactDAO ContactDAO和相應的ContactDAOImpl類ContactDAOImpl。 創建以下Java中的文件net.viralpatel.contact.dao包。
文件:src /main/ JAVA / NET / viralpatel /contact/ DAO / ContactDAO.java
package net.viralpatel.contact.dao;
import java.util.List;
import net.viralpatel.spring3.form.Contact;
public interface ContactDAO {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
文件:src /main/ JAVA / NET / viralpatel /contact/ DAO / ContactDAOImpl.java
package net.viralpatel.contact.dao;
import java.util.List;
import net.viralpatel.contact.from.Contact;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class ContactDAOImpl implements ContactDAO {
@Autowired
private SessionFactory sessionFactory;
public void addContact(Contact contact) {
sessionFactory.getCurrentSession().save(contact);
}
public List<Contact> listContact() {
return sessionFactory.getCurrentSession().createQuery("from Contact")
.list();
}
public void removeContact(Integer id) {
Contact contact = (Contact) sessionFactory.getCurrentSession().load(
Contact.class, id);
if (null != contact) {
sessionFactory.getCurrentSession().delete(contact);
}
}
}
在上面的代碼的DAO ContactDAOImpl ContactDAOImpl實現數據訪問ContactDAO接口ContactDAO定義方法listContact() ( addContact() ()等,以從數據庫中訪問數據。
請注意,我們已經使用了兩個@Repository @Autowired Autowired進行。
帶注釋的標記類是由Spring使用基於注解的配置和Classpath掃描時,自動檢測的候選人。 @Component注解是主要的刻板印象,表明一個被注解的類是一個"組件"。
@Repository注解,另一個是在Spring 2.0中引入的刻板印象。 這個注解是用來表明,作為一個倉庫一類的功能和需要有異常轉換應用透明就可以了。 異常翻譯的好處是,服務層只有從Spring的DataAccessException體系的例外處理,即使使用純JPA的DAO類。
在ContactDAOImpl使用的另一種注解@Autowired 。 這是用來自動裝配上的SessionFactory ContactDAOImpl的依賴。
服務層
聯系人管理器的應用服務層組成的接口ContactService和相應的實現類ContactServiceImpl。 創建下面的Java文件net.viralpatel.contact.service包。
文件:src /main/ JAVA / NET / viralpatel / contact/service/ContactService.java
package net.viralpatel.contact.service;
import java.util.List;
import net.viralpatel.contact.form.Contact;
public interface ContactService {
public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}
文件:src /main/ JAVA / NET / viralpatel / contact/service/ ContactServiceImpl.java
package net.viralpatel.contact.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import net.viralpatel.contact.dao.ContactDAO;
import net.viralpatel.contact.form.Contact;
@Service
public class ContactServiceImpl implements ContactService {
@Autowired
private ContactDAO contactDAO;
@Transactional
public void addContact(Contact contact) {
contactDAO.addContact(contact);
}
@Transactional
public List<Contact> listContact() {
return contactDAO.listContact();
}
@Transactional
public void removeContact(Integer id) {
contactDAO.removeContact(id);
}
}
在上述服務層的代碼,我們創建了一個接口ContactService ,並在課堂上ContactServiceImpl ContactServiceImpl 。 請注意,我們使用一些如春@Service @Autowired @Transactional @ Transactional在我們的代碼。 這些注解被稱為Spring典型化注解。
用於裝飾ContactServiceImpl類@Service的刻板印象注釋是一個專門@Component注解的形式。 這是適當的注釋與服務層中@Service @服務,以方便工具的處理或預測任何未來服務的特定功能,可能被添加到這個注解。
添加Spring MVC的支持
讓我們添加到我們的Web應用程序的Spring MVC的支持。
更新web.xml文件,並添加org.springframework.web.servlet.DispatcherServlet servlet映射。 另外請注意,我們已制訂與URL / springServlet,所以所有的請求處理的Spring。
文件:/ src目錄/ webapp的/ WEB - INF目錄/ web.xml中
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>list.html</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>/</url-pattern>
</servlet-mapping>
</web-app>
一旦在web.xml配置,讓我們在/ src目錄/main/ webapp的/ WEB - INF文件夾中添加- servlet.xml的Spring和jdbc.properties文件。
文件:/ SRC /main/ webapp的/ WEB - INF目錄/ jdbc.properties
jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/ContactManager
jdbc.username=root
jdbc.password=testpass
jdbc.properties文件包含數據庫連接信息,例如數據庫URL,用戶名,密碼,驅動程序類。 如果你不使用MySQL,你可能要編輯的DriverClass和其他數據庫的方言。
文件:/ SRC /main/ webapp的/ WEB - INF /Spring- 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.contact" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Spring- servlet.xml文件中包含不同的The Spring ,如事務管理器,Hibernate會話的工廠bean,數據源等映射
- jspViewResolver This bean -這個bean定義的視圖解析器Spring MVC的。 對於這個bean,我們也設置為"/ / WEB-INF/jsp"作為"。jsp"為后綴的前綴。 因此The Spring 自動解析WEB-INF/jsp文件夾,並分配后綴JSP。JSP來。
- messageSource bean -提供國際化,我們的演示應用程序中,我們定義束資源屬性文件,要求在CLASSPATH中的messages.properties。
在Spring MVC 相關: 國際化 - propertyConfigurer綠 bean -這個bean是用來裝載數據庫屬性文件jdbc.properties。 這是Hibernate中的連接設置使用的文件存儲在數據庫連接的詳細信息。
- 數據源bean -這是Java的數據源連接到聯系人管理器數據庫。 我們提供的JDBC驅動程序類,用戶名,密碼等配置。
- SessionFactory的 bean -這是我們定義Hibernate配置不同的休眠設置。 hibernate.cfg.xml中設置一個配置文件,其中包含實體類的映射
- TransactionManager的綠 bean -我們使用Hibernate事務管理器來管理我們的聯系人管理器應用程序的交易。
文件:/ SRC /主要/資源/ hibernate.cfg.xml中
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="net.viralpatel.contact.form.Contact" />
</session-factory>
</hibernate-configuration>
文件:/ src /main/資源/ messages_en.properties
label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.addcontact=Add Contact
label.menu=Menu
label.title=Contact Manager
label.footer=© ViralPatel.net
Spring MVC的控制器
我們幾乎完成了我們的應用程序。 只需添加下面的Spring控制器類ContactController.java net.viralpatel.contact.controller包。
文件:/ src /main/ JAVA / NET / viralpatel / contact.controller / ContactController.java
package net.viralpatel.contact.controller;
import java.util.Map;
import net.viralpatel.contact.form.Contact;
import net.viralpatel.contact.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ContactController {
@Autowired
private ContactService contactService;
@RequestMapping("/index")
public String listContacts(Map<String, Object> map) {
map.put("contact", new Contact());
map.put("contactList", contactService.listContact());
return "contact";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addContact(@ModelAttribute("contact")
Contact contact, BindingResult result) {
contactService.addContact(contact);
return "redirect:/index";
}
@RequestMapping("/delete/{contactId}")
public String deleteContact(@PathVariable("contactId")
Integer contactId) {
contactService.removeContact(contactId);
return "redirect:/index";
}
}
The Spring 控制器定義了三種方法來操縱Contact Manager應用程序。
- listContacts方法-該方法使用服務接口ContactServer來獲取我們的應用程序中的所有詳細聯系方式。 它返回一個接觸數組。 請注意,我們已經請求映射"/指數",以這種方法。 因此,Spring會自動調用此方法,每當遇到這個URL請求中。
- addContact方法-這種方法增加了一個新的聯系人,聯系人列表。 獲取詳細聯系方式Contact使用對象@ModelAttribute注解。 另外請注意,請求"/添加"映射使用此方法。 請求的方法也應發表。 在接觸使用列表添加ContactService一旦接觸,我們重定向到/索引頁,再調用listContacts()方法以顯示到用戶的聯系人列表。
相關: 在Spring MVC的表單 - deleteContact方法-這種方法將刪除從聯系人列表中的聯系人。 類似的以這種方法也addContact重定向用戶/索引頁,一旦接觸被刪除。 要注意在這個方法是我們所請求的URL映射使用@ RequestMapping注解的方式。 網址"/ / {的ContactID}"映射因此,每當用戶發送一個請求/ delete/12,刪除,deleteCotact方法將嘗試刪除接觸與ID:12。
最后添加下面的JSP文件到WEB-INF/jsp文件夾。
文件:/ SRC /main/ webapp的/ WEB - INF / JSP / contact.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager | viralpatel.net</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="add.html" commandName="contact">
<table>
<tr>
<td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="email"><spring:message code="label.email"/></form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="<spring:message code="label.addcontact"/>"/>
</td>
</tr>
</table>
</form:form>
<h3>Contacts</h3>
<c:if test="${!empty contactList}">
<table class="data">
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th> </th>
</tr>
<c:forEach items="${contactList}" var="contact">
<tr>
<td>${contact.lastname}, ${contact.firstname} </td>
<td>${contact.email}</td>
<td>${contact.telephone}</td>
<td><a href="delete/${contact.id}">delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
下載源代碼
點擊這里下載Contact Manager應用程序的完整的源代碼(16 KB )
這是所有Folks
編譯並執行在Eclipse中的聯系人管理器應用程序。
在Spring3 MVC和Hibernate保存/ Retreving BLOB對象
使用BLOB / CLOB數據類型在數據庫中的某個時候一個簡單的任務。 我發現,特別是與Hibernate 3的工作時,存儲和檢索BLOB對象,我們需要照顧的某些事情。 讓我們看到了一個教程,我們將使用Spring 3 MVC和Hibernate 3的存儲和檢索數據庫中的BLOB對象。
我們的目標
我們的目標是創建一個在Spring3 MVC和Hibernate的文檔管理應用程序。 以下是功能。
- 與領域,如文件名稱,描述和瀏覽按鈕選擇文件系統的文件的主要頁面上顯示窗體。
- 從本地驅動器,用戶可以選擇任何文件,並上傳使用保存文件的功能相同。
- 添加的所有文件保存在一個數據庫表。
- 目前數據庫中的所有文件列表顯示在主頁上。
- 列表中的每個文件有兩個按鈕:刪除和下載。
- 點擊下載按鈕,可以對任何文件下載。
- 點擊刪除按鈕,可以刪除任何文件。
這里是最后文件管理器應用程序的屏幕截圖。
第1步:創建數據庫表
文件管理器應用程序,我們將使用MySQL數據庫。 在MySQL數據庫docdb中創建表文件。 這是非常初步的例子,因此我們有最低的列代表一個文檔。 隨意延長這個例子中,創建一個更復雜的應用程序。
CREATE DATABASE 'docdb';
USE 'docdb';
CREATE TABLE 'documents' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'name' varchar(200) NOT NULL,
'description' text NOT NULL,
'filename' varchar(200) NOT NULL,
'content' mediumblob NOT NULL, /* for ORACLE enter BLOB*/
'content_type' varchar(255) NOT NULL,
'created' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ('id')
);
第2步:在Eclipse中創建Maven項目
文檔管理器應用程序將使用Maven的構建和依賴管理。 為此,我們將使用Eclipse中的Maven的動態Web項目作為我們的應用程序的基礎架構。
或直接下載下面的源代碼:
Maven的動態Web項目 (6.7 KB)
一旦導入/創建在Eclipse的Maven的Web項目。 Maven的pom.xml文件復制到以下內容。 這些都是我們將使用我們的文件管理器應用程序的依賴關系。
文件:/的pom.xml
<?xml version="1.0" encoding="UTF-8"?><project>
<modelVersion>4.0.0</modelVersion>
<groupId>MavenWeb</groupId>
<artifactId>MavenWeb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<description></description>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.3.2.ga</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
<properties>
<org.springframework.version>3.0.2.RELEASE</org.springframework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
解壓縮到您的硬盤驅動器和源代碼導入Eclipse項目。 一旦該項目是在Eclipse中導入,我們將創建一個Java源代碼的包結構。 首先重命名項目DocumentManager和src /main/ Java的文件夾下創建以下包。
- net.viralpatel.docmanager.controller -這個包將包含文件管理器應用程序的Spring控制器類。
- net.viralpatel.docmanager.model -這個包將包含文件管理器應用程序的表單對象。 文檔模型,將具有不同屬性,如文件名稱,說明,文件名等簡單的POJO類
- net.viralpatel.docmanager.dao -這是文件管理器應用程序的DAO層。 它由DocumentDao類將使用Hibernate API來與數據庫交互。
- 在 src /主要/資源文件夾,將Hibernate配置文件:hibernate.cfg.xml中。
- 在WEB - INF文件夾中的 JSP / documents.jsp文件呈現文檔列表和添加形式和jdbc.properties文件,其中包含數據庫連接配置。 此外,它包含The Spring - servlet.xml中,將定義所有的控制器類和 web.xml包含Spring配置。
實體類 - Hibernate的模型類
讓我們先從文件管理器應用程序的編碼。 首先,我們將創建一個模型對象或Hibernate的POJO類來存儲文件中的信息。 這個類將是一個實體類,將文件,數據庫表鏈接。
創建一個Java類Document.java net.viralpatel.docmanager.model包和復制下面的代碼下。
文件:/ src /main/ JAVA / NET / viralpatel / docmanager /模型/ Document.java
package net.viralpatel.docmanager.model;
import java.sql.Blob;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
@Table(name="documents")
public class Document {
@Id
@GeneratedValue
@Column(name="id")
private Integer id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@Column(name="filename")
private String filename;
@Column(name="content")
@Lob
private Blob content;
@Column(name="content_type")
private String contentType;
@Column(name="created")
private Date created;
//Getter and Setter methods
}
你會注意到的第一件事情是,import語句導入javax.persistence,而不是一個Hibernate或者Spring包。 與Spring中使用Hibernate,標准的JPA注解很好的工作,這就是我這里使用。
- 首先,我們已經注明@Entity實體,它告訴Hibernate這個類表示一個對象,我們可以堅持。
- @Table(name = "documents")注解告訴Hibernate的表映射在這個類的屬性文件表。 在這一類在第20行的第一個屬性是我們的對象ID將是獨一無二的,持續的所有事件。 這是為什么我們帶有@Id 。
- @GeneratedValue批注說,這個值將確定源代碼。
- @Column(name = "filename")注釋是使用這個屬性映射到DOCUMENTS表中的文件名 列。
數據訪問(DAO)層
文件管理器應用程序的DAO層組成的一類DocumentDAO。 理想的解決方案將創建一個接口(DocumentDAO)和其相應的實現類DocumentDAOImpl。 但為簡單起見,我們將創建只是正常的DAO類DocumentDAO.java。
文件:src /main/ JAVA / NET / viralpatel / docmanager / DAO / DocumentDAO.java
package net.viralpatel.docmanager.dao;
import java.util.List;
import net.viralpatel.docmanager.model.Document;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
public class DocumentDAO {
@Autowired
private SessionFactory sessionFactory;
@Transactional
public void save(Document document) {
Session session = sessionFactory.getCurrentSession();
session.save(document);
}
@Transactional
public List<Document> list() {
Session session = sessionFactory.getCurrentSession();
List<Document> documents = null;
try {
documents = (List<Document>)session.createQuery("from Document").list();
} catch (HibernateException e) {
e.printStackTrace();
}
return documents;
}
@Transactional
public Document get(Integer id) {
Session session = sessionFactory.getCurrentSession();
return (Document)session.get(Document.class, id);
}
@Transactional
public void remove(Integer id) {
Session session = sessionFactory.getCurrentSession();
Document document = (Document)session.get(Document.class, id);
session.delete(document);
}
}
方法:
- list()方法-該方法獲取存儲在文件表中的所有文件的列表,並返回一個Document對象名單。
- save()方法-該方法是使用數據庫存儲到一個新的文檔(包括BLOB)。
- get()方法-該方法返回一個給定的ID從數據庫文檔的條目。 下載功能,用於從數據庫中存儲的文件下載。
- remove()方法-該方法是使用一個特定的ID從數據庫中刪除的文件。
請注意,我們已經使用了兩個@Repository @ @Autowired Autowired進行。 帶注釋的標記類是由Spring使用基於注解的配置和Classpath掃描時,自動檢測的候選人。 @Component注解是主要的刻板印象,表明一個被注解的類是一個"組件"。
@Repository注解,另一個是在Spring 2.0中引入的刻板印象。 這個注解是用來表明,作為一個倉庫一類的功能和需要有異常轉換應用透明就可以了。 異常翻譯的好處是,服務層只有從Spring的DataAccessException體系的例外處理,即使使用純JPA的DAO類。
在DocumentDAO使用的另一種注解@Autowired 。 這是用來自動裝配DocumentDAO SessionFactory的依賴。
另外請注意,我們每個方法使用@ Transactional注解。 理想情況下,DAO層是從一個服務層和事務管理的需要,在服務層指定的訪問。 但同樣為簡單起見,我們將不包括在我們的例子中的服務層,直接調用DAO層從Spring控制器。 再次,隨意改變的執行情況,並添加您自己的服務層之間。
在Spring MVC和Hibernate的分層應用與服務的更多信息,閱讀本教程。
Spring MVC的休眠Maven的例子
Spring MVC的支持添加到WebApplication的
讓我們添加到我們的Web應用程序的Spring MVC的支持。
更新web.xml文件,並添加org.springframework.web.servlet.DispatcherServlet servlet映射。 另外請注意,我們已制訂與URL / springServlet,所以所有的請求處理的Spring。
文件:/ src目錄/ webapp的/ WEB - INF目錄/ web.xml中
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>DocumentManager</display-name>
<welcome-file-list>
<welcome-file>index.html</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>
一旦在web.xml配置,讓我們在/ src目錄/main/ webapp的/ WEB - INF文件夾中添加- servlet.xml的Spring和jdbc.properties文件。
文件:/ SRC /main/ webapp的/ WEB - INF目錄/ jdbc.properties
jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/docdb
jdbc.username=root
jdbc.password=password
jdbc.properties文件包含數據庫連接信息,例如數據庫URL,用戶名,密碼,驅動程序類。 如果你不使用MySQL,你可能要編輯的DriverClass和其他數據庫的方言。
文件:/ SRC /main/ webapp的/ WEB - INF /Spring- 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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<context:component-scan base-package="net.viralpatel.docmanager" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.SetBigStringTryClob">true</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
</props>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="10000000" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Spring- servlet.xml文件中包含不同的The Spring ,如事務管理器,Hibernate會話的工廠bean,數據源等映射
- jspViewResolver綠 bean -這個bean定義的視圖解析器Spring MVC的。 對於這個bean,我們也設置為"/ / WEB-INF/jsp"作為"。jsp"為后綴的前綴。 因此The Spring 自動解析WEB-INF/jsp文件夾,並分配后綴JSP。JSP來。
- propertyConfigurer綠 bean -這個bean是用來裝載數據庫屬性文件jdbc.properties。 這是Hibernate中的連接設置使用的文件存儲在數據庫連接的詳細信息。
- 數據源bean -這是Java的數據源連接到文檔管理數據庫。 我們提供的JDBC驅動程序類,用戶名,密碼等配置。
- SessionFactory的 bean -這是我們定義Hibernate配置不同的休眠設置。 hibernate.cfg.xml中設置一個配置文件,其中包含實體類映射。 另外請注意,在SessionFactory的,我們有指定的幾個Hibernate的屬性, hibernate.connection.SetBigStringTryClob hibernate.connection.SetBigStringTryClob hibernate.jdbc.batch_size hibernate.jdbc.batch_size 。 這些是用來在Hibernate配置將BLOB / CLOB設置。
- 的MultipartResolver綠 bean -我們使用Spring MVCS CommonsMultipartResolver。 這個解析器將請求解決多重形式的數據,如文件上傳和Spring控制器提供的文件對象。 請注意,我們有指定maxUploadSize屬性maxUploadSize,價值千萬。 這是在我們的例子中可以上傳最大的文件大小限制。
- TransactionManager的綠 bean -我們使用Hibernate事務管理器來管理我們的文件管理器應用程序的交易。
文件:/ SRC /主要/資源/ hibernate.cfg.xml中
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="net.viralpatel.docmanager.model.Document" />
</session-factory>
</hibernate-configuration>
控制器 - Spring MVC控制器類
我們幾乎完成了我們的應用程序。 只需添加下面的Spring控制器類DocumentController.java net.viralpatel.docmanager.controller包。
文件:/ src /main/ JAVA / NET / viralpatel / docmanager /控制器/ DocumentController.java
package net.viralpatel.docmanager.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.viralpatel.docmanager.dao.DocumentDAO;
import net.viralpatel.docmanager.model.Document;
import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class DocumentController {
@Autowired
private DocumentDAO documentDao;
@RequestMapping("/index")
public String index(Map<String, Object> map) {
try {
map.put("document", new Document());
map.put("documentList", documentDao.list());
}catch(Exception e) {
e.printStackTrace();
}
return "documents";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
@ModelAttribute("document") Document document,
@RequestParam("file") MultipartFile file) {
System.out.println("Name:" + document.getName());
System.out.println("Desc:" + document.getDescription());
System.out.println("File:" + file.getName());
System.out.println("ContentType:" + file.getContentType());
try {
Blob blob = Hibernate.createBlob(file.getInputStream());
document.setFilename(file.getOriginalFilename());
document.setContent(blob);
document.setContentType(file.getContentType());
} catch (IOException e) {
e.printStackTrace();
}
try {
documentDao.save(document);
} catch(Exception e) {
e.printStackTrace();
}
return "redirect:/index.html";
}
@RequestMapping("/download/{documentId}")
public String download(@PathVariable("documentId")
Integer documentId, HttpServletResponse response) {
Document doc = documentDao.get(documentId);
try {
response.setHeader("Content-Disposition", "inline;filename=\"" +doc.getFilename()+ "\"");
OutputStream out = response.getOutputStream();
response.setContentType(doc.getContentType());
IOUtils.copy(doc.getContent().getBinaryStream(), out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("/remove/{documentId}")
public String remove(@PathVariable("documentId")
Integer documentId) {
documentDao.remove(documentId);
return "redirect:/index.html";
}
}
The Spring 控制器定義了四個方法來操作文件管理器應用程序。
- 索引方法-該方法使用列表()DocumentDAO的方法來獲取從數據庫中的所有文件的列表。 請注意,我們已經請求映射"/指數",以這種方法。 因此,Spring會自動調用此方法,每當遇到這個URL請求中。
- 保存方法-這種方法增加了一個新的文件,文件清單。 獲取該文件的細節,在文檔中使用@ModelAttribute @ ModelAttribute注解。 另外請注意,請求"/保存",用這種方法映射。 請求的方法也應發表。 一旦該文件是在文件列表中添加,我們重定向到/ index.html頁面,這反過來又調用index()方法來顯示文件列表給用戶。 還有一點需要注意的是@RequestParam 。 我們MultipartFile對象使用@ RequestParam("文件")注釋映射。 Spring自動檢測要求"文件"的數據和地圖MultipartFile對象。 這個對象是后來轉換為BLOB對象,並在文件的內容設置。
相關: 在Spring MVC的表單 - 下載方法-這種方法是用來下載所選的測試用例。 請注意,我們是從數據庫使用DAO類和THN設置響應的數據流中獲取文件的內容。 另外請注意,我們使用response.setHeader()方法來設置"Content-Disposition" 。 這將提高在瀏覽器中的另存為對話框,當用戶嘗試下載文件。
- 刪除的方法-這種方法從文件清單中刪除的文件。 類似的save()這個方法也重定向用戶/ index.html頁面,一旦該文件被刪除。 在此方法中需要注意的一點是我們所請求的URL映射使用@ RequestMapping注解的方式。 網址"/刪除/ {documentId}"映射從而每當用戶發送一個請求/ remove/12.html,remove方法將嘗試刪除與身份證件:12。
最后添加下面的JSP文件到WEB-INF/jsp文件夾。
文件:/ SRC /main/ webapp的/ WEB - INF / JSP / documents.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Document Manager - viralpatel.net</title>
</head>
<body>
<h2>Document Manager</h2>
<h3>Add new document</h3>
<form:form method="post" action="save.html" commandName="document" enctype="multipart/form-data">
<form:errors path="*" cssClass="error"/>
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="description">Description</form:label></td>
<td><form:textarea path="description" /></td>
</tr>
<tr>
<td><form:label path="content">Document</form:label></td>
<td><input type="file" name="file" id="file"></input></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Document"/>
</td>
</tr>
</table>
</form:form>
<br/>
<h3>Document List</h3>
<c:if test="${!empty documentList}">
<table class="data">
<tr>
<th>Name</th>
<th>Description</th>
<th> </th>
</tr>
<c:forEach items="${documentList}" var="document">
<tr>
<td width="100px">${document.name}</td>
<td width="250px">${document.description}</td>
<td width="20px">
<a href="${pageContext.request.contextPath}/download/${document.id}.html"><img
src="${pageContext.request.contextPath}/img/save_icon.gif" border="0"
title="Download this document"/></a>
<a href="${pageContext.request.contextPath}/remove/${document.id}.html"
onclick="return confirm('Are you sure you want to delete this document?')"><img
src="${pageContext.request.contextPath}/img/delete_icon.gif" border="0"
title="Delete this document"/></a>
</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
下載源代碼
這是所有Folks
編譯並執行文件管理器應用程序在Eclipse。 打開網址http://localhost:8080/DocumentManager/index.html
另見:
以上翻譯來自:
http://viralpatel.net/blogs/2010/06/tutorial-spring-3-mvc-introduction-spring-mvc-framework.html
Spring Roo的:兩個數據庫配置
我見過很多時候, 一個Spring Roo的論壇經常問題。 現在的問題是"如何配置應用程序來處理這兩個數據庫"。
當然,這是一個更充裕的Spring Roo的問題,由於它涉及JPA和Spring的持久性堆棧。 所以,我相信這將是所有的Spring開發的社會,面對這樣的問題感興趣。
我假設讀者是一些與Spring Roo的familarity的Java開發。 我將重點討論如何去配置只。 對於如何使用Roo的幫助,請訪問http://www.springsource.org/roo 。
Hands on the problem
我創建了解釋設置以下最低Roo的項目(如圖所示)。 我將修改的方式,每個實體將來自不同的獨立的數據庫配置。
project --topLevelPackage org.pragmatikroo.twodb
persistence setup --provider HIBERNATE --database MYSQL --userName <username> --password <password> --databaseName twodbone
logging setup --level DEBUG --package PERSISTENCE
entity --class ~.domain.DbOne
field string --fieldName name
entity --class ~.domain.DbTwo
field string --fieldName name
perform clean
perform eclipse
exit
Database.properties文件的原始
database.password=<password>
database.url=jdbc\:mysql\://localhost\:3306/twodb
database.username=<username>
database.driverClassName=com.mysql.jdbc.Driver
Database.properties文件的修改
database.password1=<password1>
database.url1=jdbc\:mysql\://localhost\:3306/twodbone
database.username1=<username1>
database.password2=<password1>
database.url2=jdbc\:mysql\://localhost\:3306/twodbtwo
database.username2=<username2>
database.driverClassName=com.mysql.jdbc.Driver
基本上,我有重復的代碼,從袋鼠交付定義第二個數據庫的原始文件。 這種模式將重復以及其他文件。
修改persistence.xml文件
<persistence-unit name="persistenceUnit1" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.josean.twodb.domain.DbOne</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<!-- Uncomment the following two properties for JBoss only -->
<!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
<!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
</properties>
</persistence-unit>
<persistence-unit name="persistenceUnit2" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.josean.twodb.domain.DbTwo</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<!-- Uncomment the following two properties for JBoss only -->
<!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
<!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
</properties>
</persistence-unit>
我第二個數據庫的持久化單元的代碼復制並定義唯一的ID 重要:添加<class>和<exclude-unlisted-classes>在上面的代碼所示。 暗示這個持久化單元處理的每個實體都包括在內。
applicationContext.xml文件修改
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource1">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url1}"/>
<property name="username" value="${database.username1}"/>
<property name="password" value="${database.password1}"/>
<property name="validationQuery" value="SELECT 1 FROM DUAL"/>
<property name="testOnBorrow" value="true"/>
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory1">
<property name="dataSource" ref="dataSource1"/>
<property name="persistenceUnitName" value="persistenceUnit1"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager1" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager1">
<property name="entityManagerFactory" ref="entityManagerFactory1" />
</bean>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource2">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url2}"/>
<property name="username" value="${database.username2}"/>
<property name="password" value="${database.password2}"/>
<property name="validationQuery" value="SELECT 1 FROM DUAL"/>
<property name="testOnBorrow" value="true"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager2">
<property name="entityManagerFactory" ref="entityManagerFactory2"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager2" />
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory2">
<property name="dataSource" ref="dataSource2"/>
<property name="persistenceUnitName" value="persistenceUnit2"/>
</bean>
同一進程的其他文件。 重復的,如圖所示。 添加屬性的entityManagerFactory的 bean 。
修改web.xml文件
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter1</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory1</param-value>
</init-param>
</filter>
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter2</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory2</param-value>
</init-param>
</filter>
這就是它!。 部署和測試應用就緒。
結論
我比較有興趣的讀者,特別是Spring Roo的開發人員,如何設置一個Spring的web應用程序來訪問第二個數據庫的應用程序上下文。
Spring Roo的自定義Web MVC用戶界面的形式
還有,我喜歡從Spring Roo的許多功能:
- 外殼是非常有效的一個有用的標簽完成建設項目
- 往返是必不可少的,以保持同步代碼
- 沒有"不必要的抽象"代碼生成令人耳目一新,雖然1.1.2版本可能會帶來一些他們只是僅舉幾例。
在列表的頂部,我把,我考慮的寶石冠:Tagx庫JSP(X)的意見。 本文假定讀者熟悉Spring Roo的一些。 對於Spring Roo的更多信息,請訪問其網站http://www.springsource.org/roo。
簡而言之Tagx圖書館
tagx庫是由Web MVC安裝附加。 Spring Roo的支架控制器和實體類的意見。 點擊創建從tagx庫的組件。 請閱讀參考文件http://static.springsource.org/spring-roo/reference/html/base-web.html一個完整的描述。
事不宜遲。 迷你型業務。
本文指的是在世界年鑒實施JD網站的形式。 世界年鑒是一個創建Web應用程序與Spring Roo的發展實驗組的成員。 展示網站的鏈接 https://pragmatikroo.org/showcases 。 的目的,是落實典型的Web的CRUD范圍以外的發展要求。
這是工作的問題:我需要自定義list.tagx的組件來呈現國家的國旗圖像。 通常,此組件呈現一個網格內的字符串和數字。 輕松導航的形式將分頁,如下圖所示。 此功能提供了一個世界年鑒廣場查看,此外,我要附加導航到一個國家的詳細信息頁面的點擊事件。
的形式提供了兩種選擇控制,使縣過濾。 分頁的形式和導航一個典型的list.jspx形式是相同的方式。 通常情況下,Roo的選擇按鈕與動作按鈕。 在這種情況下,我刪除和過濾作用是觸發選擇選擇。 我沒有從頭開始。 我只是調整Roo的生成的源代碼。 袋鼠是偉大的!。
分頁畫廊表
下面是呈現標志國家畫廊查看源代碼。 這里有很多的定制。 但是你仍然可以看到原支架Roo的創建形式的骨架。
畫廊JSPX分頁代碼
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:page="urn:jsptagdir:/WEB-INF/tags/form"
xmlns:table="urn:jsptagdir:/WEB-INF/tags/form/fields" version="2.0"
xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields"
xmlns:form="urn:jsptagdir:/WEB-INF/tags/form"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">
<script type="text/javascript">
<![CDATA[
function selectIt( aName ){
var selectContinentPage="/worldAlmanac/countrys";
document.body.innerHTML = '<form id="dynForm" action='+
selectContinentPage+
' method="get">'+
'<input type="hidden" name="find" value="gallery" />'+
'<input type="hidden" name="\page" value="1" />'+
'<input type="hidden" name="\size" value="50" />'+
'<input type="hidden" name="'+aName.name+'" value="'+aName.value+'" />'+
'</form>';
document.getElementById("dynForm").submit();
}
]]>
</script>
<jsp:output omit-xml-declaration="yes" />
<div id="wrapperTop">
<input name="btnBack" title="Previous Page"
onMouseOver="window.status='Previous Page'; return true"
onMouseOut="window.status=''; return true"
onclick="location.href = '/worldAlmanac'"
type="button" value="Previous Page"/>
</div>
<page:list id="pl:org.josean.rooworld.domain.Country"
items="${countrys}">
<div>
<div style="float: left; width: 60%;">
<field:select disableFormBinding="true"
id="f:org.josean.rooworld.domain.Country.continent"
items="${continent}"
field="continent"
path="/countrys"
onchange="selectIt(this);"/>
</div>
<div>
<field:select disableFormBinding="true"
id="f:org.josean.rooworld.domain.Country.region"
items="${region}"
field="region"
path="/countrys"
onchange="selectIt(this);" />
</div>
</div>
<table:gallery data="${countrys}"
id="l:org.josean.rooworld.domain.Country" path="/countrys"
title="Click on image to select country info" page="${page}" size="${size}"
typeIdFieldName="code" pageid="page" sizeid="size" delete="false"
update="false" create="false" select="false" show="false"
anchorURL="/countrys?find=gallery">
<table:column id="c:org.josean.rooworld.domain.Country.code"
type="img" property="code" />
</table:gallery>
</page:list>
<script type="text/javascript">
<![CDATA[
function applyStateControl(aControl, anItem){
var option = aControl.getElementsByClassName("HTMLOptionElement");
for( i=0; i<aControl.options.length;i++){
if(aControl.options.item(i).value==anItem)
break;
}
aControl.options.item(i).defaultSelected=true;
}
var selectedItem= window.location.search;
var cIndex = selectedItem.indexOf("continent");
var rIndex = selectedItem.indexOf("region");
if(cIndex>-1){
var continent= selectedItem.substring( cIndex+10, selectedItem.length);
var control = document.getElementById("_continent_id");
applyStateControl(control, continent);
}
else if (rIndex>-1){
var region= selectedItem.substring( rIndex+7, selectedItem.length);
var control = document.getElementById("_region_id");
applyStateControl(control, region);
}
]]>
</script>
</div>
接下來,我將向國家詳細表格后,點擊其國旗航行。 WorldAlmanac集成以及容易谷歌地圖。 這使得國家的地圖,使用其存儲在數據庫中的緯度/經度。 所有元素,共同創造一個很好的組合。
詳細的國家表
詳細的國家JSPX代碼
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div
xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:page="urn:jsptagdir:/WEB-INF/tags/form"
version="2.0"
xmlns:spring="http://www.springframework.org/tags"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<jsp:output omit-xml-declaration="yes" />
<spring:url
value="http://maps.google.com/maps/api/js?sensor=false"
var="google_map_url" />
<spring:url
value="/static/js/googleMap.js"
var="tmp_map_url" />
<c:set
var="map_url"
value="uri:/${tmp_map_url}" />
<script
type="text/javascript"
src="${google_map_url}">
</script>
<script
src="${tmp_map_url}"
type="text/javascript">
</script>
<page:show
id="ps:org.josean.rooworld.domain.Country"
object="${country}"
z="3tU6/DN2doNWT+sTLgEAZR7U8hk=">
<table
width="100%;">
<tr>
<td
width="50%">
<field:display
field="code"
id="s:org.josean.rooworld.domain.Country.code"
object="${country}"
type="img"
z="?"
label="Flag" />
<field:display
field="name"
id="s:org.josean.rooworld.domain.Country.name"
object="${country}"
z="FAyyuD7aX42uNNgL4e7tS//taRI=" />
<field:display
field="continent"
id="s:org.josean.rooworld.domain.Country.continent"
object="${country}"
z="fSpvsKUctolI0akJTZzYHoOwueo=" />
<field:display
field="region"
id="s:org.josean.rooworld.domain.Country.region"
object="${country}"
z="z7xfg8bZs8LFPftHWVjP45HdpGI=" />
<field:display
field="surfaceArea"
id="s:org.josean.rooworld.domain.Country.surfaceArea"
object="${country}"
z="7C7ri5E3jCruBij5X5iEJqh4g1k=" />
<field:display
field="indepYear"
id="s:org.josean.rooworld.domain.Country.indepYear"
object="${country}"
z="EZL1ubZ/J9SiMbCUfokjr1OoDKA=" />
<field:display
field="population"
id="s:org.josean.rooworld.domain.Country.population"
object="${country}"
z="kqB3gvDWozV4lRD2m/S/6tpw2rE=" />
<field:display
field="lifeExpectancy"
id="s:org.josean.rooworld.domain.Country.lifeExpectancy"
object="${country}"
z="6Sj9b9rtuCZd1V5oNnz7gmAaQkI=" />
<field:display
field="gnp"
id="s:org.josean.rooworld.domain.Country.gnp"
object="${country}"
z="cQC9QwBNccJoYP9+xn4nAakFVVk=" />
<field:display
field="gnpold"
id="s:org.josean.rooworld.domain.Country.gnpold"
object="${country}"
z="AKqXyf8qWGWBU0HwUSIvnnLzZeE=" />
<field:display
field="localName"
id="s:org.josean.rooworld.domain.Country.localName"
object="${country}"
z="jYwa2XCaRe58W9ae45HLAaLlt7A=" />
<field:display
field="govermentForm"
id="s:org.josean.rooworld.domain.Country.govermentForm"
object="${country}"
z="N9WckigFkEM6lBgGaHR3QG13Lq4=" />
<field:display
field="capital"
id="s:org.josean.rooworld.domain.Country.capital"
object="${country}"
z="JRQSSvwHoOt1d2yff5JeK7NDn0k=" />
<field:display
field="code2"
id="s:org.josean.rooworld.domain.Country.code2"
object="${country}"
z="gIR7Z72tUJCdEBJHExd4FLG1ze0=" />
<field:display
field="headofState"
id="s:org.josean.rooworld.domain.Country.headofState"
object="${country}"
z="EmNqI9StH4djy7tAZsVKe3+VJ+A=" />
<field:display
field="latitude"
id="s:org.josean.rooworld.domain.Country.latitude"
object="${country}"
z="?" />
<field:display
field="longitude"
id="s:org.josean.rooworld.domain.Country.longitude"
object="${country}"
z="?" />
<page:find
reportParam="${country.code}"
path="/pdf/countryReport"
id="c:report"
buttonLabel="Pdf Report" />
</td>
<td>
<div
id="map_canvas"
style="width: 400px; height: 550px;">
<button
onclick="initialize();">Show Map</button>
</div>
</td>
</tr>
</table>
</page:show>
</div>
這就是它!
結論
本文展示了一個定制的例子,使用最初創建由Spring Roo的Web MVC的附加腳手架開始的代碼。 我發現極具表現力和直觀的JSPX符號。 tagx庫充裕,很容易擴展如果需要的話。 JSPX XML文檔,因此,他們對健康驗證。 我不得不說這開始感到厭煩我,而是很短的時間后,我習慣了,並開始喜歡它。 且不說形式錯誤檢查的好處。
Spring Roo的Web MVC的意見和他們的禁忌部分大量基於JavaScript和Ajax的交互式少。 不過,我相信他們是在不同的Web開發項目和大量的市場,他們非常有用。 讀者可以看到,外觀和感覺一個Roo的創建應用程序可以完全改變,以滿足任何UI /網頁設計要求。 此代碼示例創建Spring Roo的1.1.0.M1。
以上翻譯:
http://viralpatel.net/blogs/2011/02/spring-roo-customizing-web-mvc-ui-forms.html
其他參考:
http://viralpatel.net/blogs/2011/02/spring-roo-save-read-blob-object-spring-roo-tutorial.html
http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html
Spring 3.0新增特性與功能前瞻
Java SE與Java EE支持
現在的Spring Framework基於Java 5,並且完全支持Java 6。而且,它兼容J2EE 1.4及Java EE 5,同時還引入了一些對Java EE 6的早期支持。
1、Java 5
為了利用Java 5特性,例如泛型、可變參數和其他語言改進,整個框架的代碼都被修改過了。我們盡可能地保證代碼能夠向后兼容。我們現在一致使用的泛型 Collection和Map,一致使用泛型FactoryBean,並且在Spring AOP API中有一致的橋接方法解析。泛型ApplicationListener只會自動接收特定的事件類型。所有的回調接口,例如 TransactionCallback和HibernateCallback,可以聲明泛型結果值了。總而言之,Spring的核心代碼經過了徹底的修 改,並為Java 5做了優化。
為了與Java 5的java.util.concurrent機制緊密結合,Spring的TaskExecutor抽象也被修改過了。我們為Callable和 Future提供了一流的支持,還有ExecutorService適配器、ThreadFactory集成等等。這些特性都盡可能與JSR- 236(Concurrency Utilities for Java EE 6)保持一致。此外,針對通過新的@Async注解(或者EJB 3.1的@Asynchronous注解)進行異步方法調用,我們也提供了相應的支持。
2、改進的文檔
Spring的參考文檔也不斷被更新着,這樣它才能完整地反映Spring 3.0的變化和新特性。盡管我們進了一切努力不在文檔中犯錯,但還是有些漏網之魚。如果你發現了一些拼寫錯誤或者更嚴重的錯誤,並能在午餐時擠出點時間的 話,請將這些錯誤告訴Spring團隊,提個事件 就可以了。
3、新的入門教程
現在有了一份新的開發基礎Spring 3.0 MVC Web應用程序的教程。這個教程是一份獨立的文檔,你能在Spring Documentation 頁面中找到它。
注意:要到Spring 3.0正式發布時才能獲得該文檔。
4、新的模塊組織結構和構建系統
我們修改了框架的模塊,並用每個模塊jar一棵源碼樹的方式分別進行管理:
• org.springframework.aop
• org.springframework.beans
• org.springframework.context
• org.springframework.context.support
• org.springframework.expression
• org.springframework.instrument
從Spring Web Flow 2.0開始,我們使用了新的Spring構建系統。這給了我們:
◆基於Ivy的"Spring Build"系統
◆一致的部署過程
◆一致的依賴管理方式
◆一致的OSGi Manifest生成方式
5、新特性概述
以下是Spring 3.0新特性的列表,我們稍后會更詳細地介紹它們。
◆Spring Expression Language
◆IoC增強 / 基於Java的Bean元數據
◆從Spring Web Services遷移過來的對象 / XML映射功能(OXM)
◆全面的REST支持
◆更多@MVC注解
◆聲明式模型驗證
◆Java EE 6早期支持
◆嵌入式數據庫支持
針對Java 5的核心API更新
BeanFactory接口會盡可能地返回確定類型的Bean實例:
◆T getBean(String name, Class requiredType)
◆Map getBeansOfType(Class type)
Spring的TaskExecutor接口現在擴展了java.util.concurrent.Executor接口:
擴展了的AsyncTaskExecutor支持帶Future的標准Callable
新的基於Java 5的轉換器API和SPI:
◆無狀態的ConversionService和Converter
◆取代標准JDK PropertyEditor
指定類型的ApplicationListener
Spring Expression Language
Spring引入了一種表達式語言,它在語法上很像Unified EL,但提供了更多功能。在定義XML和基於注解的Bean定義的時候,可以使用該表達式語言,此外,它也是Spring Portfolio中表達式語言支持的基礎。該功能的詳細信息請參考Spring Expression Language(SpEL)一章。
Spring Expression Language為Spring社區提供了一種能在所有Spring Portfolio產品中使用的、有良好支持的表達式語言。它的語言特性是由Spring Portfolio中項目的需求來驅動的,其中也包含工具的需求,例如,在基於Eclipse的SpringSource Tool Suite中的代碼補全支持。
下面是一個例子,演示了如何用它來配置數據庫屬性。
<bean class="mycompany.RewardsTestDatabase">
<property name="databaseName"
value="#{systemProperties.databaseName}"/>
<property name="keyGenerator"
value="#{strategyBean.databaseKeyGenerator}"/>
bean>
如果你更喜歡用注解來配置你的組件,該功能也同樣適用:
@Repository
public class RewardsTestDatabase {
@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { … }
@Value("#{strategyBean.databaseKeyGenerator}")
public voidsetKeyGenerator(KeyGenerator kg) { … }
}
控制反轉(Inversion of Control,IoC)容器
基於Java的Bean元數據
如今,Java Config項目中的一些核心特性已經被添加到了Spring Framework項目中,這意味着現在Spring直接支持下面的這些注解了:
◆@Configuration
◆@Bean
◆@Primary
◆@Lazy
◆@Import
◆@Value
以下是一個Java類使用新JavaConfig特性提供基本配置的例子:
@Configuration
public class AppConfig{
private @Value("#{jdbcProperties.url}") String jdbcUrl;
private @Value("#{jdbcProperties.username}") String username;
private @Value("#{jdbcProperties.password}") String password;
@Bean
public FooService fooService() {
return new FooServiceImpl(fooRepository());
}
@Bean
public FooRepository fooRepository() {
return new HibernateFooRepository(sessionFactory());
}
@Bean
public SessionFactory sessionFactory() {
// wire up a session factory
AnnotationSessionFactoryBean asFactoryBean =
new AnnotationSessionFactoryBean();
asFactoryBean.setDataSource(dataSource());
// additional config
return asFactoryBean.getObject();
}
@Bean
public DataSource dataSource() {
return new DriverManagerDataSource(jdbcUrl, username, password);
}
}
要讓上面的代碼運行起來,你需要將如下組件掃描配置加入應用程序上下文XML文件中
<context:component-scan
base-package="com.myco.config"/>
在組件中定義Bean元數據
Spring組件中也同樣支持添加了@Bean注解的方法,它們為容器提供了一個工廠Bean。
數據層
對象 / XML映射功能(OXM)已經從Spring Web Services項目遷移到核心Spring Framework中了,可以在org.springframework.oxm包中找到它。
Web層
Web層中最令人興奮的新特性莫過於對構建RESTful Web服務和Web應用程序的支持了。此外,還有一些用於Web應用程序中的新注解。
全面的RESTful支持
通過對現有的注解驅動MVC Web框架的擴展,Spring Framework提供了構建RESTful應用程序的服務器端支持。客戶端的支持則由RestTemplate類提供,它和JdbcTemplate、 JmsTemplate這些模板類非常類似。無論是服務器端還是客戶端的REST功能,都使用了HttpConverter來簡化對象與對應的HTTP請 求/應答中的表述的轉換。
MarshallingHttpMessageConverter用到了之前提到的OXM功能。
更多@MVC注解
新增了幾個注解,例如@CookieValue和@RequestHeaders。詳見"使用@CookieValue注解映射Cookie值"和"用@RequestHeader注解映射請求頭屬性"。
聲明式模型驗證
Hibernate Validator,JSR303
進行中,未包括在Spring 3.0 M3中。
Java EE 6早期支持
我們提供了對使用@Async注解(或EJB 3.1的@Asynchronous注解)進行異步方法調用的支持,還支持JSF 2.0、JPA 2.0等。
進行中,未包括在Spring 3.0 M3中。
支持嵌入式數據庫
目前已經提供了對嵌入式Java數據庫引擎的支持,包括HSQL、H2和Derby。
【編輯推薦】