1

我看到了有关 GWT + SPRING + HIBERNATE 集成的问题,但没有一个是明确的或最新的当前版本!如果有人有一个清晰简单的集成示例(表单提交和保存在数据库中),我将非常感激!如果你能把这个简单的项目放在一个 ZIP 中并上传它(用它的 jars 会很棒)谢谢!

4

2 回答 2

2

我猜这个使用gwt 2.5.0-rc1Spring 3.1.2.RELEASEHibernate 4会有所帮助。这个项目正在使用maven,所以安装 maven 它将处理所需的依赖项。git clone它,命令行构建$ mvn clean install潜入。

基本的 gwt 服务器-共享-客户端架构是

实体

@Entity
@Table(name = "TBL_BOOK")
public class Book implements Serializable {

    private static final long serialVersionUID = -687874117917352477L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;

    @Column(name = "TITLE", nullable = false)
    private String title;

    @Column(name = "SUBTITLE")
    private String subtitle;

    @Column(name = "AUTOR", nullable = false)
    private String autor;

    @Column(name = "DESCRIPTION")
    private String description;

    @Column(name = "ISBN")
    private String isbn;

    @Column(name = "GENRE")
    private String genre;

    @Temporal(TemporalType.DATE)
    @Column(name = "PUBLISHED_DATE")
    private Date publishedDate;

    @Column(name = "PUBLISHER")
    private String publisher;

    public Book() {
    }

    public Book(Long id, String title, String subtitle, String autor,
            String description, String isbn, String genre, Date publishedDate,
            String publisher) {
        this.id = id;
        this.title = title;
        this.subtitle = subtitle;
        this.autor = autor;
        this.description = description;
        this.isbn = isbn;
        this.genre = genre;
        this.publishedDate = publishedDate;
        this.publisher = publisher;
    }

    public Book(Book bookDTO) {
        this.id = bookDTO.getId();
        this.title = bookDTO.getTitle();
        this.subtitle = bookDTO.getSubtitle();
        this.autor = bookDTO.getAutor();
        this.description = bookDTO.getDescription();
        this.isbn = bookDTO.getIsbn();
        this.genre = bookDTO.getGenre();
        this.publishedDate = bookDTO.getPublishedDate();
        this.publisher = bookDTO.getPublisher();
    }
    //getters and setters

    @Override
    public String toString() {
        return "Book [id=" + id + ", title=" + title + ", subtitle=" + subtitle
                + ", author=" + autor + ", description=" + description
                + ", isbn=" + isbn + ", genre=" + genre + ", publishedDate="
                + publishedDate + ", publisher=" + publisher + "]";
    }

}

网页配置

<!-- SpringGwt remote service servlet -->
    <servlet>
        <servlet-name>springGwtRemoteServiceServlet</servlet-name>
        <servlet-class>org.spring4gwt.server.SpringGwtRemoteServiceServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>springGwtRemoteServiceServlet</servlet-name>
        <url-pattern>/GwtSpringHibernate/springGwtServices/*</url-pattern>
    </servlet-mapping>

RPC 的客户端存根

/**
 * The client side stub for the RPC service.
 */
@RemoteServiceRelativePath("springGwtServices/bookService")
public interface BookService extends RemoteService {

    public void saveOrUpdate(Book book) throws Exception;

    public void delete(Book book) throws Exception;

    public Book find(long id);

    public List<Book> findAllEntries();

}

服务器

@Service("bookService")
public class BookServiceImpl extends RemoteServiceServlet implements BookService {

    private static final long serialVersionUID = -6547737229424190373L;

    private static final Log LOG = LogFactory.getLog(BookServiceImpl.class);

    @Autowired
    private BookDAO bookDAO;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveOrUpdate(Book book) throws Exception {
                //
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void delete(Book book) throws Exception {
           //
    }

    public Book find(long id) {
        return bookDAO.findById(id);
    }

    public List<Book> findAllEntries() {
        //
    }

}

客户视图

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GwtSpringHibernate 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.";

    /**
     * Create a remote service proxy to talk to the server-side Book service.
     */
    private final BookServiceAsync bookService = GWT.create(BookService.class);

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        DateBox.DefaultFormat defaultFormatter = new DateBox.DefaultFormat(DateTimeFormat.getFormat("dd.MM.yyyy"));

        // Add new Book Area
        final TextBox titleField = new TextBox();
        titleField.setFocus(true);

        final TextBox subtitleField = new TextBox();
        final TextBox autorField = new TextBox();
        final TextBox descriptionField = new TextBox();
        final TextBox isbnField = new TextBox();
        final TextBox genreField = new TextBox();

        final DateBox publishedDateField = new DateBox();
        publishedDateField.setFormat(defaultFormatter);

        final TextBox publisherField = new TextBox();

        final Button saveButton = new Button("Save");
        saveButton.addStyleName("button");

        final Button retrieveButton = new Button("Retrieve");
        retrieveButton.addStyleName("button");

        final Label errorLabel = new Label();

        // Add fields to the Rootpanel
        RootPanel.get("title").add(titleField);
        RootPanel.get("subtitle").add(subtitleField);
        RootPanel.get("autor").add(autorField);
        RootPanel.get("description").add(descriptionField);
        RootPanel.get("isbn").add(isbnField);
        RootPanel.get("genre").add(genreField);
        RootPanel.get("publishedDate").add(publishedDateField);
        RootPanel.get("publisher").add(publisherField);
        RootPanel.get("btnSave").add(saveButton);
        RootPanel.get("btnRetrieveAllEntries").add(retrieveButton);
        RootPanel.get("errorLabelContainer").add(errorLabel);

        // 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();
                saveButton.setEnabled(true);
                saveButton.setFocus(true);
                retrieveButton.setEnabled(true);
            }
        });

        class SaveBookHandler implements ClickHandler, KeyUpHandler {

            public void onKeyUp(KeyUpEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                    saveBook();
                }               
            }

            public void onClick(ClickEvent arg0) {
                saveBook();
            }

            private void saveBook() {
                errorLabel.setText("");

                String _title = titleField.getText();
                String _subtitle = subtitleField.getText();
                String _autor = autorField.getText();
                String _desc = descriptionField.getText();
                String _isbn = isbnField.getText();
                String _genre = genreField.getText();
                Date _publishedDate = publishedDateField.getValue();
                String _publisher = publisherField.getText();

                // First, we validate the input.
                if (Validator.isBlank(_title) || Validator.isBlank(_autor)) {
                    String errorMessage = "Please enter at least the Title and the Autor of the book";
                    errorLabel.setText(errorMessage);
                    return;
                }

                Book bookDTO = new Book(null, _title, _subtitle, _autor, _desc, _isbn, _genre, _publishedDate, _publisher);

                saveButton.setEnabled(false);
                serverResponseLabel.setText("");
                textToServerLabel.setText(bookDTO.toString());

                bookService.saveOrUpdate(bookDTO, new AsyncCallback<Void>() {
                    public void onFailure(Throwable caught) {
                        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);
                    }
                });
            }
        }

        // Add a handler to send the book info to the server
        SaveBookHandler saveBookHandler = new SaveBookHandler();
        saveButton.addClickHandler(saveBookHandler);
        publisherField.addKeyUpHandler(saveBookHandler);

        // Create a handler for the retrieveButton
        class RetrieveAllEntriesHandler implements ClickHandler {
            /**
             * Fired when the user clicks on the retrieveButton.
             */
            public void onClick(ClickEvent event) {
                retrieveAllEntries();
            }

            private void retrieveAllEntries() {
                // Nothing to validate here

                // Then, we send the input to the server.
                retrieveButton.setEnabled(false);
                errorLabel.setText("");
                textToServerLabel.setText("");
                serverResponseLabel.setText("");

                bookService.findAllEntries(
                    new AsyncCallback<List<Book>>() {

                        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(List<Book> data) {
                            dialogBox.setText("Remote Procedure Call");
                            serverResponseLabel.removeStyleName("serverResponseLabelError");

                            if(data != null && !data.isEmpty()){
                                StringBuffer buffer = new StringBuffer();
                                for (Book book : data) {
                                    buffer.append(book.toString());
                                    buffer.append("<br /><br />");
                                }
                                serverResponseLabel.setHTML(buffer.toString());
                            } else {
                                serverResponseLabel.setHTML("No book information store in the database.");
                            }
                            dialogBox.center();
                            closeButton.setFocus(true);
                        }
                });
            }
        }

        // Add a handler
        RetrieveAllEntriesHandler retrieveAllEntriesHandler = new RetrieveAllEntriesHandler();
        retrieveButton.addClickHandler(retrieveAllEntriesHandler);
    }
}

如需更多小部件,请访问官方小部件UiBinder

于 2013-05-07T16:40:00.997 回答
0

1) 从https://github.com/chieukam/gwt-spring-hibernate-tutorial/archive/master.zip下载上面引用的 zip 文件并将其解压缩到某个地方

2) 在 Eclipse 中,创建一个新的 Maven 项目。由于上述 zip 中没有提供 .project 文件,因此您需要手动配置所有这些。

3) 从你解压这个项目的地方导入“文件系统”到你的新 Maven 项目中。

在这一点上,我有一些错误:

  • BookServiceAsync 似乎不存在,导致 6 个编译错误。
  • “生命周期配置未涵盖插件执行:org.apache.maven.plugins:maven-war-plugin:2.1.1:exploded (execution: default, phase: compile)”在 pom.xml 中,第 162 和 185 行

这个例子似乎有些不完整。我错过了什么吗?

于 2013-10-24T08:21:04.933 回答