В этой статье показано, как интегрировать технологии JSF2, PrimeFaces3, Spring3 и Hibernate4. Он предоставляет общий шаблон проекта для разработчиков Java.
Также, если Spring не используется для уровня доступа к бизнесу и данным, может быть предложен проект интеграции JSF-PrimeFaces & Hibernate.
Используемые технологии:
- JDK 1.6.0_31
- Весна 3.1.1
- JSF 2.1
- Hibernate 4.1.0
- Primefaces 3.1.1
- MySQL, Connector 5.1.17
- MySQL 5.5.8
- c3p0 0.9.1.2
- Tomcat 7.0
- Maven 3.0.2
ШАГ 1: СОЗДАТЬ MAVEN ПРОЕКТ
Maven проект создается как показано ниже. (Его можно создать с помощью Maven или IDE Plug-in).
ШАГ 2: СОЗДАТЬ ТАБЛИЦУ ПОЛЬЗОВАТЕЛЯ
Новая таблица USER создается с помощью следующего скрипта:
1
2
3
4
5
6
|
CREATE TABLE USER ( id int(11) NOT NULL, name varchar(45) NOT NULL, surname varchar(45) NOT NULL, PRIMARY KEY (`id`) ); |
ШАГ 3: БИБЛИОТЕКИ
В pom.xml Maven добавлены зависимости Spring, JSF, Hibernate, Primefaces, MySQL и c3p0.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
< properties > < spring.version >3.1.1.RELEASE</ spring.version > </ properties > < dependencies > <!-- Spring 3 dependencies --> < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-core</ artifactId > < version >${spring.version}</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-context</ artifactId > < version >${spring.version}</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-web</ artifactId > < version >${spring.version}</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-tx</ artifactId > < version >${spring.version}</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-orm</ artifactId > < version >${spring.version}</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-test</ artifactId > < version >${spring.version}</ version > </ dependency > <!-- JSF dependencies --> < dependency > < groupId >com.sun.faces</ groupId > < artifactId >jsf-api</ artifactId > < version >2.1.6</ version > </ dependency > < dependency > < groupId >com.sun.faces</ groupId > < artifactId >jsf-impl</ artifactId > < version >2.1.6</ version > </ dependency > < dependency > < groupId >javax.servlet</ groupId > < artifactId >jstl</ artifactId > < version >1.2</ version > </ dependency > <!-- Primefaces dependency --> < dependency > < groupId >org.primefaces</ groupId > < artifactId >primefaces</ artifactId > < version >3.1.1</ version > </ dependency > <!-- Hibernate dependencies --> < dependency > < groupId >org.hibernate</ groupId > < artifactId >hibernate-core</ artifactId > < version >4.1.0.Final</ version > </ dependency > < dependency > < groupId >javassist</ groupId > < artifactId >javassist</ artifactId > < version >3.12.1.GA</ version > </ dependency > <!-- MySQL Java Connector dependency --> < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >5.1.17</ version > </ dependency > <!-- c3p0 dependency --> < dependency > < groupId >c3p0</ groupId > < artifactId >c3p0</ artifactId > < version >0.9.1.2</ version > </ dependency > </ dependencies > |
ШАГ 4: СОЗДАЙТЕ КЛАСС МОДЕЛИ ПОЛЬЗОВАТЕЛЯ
Новый класс модели пользователя создан.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
package com.otv.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * * User Entity * * @author onlinetechvision.com * @since 25 Mar 2012 * @version 1.0.0 * */ @Entity @Table (name= "USER" ) public class User { private int id; private String name; private String surname; /** * Get User Id * * @return int - User Id */ @Id @Column (name= "ID" , unique = true , nullable = false ) public int getId() { return id; } /** * Set User Id * * @param int - User Id */ public void setId( int id) { this .id = id; } /** * Get User Name * * @return String - User Name */ @Column (name= "NAME" , unique = true , nullable = false ) public String getName() { return name; } /** * Set User Name * * @param String - User Name */ public void setName(String name) { this .name = name; } /** * Get User Surname * * @return String - User Surname */ @Column (name= "SURNAME" , unique = true , nullable = false ) public String getSurname() { return surname; } /** * Set User Surname * * @param String - User Surname */ public void setSurname(String surname) { this .surname = surname; } @Override public String toString() { StringBuffer strBuff = new StringBuffer(); strBuff.append( "id : " ).append(getId()); strBuff.append( ", name : " ).append(getName()); strBuff.append( ", surname : " ).append(getSurname()); return strBuff.toString(); } } |
ШАГ 5: СОЗДАЙТЕ ПОЛЬЗОВАТЕЛЬСКИЙ БИНО-КЛАСС
Управляемый пользовательский компонент создан.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
|
package com.otv.managed.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import org.springframework.dao.DataAccessException; import com.otv.model.User; import com.otv.user.service.IUserService; /** * * User Managed Bean * * @author onlinetechvision.com * @since 25 Mar 2012 * @version 1.0.0 * */ @ManagedBean (name= "userMB" ) @RequestScoped public class UserManagedBean implements Serializable { private static final long serialVersionUID = 1L; private static final String SUCCESS = "success" ; private static final String ERROR = "error" ; //Spring User Service is injected... @ManagedProperty (value= "#{UserService}" ) IUserService userService; List<User> userList; private int id; private String name; private String surname; /** * Add User * * @return String - Response Message */ public String addUser() { try { User user = new User(); user.setId(getId()); user.setName(getName()); user.setSurname(getSurname()); getUserService().addUser(user); return SUCCESS; } catch (DataAccessException e) { e.printStackTrace(); } return ERROR; } /** * Reset Fields * */ public void reset() { this .setId( 0 ); this .setName( "" ); this .setSurname( "" ); } /** * Get User List * * @return List - User List */ public List<User> getUserList() { userList = new ArrayList<User>(); userList.addAll(getUserService().getUsers()); return userList; } /** * Get User Service * * @return IUserService - User Service */ public IUserService getUserService() { return userService; } /** * Set User Service * * @param IUserService - User Service */ public void setUserService(IUserService userService) { this .userService = userService; } /** * Set User List * * @param List - User List */ public void setUserList(List<User> userList) { this .userList = userList; } /** * Get User Id * * @return int - User Id */ public int getId() { return id; } /** * Set User Id * * @param int - User Id */ public void setId( int id) { this .id = id; } /** * Get User Name * * @return String - User Name */ public String getName() { return name; } /** * Set User Name * * @param String - User Name */ public void setName(String name) { this .name = name; } /** * Get User Surname * * @return String - User Surname */ public String getSurname() { return surname; } /** * Set User Surname * * @param String - User Surname */ public void setSurname(String surname) { this .surname = surname; } } |
ШАГ 6: СОЗДАТЬ IUserDAO ИНТЕРФЕЙС
Интерфейс IUserDAO предоставляет методы уровня доступа к данным. Уровень доступа к данным управляет всей логикой для сохранения и извлечения данных из базы данных.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
package com.otv.user.dao; import java.util.List; import com.otv.model.User; /** * * User DAO Interface * * @author onlinetechvision.com * @since 25 Mar 2012 * @version 1.0.0 * */ public interface IUserDAO { /** * Add User * * @param User user */ public void addUser(User user); /** * Update User * * @param User user */ public void updateUser(User user); /** * Delete User * * @param User user */ public void deleteUser(User user); /** * Get User * * @param int User Id */ public User getUserById( int id); /** * Get User List * */ public List<User> getUsers(); } |
ШАГ 7: СОЗДАТЬ UserDAO CLASS
Класс UserDAO создается путем реализации интерфейса IUserDAO.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
package com.otv.user.dao; import java.util.List; import com.otv.model.User; import org.hibernate.SessionFactory; /** * * User DAO * * @author onlinetechvision.com * @since 25 Mar 2012 * @version 1.0.0 * */ public class UserDAO implements IUserDAO { private SessionFactory sessionFactory; /** * Get Hibernate Session Factory * * @return SessionFactory - Hibernate Session Factory */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * Set Hibernate Session Factory * * @param SessionFactory - Hibernate Session Factory */ public void setSessionFactory(SessionFactory sessionFactory) { this .sessionFactory = sessionFactory; } /** * Add User * * @param User user */ @Override public void addUser(User user) { getSessionFactory().getCurrentSession().save(user); } /** * Delete User * * @param User user */ @Override public void deleteUser(User user) { getSessionFactory().getCurrentSession().delete(user); } /** * Update User * * @param User user */ @Override public void updateUser(User user) { getSessionFactory().getCurrentSession().update(user); } /** * Get User * * @param int User Id * @return User */ @Override public User getUserById( int id) { List list = getSessionFactory().getCurrentSession() .createQuery( "from User where id=?" ) .setParameter( 0 , id).list(); return (User)list.get( 0 ); } /** * Get User List * * @return List - User list */ @Override public List<User> getUsers() { List list = getSessionFactory().getCurrentSession().createQuery( "from User" ).list(); return list; } } |
ШАГ 8: СОЗДАЙТЕ ИНТЕРФЕЙС IUserService
Интерфейс IUserService предоставляет методы для обработки бизнес-логики.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
package com.otv.user.service; import java.util.List; import com.otv.model.User; /** * * User Service Interface * * @author onlinetechvision.com * @since 25 Mar 2012 * @version 1.0.0 * */ public interface IUserService { /** * Add User * * @param User user */ public void addUser(User user); /** * Update User * * @param User user */ public void updateUser(User user); /** * Delete User * * @param User user */ public void deleteUser(User user); /** * Get User * * @param int User Id */ public User getUserById( int id); /** * Get User List * * @return List - User list */ public List<User> getUsers(); } |
ШАГ 9: СОЗДАНИЕ КЛАССА UserService
Класс UserService создается путем реализации интерфейса IUserService.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package com.otv.user.service; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.otv.model.User; import com.otv.user.dao.IUserDAO; /** * * User Service * * @author onlinetechvision.com * @since 25 Mar 2012 * @version 1.0.0 * */ @Transactional (readOnly = true ) public class UserService implements IUserService { // UserDAO is injected... IUserDAO userDAO; /** * Add User * * @param User user */ @Transactional (readOnly = false ) @Override public void addUser(User user) { getUserDAO().addUser(user); } /** * Delete User * * @param User user */ @Transactional (readOnly = false ) @Override public void deleteUser(User user) { getUserDAO().deleteUser(user); } /** * Update User * * @param User user */ @Transactional (readOnly = false ) @Override public void updateUser(User user) { getUserDAO().updateUser(user); } /** * Get User * * @param int User Id */ @Override public User getUserById( int id) { return getUserDAO().getUserById(id); } /** * Get User List * */ @Override public List<User> getUsers() { return getUserDAO().getUsers(); } /** * Get User DAO * * @return IUserDAO - User DAO */ public IUserDAO getUserDAO() { return userDAO; } /** * Set User DAO * * @param IUserDAO - User DAO */ public void setUserDAO(IUserDAO userDAO) { this .userDAO = userDAO; } } |
ШАГ 10: СОЗДАТЬ applicationContext.xml
Контент Spring Application Context выглядит следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
xsi:schemaLocation="http://www.springframework.org/schema/beans <!-- Beans Declaration --> < bean id = "User" class = "com.otv.model.User" /> <!-- User Service Declaration --> < bean id = "UserService" class = "com.otv.user.service.UserService" > < property name = "userDAO" ref = "UserDAO" /> </ bean > <!-- User DAO Declaration --> < bean id = "UserDAO" class = "com.otv.user.dao.UserDAO" > < property name = "sessionFactory" ref = "SessionFactory" /> </ bean > <!-- Data Source Declaration --> < bean id = "DataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method = "close" > < property name = "driverClass" value = "com.mysql.jdbc.Driver" /> < property name = "jdbcUrl" value = "jdbc:mysql://localhost:3306/Test" /> < property name = "user" value = "root" /> < property name = "password" value = "root" /> < property name = "maxPoolSize" value = "10" /> < property name = "maxStatements" value = "0" /> < property name = "minPoolSize" value = "5" /> </ bean > <!-- Session Factory Declaration --> < bean id = "SessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean" > < property name = "dataSource" ref = "DataSource" /> < property name = "annotatedClasses" > < list > < value >com.otv.model.User</ value > </ list > </ property > < property name = "hibernateProperties" > < props > < prop key = "hibernate.dialect" >org.hibernate.dialect.MySQLDialect</ prop > < prop key = "hibernate.show_sql" >true</ prop > </ props > </ property > </ bean > <!-- Enable the configuration of transactional behavior based on annotations --> < tx:annotation-driven transaction-manager = "txManager" /> <!-- Transaction Manager is defined --> < bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager" > < property name = "sessionFactory" ref = "SessionFactory" /> </ bean > </ beans > |
ШАГ 11: СОЗДАНИЕ Face-config.xml
Конфигурация JSF показана следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<? xml version = "1.0" encoding = "UTF-8" ?> < faces-config xsi:schemaLocation="http://java.sun.com/xml/ns/javaee version = "2.0" > <!-- JSF and Spring are integrated --> < application > < el-resolver > org.springframework.web.jsf.el.SpringBeanFacesELResolver </ el-resolver > </ application > <!-- configuration of navigation rules --> < navigation-rule > < from-view-id >/pages/index.xhtml</ from-view-id > < navigation-case > < from-outcome >success</ from-outcome > < to-view-id >/pages/success.xhtml</ to-view-id > </ navigation-case > < navigation-case > < from-outcome >error</ from-outcome > < to-view-id >/pages/error.xhtml</ to-view-id > </ navigation-case > </ navigation-rule > </ faces-config > |
ШАГ 12: СОЗДАЙТЕ web.xml
web.xml настроен следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<? xml version = "1.0" encoding = "UTF-8" ?> 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 >OTV_JSF_PrimeFaces_Spring_Hibernate</ display-name > <!-- Spring Context Configuration' s Path definition --> < context-param > < param-name >contextConfigLocation</ param-name > < param-value > /WEB-INF/applicationContext.xml </ param-value > </ context-param > <!-- The Bootstrap listener to start up and shut down Spring's root WebApplicationContext. It is registered to Servlet Container --> < listener > < listener-class > org.springframework.web.context.ContextLoaderListener </ listener-class > </ listener > < listener > < listener-class > org.springframework.web.context.request.RequestContextListener </ listener-class > </ listener > <!-- Project Stage Level --> < context-param > < param-name >javax.faces.PROJECT_STAGE</ param-name > < param-value >Development</ param-value > </ context-param > <!-- Welcome Page --> < welcome-file-list > < welcome-file >/pages/index.xhtml</ welcome-file > </ welcome-file-list > <!-- JSF Servlet is defined to container --> < servlet > < servlet-name >Faces Servlet</ servlet-name > < servlet-class >javax.faces.webapp.FacesServlet</ servlet-class > < load-on-startup >1</ load-on-startup > </ servlet > <!-- Mapping with servlet and url for the http requests. --> < servlet-mapping > < servlet-name >Faces Servlet</ servlet-name > < url-pattern >*.jsf</ url-pattern > </ servlet-mapping > < servlet-mapping > < servlet-name >Faces Servlet</ servlet-name > < url-pattern >*.faces</ url-pattern > </ servlet-mapping > </ web-app > |
ШАГ 13: СОЗДАТЬ index.xhtml
index.xhtml создается следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
< h:head >< title >Welcome to OTV_JSF_Spring_Hibernate_Project</ title ></ h:head > < h:body > < h:form > < table > < tr > < td >< h:outputLabel for = "id" value = "Id : " /></ td > < td >< p:inputText id = "id" value = "#{userMB.id}" > < f:converter converterId = "javax.faces.Integer" /> < p:ajax event = "blur" update = "idMsg" /> </ p:inputText > < p:message id = "idMsg" for = "id" display = "icon" /> </ td > </ tr > < tr > < td >< h:outputLabel for = "name" value = "Name : " /></ td > < td >< p:inputText id = "name" value = "#{userMB.name}" > < f:validateLength minimum = "5" /> < p:ajax event = "blur" update = "nameMsg" /> </ p:inputText > < p:message id = "nameMsg" for = "name" display = "icon" /> </ td > </ tr > < tr > < td >< h:outputLabel for = "surname" value = "Surname : " /></ td > < td >< p:inputText id = "surname" value = "#{userMB.surname}" > < f:validateLength minimum = "5" /> < p:ajax event = "blur" update = "surnameMsg" /> </ p:inputText > < p:message id = "surnameMsg" for = "surname" display = "icon" /> </ td > </ tr > < tr > < td >< p:commandButton id = "addUser" value = "Add" action = "#{userMB.addUser}" ajax = "false" /></ td > < td >< p:commandButton id = "reset" value = "Reset" action = "#{userMB.reset}" ajax = "false" /></ td > </ tr > </ table > </ h:form > </ h:body > </ html > |
ШАГ 14: СОЗДАЙТЕ success.xhtml
success.xhtml создается следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
< h:head > < title >Welcome to OTV_JSF_Spring_Hibernate_Project</ title > </ h:head > < h:body > < h:form > < h:outputText value = "USERs : " ></ h:outputText > < p:dataTable id = "users" var = "user" value = "#{userMB.userList}" style = "width: 10%" > < p:column > < f:facet name = "header" > < h:outputText value = "ID" /> </ f:facet > < h:outputText value = "#{user.id}" /> </ p:column > < p:column > < f:facet name = "header" > < h:outputText value = "Name" /> </ f:facet > < h:outputText value = "#{user.name}" /> </ p:column > < p:column > < f:facet name = "header" > < h:outputText value = "Surname" /> </ f:facet > < h:outputText value = "#{user.surname}" /> </ p:column > </ p:dataTable > </ h:form > </ h:body > </ html > |
ШАГ 15: СОЗДАЙТЕ error.xhtml
error.xhtml создается следующим образом:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
< h:head >< title >Welcome to JSF_PrimeFaces_Spring_Hibernate Project</ title ></ h:head > < body > < f:view > < h:form > < h:outputText value = "Transaction Error has occurred!" ></ h:outputText > </ h:form > </ f:view > </ body > </ html > |
ШАГ 16: ДЕПЛОЙНЫЙ ПРОЕКТ
После развертывания проекта OTV_JSF_Spring_Hibernate на Tomcat страницу индекса можно открыть по следующему URL-адресу:
HTTP: // IP: порт / OTV_JSF_Spring_Hibernate_Project-1,0-ПАНОРАМА / страницы / index.jsf
ШАГ 17: СКАЧАТЬ
- OTV_JSF_Spring_Hibernate
- https://github.com/erenavsarogullari/OTV_JSF_Spring_Hibernate
РЕСУРСЫ :
- Spring Framework Reference 3.1.x Документация
- Документация Hibernate 4.x
- Primefaces 3.x Документация
Ссылка: проект интеграции JSF2 + Primefaces3 + Spring3 и Hibernate4 от нашего партнера по JCG Эрен Авсарогуллари в блоге Online Technology Vision .