Форум программистов, компьютерный форум, киберфорум
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. Показов 2478. Ответов 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
Ответ Создать тему
Новые блоги и статьи
Доступность команды формы по условию
Maks 07.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: сделать доступной кнопку (команда формы "ЗавершитьСписание") при. . .
Уведомление о неверно выбранном значении справочника
Maks 06.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "НарядПутевка", разработанного в конфигурации КА2. Задача: уведомлять пользователя, если в документе выбран неверный склад. . .
Установка Qt Creator для C и C++: ставим среду, CMake и MinGW без фреймворка Qt
8Observer8 05.04.2026
Среду разработки Qt Creator можно установить без фреймворка Qt. Есть отдельный репозиторий для этой среды: https:/ / github. com/ qt-creator/ qt-creator, где можно скачать установщик, на вкладке Releases:. . .
AkelPad-скрипты, структуры, и немного лирики..
testuser2 05.04.2026
Такая программа, как AkelPad существует уже давно, и также давно существуют скрипты под нее. Тем не менее, прога живет, периодически что-то не спеша дополняется, улучшается. Что меня в первую очередь. . .
Отображение реквизитов в документе по условию и контроль их заполнения
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеСпецтехники", разработанного в конфигурации КА2. Данный документ берёт данные из другого нетипового документа. . .
Фото всей Земли с борта корабля Orion миссии Artemis II
kumehtar 04.04.2026
Это первое подобное фото сделанное человеком за 50 лет. Снимок называют новым вариантом легендарной фотографии «The Blue Marble» 1972 года, сделанной с борта корабля «Аполлон-17». Новое фото. . .
Вывод диалогового окна перед закрытием, если документ не проведён
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: реализовать программный контроль на предмет проведения документа. . .
Программный контроль заполнения реквизитов табличной части документа
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: 1. Реализовать контроль заполнения реквизита. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru