Форум программистов, компьютерный форум, киберфорум
Java: Spring, Spring Boot
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.73/11: Рейтинг темы: голосов - 11, средняя оценка - 4.73
1 / 1 / 0
Регистрация: 13.10.2012
Сообщений: 9

GWT+Spring+hibernate! Error 404 :(

30.11.2013, 12:32. Показов 2432. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Уже блин неделю мучаюсь!
Разбираюсь в связке GWT+Spring+Hibernate+Maven.
Со всем вроде ок, просто GWT - работает, страничку грузит, HelloWorld, с отправкой имя на сервер и получения по кнопке сообщения тоже. К Базе Данных(PostsgreSql) тоже подключается (видно в консоли Eclipse), а вот когда пытаюсь отправить запрос к БД вылетает следующее сообщение:
Кликните здесь для просмотра всего текста

Sending request to the server:
1 Name Sname job
Server replies:
An error occurred while attempting to contact the server. Please check your network connection and try again. The error is : com.google.gwt.user.client.rpc.StatusCod eException: 404
HTTP ERROR: 404

NOT_FOUND

RequestURI=/gwtspringtestnomaven/springGwtServices/employeeService

Powered by Jetty://


Уже даже без Мавена попровал сделать, чтобы проверить добавлением\удалением библиотек разные комбинации... Посмотрел все возможные темы на Stackowerflov, и др форумах, на свою проблему ответа не нашел(((

Текст из консоли, при запуске Веб-приложения:

Кликните здесь для просмотра всего текста
ноя 30, 2013 10:05:06 AM org.springframework.web.context.ContextL oader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
ноя 30, 2013 10:05:06 AM org.springframework.context.support.Abst ractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Sat Nov 30 10:05:06 EET 2013]; root of context hierarchy
ноя 30, 2013 10:05:07 AM org.springframework.beans.factory.xml.Xm lBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
ноя 30, 2013 10:05:07 AM org.springframework.context.annotation.C lassPathScanningCandidateComponentProvid er registerDefaultFilters
INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
ноя 30, 2013 10:05:07 AM org.springframework.beans.factory.annota tion.AutowiredAnnotationBeanPostProcesso r <init>
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
ноя 30, 2013 10:05:07 AM org.springframework.beans.factory.suppor t.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.suppor t.DefaultListableBeanFactory@4a0d7146: defining beans [employeeDAO,employeeService,org.springfr amework.context.annotation.internalConfi gurationAnnotationProcessor,org.springfr amework.context.annotation.internalAutow iredAnnotationProcessor,org.springframew ork.context.annotation.internalRequiredA nnotationProcessor,org.springframework.c ontext.annotation.internalCommonAnnotati onProcessor,org.springframework.context. annotation.internalPersistenceAnnotation Processor,org.springframework.aop.config .internalAutoProxyCreator,org.springfram ework.transaction.annotation.AnnotationT ransactionAttributeSource#0,org.springfr amework.transaction.interceptor.Transact ionInterceptor#0,org.springframework.tra nsaction.config.internalTransactionAdvis or,entityManagerFactory,transactionManag er,org.springframework.context.annotatio n.ConfigurationClassPostProcessor$Import AwareBeanPostProcessor#0]; root of factory hierarchy
ноя 30, 2013 10:05:07 AM org.springframework.orm.jpa.LocalEntityM anagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA EntityManagerFactory for persistence unit 'MyPersistenceUnit'
ноя 30, 2013 10:05:09 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
ноя 30, 2013 10:05:09 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.5.Final}
ноя 30, 2013 10:05:09 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
ноя 30, 2013 10:05:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
ноя 30, 2013 10:05:10 AM org.hibernate.service.jdbc.connections.i nternal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.service.jdbc.connections.i nternal.C3P0ConnectionProvider
ноя 30, 2013 10:05:10 AM org.hibernate.service.jdbc.connections.i nternal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: org.postgresql.Driver at URL: jdbcostgresql://localhost:5432/User
ноя 30, 2013 10:05:10 AM org.hibernate.service.jdbc.connections.i nternal.C3P0ConnectionProvider configure
INFO: HHH000046: Connection properties: {user=postgres, password=****, autocommit=true, release_mode=auto}
ноя 30, 2013 10:05:10 AM org.hibernate.service.jdbc.connections.i nternal.C3P0ConnectionProvider configure
INFO: HHH000006: Autocommit mode: true
ноя 30, 2013 10:05:10 AM com.mchange.v2.log.MLog <clinit>
INFO: MLog clients using java 1.4+ standard logging.
ноя 30, 2013 10:05:10 AM com.mchange.v2.c3p0.C3P0Registry banner
INFO: Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
ноя 30, 2013 10:05:10 AM com.mchange.v2.c3p0.impl.AbstractPoolBac kedDataSource getPoolManager
INFO: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource @114c3286 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoo lDataSource@aebbd4c4 [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnecti onTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge1388y1ami4e3no86t8|5ad19ff, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 300, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSou rce@666bcfe5 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1hge1388y1ami4e3no86t8|800e4a9, jdbcUrl -> jdbcostgresql://localhost:5432/User, properties -> {user=******, password=******, autocommit=true, release_mode=auto} ], preferredTestQuery -> null, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 1hge1388y1ami4e3no86t8|1f485a2a, numHelperThreads -> 3 ]
ноя 30, 2013 10:05:11 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
ноя 30, 2013 10:05:11 AM org.hibernate.engine.jdbc.internal.LobCr eatorBuilder useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetExcept ion
ноя 30, 2013 10:05:11 AM org.hibernate.engine.transaction.interna l.TransactionFactoryInitiator initiateService
INFO: HHH000268: Transaction strategy: org.hibernate.engine.transaction.interna l.jdbc.JdbcTransactionFactory
ноя 30, 2013 10:05:11 AM org.hibernate.hql.internal.ast.ASTQueryT ranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: public.employee
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [job, employee_surname, employee_id, employee_name]
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [employee_pkey]
ноя 30, 2013 10:05:11 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
ноя 30, 2013 10:05:11 AM org.springframework.web.context.ContextL oader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 5436 ms


Вот код всего, где я думаю м б ошибка :

Листинг web.xml :
Кликните здесь для просмотра всего текста

XML
1
2
3
4
5
6
7
8
9
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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee">
  
   <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  
  <listener>
 <listener-class>
  org.springframework.web.context.ContextLoaderListener
 </listener-class>
</listener>
<servlet>
 <servlet-name>springGwtRemoteServiceServlet</servlet-name>
 <servlet-class>org.spring4gwt.server.SpringGwtRemoteServiceServlet
 </servlet-class>
 
</servlet>
 
<servlet-mapping>
    
  <servlet-name>springGwtRemoteServiceServlet</servlet-name>
 <url-pattern>/com.javacodegeeks.Gwtspringtestnomaven/springGwtServices/*</url-pattern>
  
</servlet-mapping> 
  
  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>Gwtspringtestnomaven.html</welcome-file>
  </welcome-file-list>
 
</web-app>

ApplicationContex.xml:
Кликните здесь для просмотра всего текста

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:task="http://www.springframework.org/schema/task"
 xsi:schemaLocation="
   [url]http://www.springframework.org/schema/aop[/url] [url]http://www.springframework.org/schema/aop/spring-aop-3.0.xsd[/url]
   [url]http://www.springframework.org/schema/beans[/url] [url]http://www.springframework.org/schema/beans/spring-beans-3.0.xsd[/url]
   [url]http://www.springframework.org/schema/context[/url] [url]http://www.springframework.org/schema/context/spring-context-3.0.xsd[/url]
   [url]http://www.springframework.org/schema/jee[/url] [url]http://www.springframework.org/schema/jee/spring-jee-3.0.xsd[/url]
   [url]http://www.springframework.org/schema/tx[/url] [url]http://www.springframework.org/schema/tx/spring-tx-3.0.xsd[/url]
   [url]http://www.springframework.org/schema/task[/url] http://www.springframework.org/schema/task/spring-task-3.0.xsd">
 
 <context:component-scan base-package="com.javacodegeeks" />
 <tx:annotation-driven />
 
 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
  <property name="persistenceUnitName" value="MyPersistenceUnit" />
 </bean>
 
 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory" />
 </bean>
 
 
</beans>


persistance.xml
Кликните здесь для просмотра всего текста

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
 version="2.0">
 
 <persistence-unit name="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
 
  <properties>
   <property name="hibernate.hbm2ddl.auto" value="update" />
   <property name="hibernate.show_sql" value="false" />
   <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
   <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
   <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/User" />
   <property name="hibernate.connection.username" value="postgres" />
   <property name="hibernate.connection.password" value="1111" />
 
   <property name="hibernate.c3p0.min_size" value="5" />
   <property name="hibernate.c3p0.max_size" value="20" />
   <property name="hibernate.c3p0.timeout" value="300" />
   <property name="hibernate.c3p0.max_statements" value="50" />
   <property name="hibernate.c3p0.idle_test_period" value="3000" />
 
  </properties>
 
 </persistence-unit>
 
</persistence>


Gwtspringtestnomaven.gwt.xml :
Кликните здесь для просмотра всего текста

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?xml version="1.0" encoding="UTF-8"?>
<!--
  When updating your version of GWT, you should also update this DTD reference,
  so that your app can take advantage of the latest GWT module capabilities.
-->
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN"
  "http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">
<module rename-to='gwtspringtestnomaven'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name='com.google.gwt.user.User'/>
 
  <!-- Inherit the default GWT style sheet.  You can change       -->
  <!-- the theme of your GWT application by uncommenting          -->
  <!-- any one of the following lines.                            -->
  <inherits name='com.google.gwt.user.theme.clean.Clean'/>
  <!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/>     -->
 
  <!-- Other module inherits                                      -->
 
  <!-- Specify the app entry point class.                         -->
  <entry-point class='com.javacodegeeks.client.Gwtspringtestnomaven'/>
 
  <!-- Specify the paths for translatable code                    -->
  <source path='client'/>
  <source path='shared'/>
 
</module>


Gwtspringtestnomawen.java:
Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
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
98
99
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package com.javacodegeeks.client;
 
import com.javacodegeeks.shared.dto.EmployeeDTO;
import com.javacodegeeks.shared.services.EmployeeServiceAsync;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
 
 
public class Gwtspringtestnomaven
implements EntryPoint
{
    /**
     * The message displayed to the user when the server cannot be reached or
     * returns an error.
     */
    private static final String SERVER_ERROR = "An error occurred while "
      + "attempting to contact the server. Please check your network "
      + "connection and try again. The error is : ";
   
    /**
     * Create a remote service proxy to talk to the server-side Employee service.
     */
    private final EmployeeServiceAsync employeeService =EmployeeServiceAsync.Util.getInstance();
 
    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {
     final Button saveOrUpdateButton = new Button("SaveOrUpdate");
     final Button retrieveButton = new Button("Retrieve");
     final TextBox employeeInfoField = new TextBox();
     employeeInfoField.setText("2 Employee Info jjjj");
     final TextBox employeeIdField = new TextBox();
     final Label errorLabel = new Label();
     
     // We can add style names to widgets
     saveOrUpdateButton.addStyleName("sendButton");
     retrieveButton.addStyleName("sendButton");
 
     // Add the nameField and sendButton to the RootPanel
     // Use RootPanel.get() to get the entire body element
     RootPanel.get("employeeInfoFieldContainer").add(employeeInfoField);
     RootPanel.get("updateEmployeeButtonContainer").add(saveOrUpdateButton);
     RootPanel.get("employeeIdFieldContainer").add(employeeIdField);
     RootPanel.get("retrieveEmployeeButtonContainer").add(retrieveButton);
     RootPanel.get("errorLabelContainer").add(errorLabel);
 
     // Focus the cursor on the name field when the app loads
     employeeInfoField.setFocus(true);
     employeeInfoField.selectAll();
 
     // Create the popup dialog box
     final DialogBox dialogBox = new DialogBox();
     dialogBox.setText("Remote Procedure Call");
     dialogBox.setAnimationEnabled(true);
     final Button closeButton = new Button("Close");
     // We can set the id of a widget by accessing its Element
     closeButton.getElement().setId("closeButton");
     final Label textToServerLabel = new Label();
     final HTML serverResponseLabel = new HTML();
     VerticalPanel dialogVPanel = new VerticalPanel();
     dialogVPanel.addStyleName("dialogVPanel");
     dialogVPanel.add(new HTML("<b>Sending request to the server:</b>"));
     dialogVPanel.add(textToServerLabel);
     dialogVPanel.add(new HTML("<b>Server replies:</b>"));
     dialogVPanel.add(serverResponseLabel);
     dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
     dialogVPanel.add(closeButton);
     dialogBox.setWidget(dialogVPanel);
 
     // Add a handler to close the DialogBox
     closeButton.addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
       dialogBox.hide();
       saveOrUpdateButton.setEnabled(true);
       saveOrUpdateButton.setFocus(true);
       retrieveButton.setEnabled(true);
      }
     });
 
     // Create a handler for the saveOrUpdateButton and employeeInfoField
     class SaveOrUpdateEmployeeHandler implements ClickHandler, KeyUpHandler {
      /**
       * Fired when the user clicks on the saveOrUpdateButton.
       */
      public void onClick(ClickEvent event) {
       sendEmployeeInfoToServer();
      }
 
      /**
       * Fired when the user types in the employeeInfoField.
       */
      public void onKeyUp(KeyUpEvent event) {
       if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
        sendEmployeeInfoToServer();
       }
      }
 
      /**
       * Send the employee info from the employeeInfoField to the server and wait for a response.
       */
      private void sendEmployeeInfoToServer() {
       // First, we validate the input.
       errorLabel.setText("");
       String textToServer = employeeInfoField.getText();
 
       // Then, we send the input to the server.
       saveOrUpdateButton.setEnabled(false);
       textToServerLabel.setText(textToServer);
       serverResponseLabel.setText("");
 
       String[] employeeInfo = textToServer.split(" ");
       
       long employeeId = Long.parseLong(employeeInfo[0]);
       String employeeName = employeeInfo[1];
       String employeeSurname = employeeInfo[2];
       String employeeJobTitle = employeeInfo[3];
       System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
       System.out.println("String[] = "+employeeInfo);
       System.out.println("employeeId = "+employeeId);
       System.out.println("employeeName = "+employeeName);
       System.out.println("employeeSurname = "+employeeSurname);
       System.out.println("employeeJobTitle = "+employeeJobTitle);
       
       employeeService.saveOrUpdateEmployee(employeeId, employeeName, employeeSurname, employeeJobTitle, 
         new AsyncCallback<Void>() {
          public void onFailure(Throwable caught) {
           // Show the RPC error message to the user
           dialogBox
             .setText("Remote Procedure Call - Failure");
           serverResponseLabel
             .addStyleName("serverResponseLabelError");
           serverResponseLabel.setHTML(SERVER_ERROR + caught.toString());
           dialogBox.center();
           closeButton.setFocus(true);
          }
 
          public void onSuccess(Void noAnswer) {
           dialogBox.setText("Remote Procedure Call");
           serverResponseLabel
             .removeStyleName("serverResponseLabelError");
           serverResponseLabel.setHTML("OK");
           dialogBox.center();
           closeButton.setFocus(true);
          }
         });
      }
     }
     
     // Create a handler for the retrieveButton and employeeIdField
     class RetrieveEmployeeHandler implements ClickHandler, KeyUpHandler {
      /**
       * Fired when the user clicks on the retrieveButton.
       */
      public void onClick(ClickEvent event) {
       sendEmployeeIdToServer();
      }
 
      /**
       * Fired when the user types in the employeeIdField.
       */
      public void onKeyUp(KeyUpEvent event) {
       if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
        sendEmployeeIdToServer();
       }
      }
 
      /**
       * Send the id from the employeeIdField to the server and wait for a response.
       */
      private void sendEmployeeIdToServer() {
       // First, we validate the input.
       errorLabel.setText("");
       String textToServer = employeeIdField.getText();
       System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
       System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!! sendEmployeeIdToServer = "+ textToServer);
       // Then, we send the input to the server.
       retrieveButton.setEnabled(false);
       textToServerLabel.setText(textToServer);
       serverResponseLabel.setText("");
 
       employeeService.findEmployee(Long.parseLong(textToServer),  
         new AsyncCallback<EmployeeDTO>() {
          public void onFailure(Throwable caught) {
           // Show the RPC error message to the user
           dialogBox
             .setText("Remote Procedure Call - Failure");
           serverResponseLabel
             .addStyleName("serverResponseLabelError");
           serverResponseLabel.setHTML(SERVER_ERROR + caught.toString());
           dialogBox.center();
           closeButton.setFocus(true);
          }
 
          public void onSuccess(EmployeeDTO employeeDTO) {
           dialogBox.setText("Remote Procedure Call");
           serverResponseLabel
             .removeStyleName("serverResponseLabelError");
           if(employeeDTO != null)
            serverResponseLabel.setHTML("Employee Information Id : " 
           + employeeDTO.getEmployeeId() + "Name : " + employeeDTO.getEmployeeName() 
           + "Surname : " + employeeDTO.getEmployeeSurname() 
           + " Job Title : " + employeeDTO.getJob());
           else
            serverResponseLabel.setHTML("No employee with the specified id found");
           dialogBox.center();
           closeButton.setFocus(true);
          }
         });
      }
     }
 
     // Add a handler to send the employee info to the server
     SaveOrUpdateEmployeeHandler saveOrUpdateEmployeehandler = new SaveOrUpdateEmployeeHandler();
     saveOrUpdateButton.addClickHandler(saveOrUpdateEmployeehandler);
     employeeInfoField.addKeyUpHandler(saveOrUpdateEmployeehandler);
     
     // Add a handler to send the employee id to the server
     RetrieveEmployeeHandler retrieveEmployeehandler = new RetrieveEmployeeHandler();
     retrieveButton.addClickHandler(retrieveEmployeehandler);
     employeeIdField.addKeyUpHandler(retrieveEmployeehandler);
    }


EmployeeService.java
Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.javacodegeeks.shared.services;
 
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
 
import com.javacodegeeks.shared.dto.EmployeeDTO;
 
@RemoteServiceRelativePath("springGwtServices/employeeService")
public interface EmployeeService extends RemoteService {
 
 public EmployeeDTO findEmployee(long employeeId);
 public void saveEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception;
 public void updateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception;
 public void saveOrUpdateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception;
 public void deleteEmployee(long employeeId) throws Exception;
 
}


EmployeeServiceAsync.java:
Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
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
package com.javacodegeeks.shared.services;
 
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
 
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.javacodegeeks.shared.dto.EmployeeDTO;
 
public interface EmployeeServiceAsync {
 
 
    void deleteEmployee(long employeeId, AsyncCallback<Void> callback);
 
    void findEmployee(long employeeId, AsyncCallback<EmployeeDTO> callback);
 
    void saveEmployee(long employeeId, String name, String surname,
        String jobDescription, AsyncCallback<Void> callback);
 
    void saveOrUpdateEmployee(long employeeId, String name, String surname,
        String jobDescription, AsyncCallback<Void> callback);
 
    void updateEmployee(long employeeId, String name, String surname,
        String jobDescription, AsyncCallback<Void> callback);
 
    public static final class Util
    {
    private static EmployeeServiceAsync instance;
    public static final EmployeeServiceAsync getInstance()
    {
    if ( instance == null )
    {
    instance = (EmployeeServiceAsync) GWT.create( EmployeeService.class );
 
    ServiceDefTarget target = (ServiceDefTarget) instance;
    target.setServiceEntryPoint( GWT.getModuleBaseURL() + "springGwtServices/employeeService " );
 
    }
    return instance;
    }
    private Util()
    {
    // Utility class should not be instanciated
    }
    }
    
}


EmployeeServiceImpl.java:
Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
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
package com.javacodegeeks.server.services; 
 
import javax.annotation.PostConstruct; 
import javax.annotation.PreDestroy; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Propagation; 
import org.springframework.transaction.annotation.Transactional; 
 
import com.javacodegeeks.server.dao.EmployeeDAO;
import com.javacodegeeks.shared.dto.EmployeeDTO;
import com.javacodegeeks.shared.services.EmployeeService;
 
@Service("employeeService") 
public class EmployeeServiceImpl implements EmployeeService { 
  
    
 @Autowired 
 private EmployeeDAO employeeDAO; 
 
 @PostConstruct 
 public void init() throws Exception { 
 } 
  
 @PreDestroy 
 public void destroy() { 
 } 
 
 public EmployeeDTO findEmployee(long employeeId) { 
  
  return employeeDAO.findById(employeeId); 
   
 } 
  
 @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
 public void saveEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception { 
  EmployeeDTO employeeDTO = employeeDAO.findById(employeeId); 
   
  if(employeeDTO == null) { 
   employeeDTO = new EmployeeDTO(employeeId, name,surname, jobDescription); 
   employeeDAO.persist(employeeDTO); 
  } 
   
 } 
  
 @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
 public void updateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception { 
   
  EmployeeDTO employeeDTO = employeeDAO.findById(employeeId); 
   
  if(employeeDTO != null) { 
   employeeDTO.setEmployeeName(name); 
   employeeDTO.setEmployeeSurname(surname); 
   employeeDTO.setJob(jobDescription); 
  } 
 
 } 
  
 @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
 public void deleteEmployee(long employeeId) throws Exception { 
   
  EmployeeDTO employeeDTO = employeeDAO.findById(employeeId); 
   
  if(employeeDTO != null) 
   employeeDAO.remove(employeeDTO); 
 
 } 
  
 @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
 public void saveOrUpdateEmployee(long employeeId, String name, String surname, String jobDescription) throws Exception { 
   System.out.println("into SaveOrUpdate");
  EmployeeDTO employeeDTO = new EmployeeDTO(employeeId, name,surname, jobDescription); 
  System.out.println("SaveOrUpdate good");
  employeeDAO.merge(employeeDTO); 
  System.out.println(" SaveOrUpdate out"); 
 } 
 
}


Gwtspringtestnomaven.html:
Кликните здесь для просмотра всего текста

HTML5
1
2
3
4
5
6
7
8
9
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
<!doctype html>
<!-- The DOCTYPE declaration above will set the     -->
<!-- browser's rendering engine into                -->
<!-- "Standards Mode". Replacing this declaration   -->
<!-- with a "Quirks Mode" doctype is not supported. -->
 
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 
    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="Gwtspringtestnomaven.css">
 
    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title>Web Application Starter Project</title>
    
    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript"language="javascript" <!-- здесь кст пишет :Attribute (language) is obsolete. Its use is discouraged in HTML5 documents. -->
 src="gwtspringtestnomaven/gwtspringtestnomaven.nocache.js"></script>
  </head>
 
  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
  <body>
 
    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
    
    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
      <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.
      </div>
    </noscript>
 
    <h1>Web Application Starter Project</h1>
 
   <table align="center">
      <tr>
        <td colspan="2" style="font-weight:bold;">Please enter employee info (id name surname job):</td>        
      </tr>
      <tr>
        <td id="employeeInfoFieldContainer"></td>
        <td id="updateEmployeeButtonContainer"></td>
      </tr>
      <tr>
      <tr>
        <td colspan="2" style="font-weight:bold;">Please enter employee id:</td>        
      </tr>
      <tr>
        <td id="employeeIdFieldContainer"></td>
        <td id="retrieveEmployeeButtonContainer"></td>
      </tr>
      <tr>
        <td colspan="2" style="color:red;" id="errorLabelContainer"></td>
      </tr>
    </table>
  </body>
</html>


Очень жду помощи!!!! Спасибо!!
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
30.11.2013, 12:32
Ответы с готовыми решениями:

Не компилируется gwt spring hibernate
Пытаюсь интегрировать в gwt - spring и hibernate по этому примеру...

Spring+hibernate+GWT+RCP+ant
Что нужно сделать? Запрограммировать систему &quot;Электронная школа&quot;, а именно: 1) при переходе на страницу проекта в браузере должна...

Spring Project + Hibernate. root-context.xml - 404 ошибка
Подскажите пожалуйста с чем это может быть св&quot;язано. Когда рут-контекст чистый, то контроллер нормально запускает и приложение работает. Но...

4
21 / 19 / 4
Регистрация: 05.06.2013
Сообщений: 190
30.11.2013, 17:37
Жаль, но не дождёшься попробуй воспользоваться stackoverflow.com
0
1 / 1 / 0
Регистрация: 13.10.2012
Сообщений: 9
30.11.2013, 17:58  [ТС]
Та сегодня там тоже уже создал вопрос, жду...
Уверен там какая-то мелочь, а я парюсь уже так долго(((
А все похожие посты, не помогают решить мою проблему(
0
21 / 19 / 4
Регистрация: 05.06.2013
Сообщений: 190
30.11.2013, 18:21
Да, бывает. Всем влом разбираться с такой большой проблемой.
0
1 / 1 / 0
Регистрация: 13.10.2012
Сообщений: 9
03.12.2013, 01:46  [ТС]
Я нашел ошибку!!

нужно в web.xml писать не

XML
1
2
<servlet-name>springGwtRemoteServiceServlet</servlet-name>
 <url-pattern>/com.javacodegeeks.Gwtspringtestnomaven/springGwtServices/*</url-pattern>
а,
XML
1
2
<servlet-name>springGwtRemoteServiceServlet</servlet-name>
 <url-pattern>/gwtspringtestnomaven/springGwtServices/*</url-pattern>
gwtspringtestnomaven - имя из файла .gwt.xml
может кому-нибудь, когда-то поможет)
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
03.12.2013, 01:46
Помогаю со студенческими работами здесь

Spring + Hibernate | Error creating bean with name 'sessionFactory'
Относительно недавно начал изучение Java. При создании веб-приложения при помощи Sprng'а и Hibirnate выскакивает ошибка, хотя делал по...

Spring MVC. 404 ошибка при включении Spring Data JPA в проект
Добрый день. Есть простой шаблонный проект с использованием Spring MVC и Maven. С зависимостями Spring MVC проект собирается нормально и...

Spring MVC + GWT
Есть задача, слить два этих фреймворка. Пока необходимо хотя бы сделать так, что бы на одной странице была JSP страница которая...

Помогите: сслыка на роботс в выдаче и старая ошибка 404 в GWT
Доброе время суток всем. Помогите пожалуйста, посоветуйте по парочке вопросов. Гугл по запросу site:www.mydomain.com выдает кроме...

Spring + Hibernate
Вообщем решил изучить Java, Spring, Hibernate. Запили основу, но вот постоянно выскакивает, не знаю как её поправить... Ошибка: ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru