GWT - 使用Hibernate的登录页面实现无法正常工作

时间:2011-04-22 10:47:19

标签: java gwt gwt-rpc

我正在遵循这个教程Login,而且我正面临一些困难。 我有一个MYSQL数据库,我创建了一个包含id,用户名和密码的表。 数据库已启动并正在运行。创建了 hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

<session-factory>
    <property name="connection.url">jdbc:mysql://localhost:3306/timetable</property>
    <property name="connection.username">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.password">k771u3</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

    <property name="current_session_context_class">thread</property>
    <!-- this will show us all sql statements -->
    <property name="hibernate.show_sql">true</property>

    <!-- mapping files -->
    <mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>

User.hbm.xml

<hibernate-mapping>
    <class name="com.Logins.client.bean.User" table="username">
        <id name="id" column="id" type="int" unsaved-value="null">
            <generator class="native"/>
        </id>
        <property name="username" type="java.lang.String" column="username"/>
        <property name="password" type="java.lang.String" column="password"/>
    </class>
</hibernate-mapping>

Logins.java     包com.Logins.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.Logins.client.bean.User;
import com.Logins.client.screen.HomeScreen;
import com.Logins.client.screen.LoginScreen;

public class Logins implements EntryPoint {

    private static Logins singleton;
    public static Logins get(){
        return singleton;
    }

    @Override
    public void onModuleLoad() {
        singleton=this;
          setLoginScreen(); 
    }
     private void setLoginScreen()  {
            //Create the Login screen
            LoginScreen scrLogin=new LoginScreen();
            //Attach it to the root panel
            RootPanel.get().add(scrLogin);
      }
      public void setHomeScreen(User user)  {
          HomeScreen homeScreen=new HomeScreen(user);
          RootPanel.get().clear();
          RootPanel.get().add(homeScreen);
      }
}

GreetingService.java

package com.Logins.client;

import com.Logins.client.bean.User;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
    public User checkLogin(String userName, String password);
    public User isSessionAlive();
    void logout();
}

GreetingServiceAsync.java

package com.Logins.client;

import com.Logins.client.bean.User;
import com.google.gwt.user.client.rpc.AsyncCallback;

public interface GreetingServiceAsync {
    public void checkLogin(String userName, String password, AsyncCallback callback);
    public void isSessionAlive(AsyncCallback callback);
    public void logout(AsyncCallback callback);
}

HomeScreen.java

package com.Logins.client.screen;

import com.Logins.client.bean.User;

public class HomeScreen extends Composite{

    public HomeScreen(User user)    {
        VerticalPanel vp=new VerticalPanel();
        Label lblWelcome=new Label();
        lblWelcome.setText("Hello "+user.getUserName());
        vp.add(lblWelcome);
        initWidget(vp);
    }
}

LoginScreen.java

package com.Logins.client.screen;

import com.Logins.client.GreetingService;

public class LoginScreen extends Composite{
    // TextBox for the User Name
    private TextBox txtLogin=new TextBox();
    // PasswordTextBox for the password
    private PasswordTextBox txtPassword=new PasswordTextBox();
    //Error Label
    private Label lblError=new Label();

    public LoginScreen()    {
        // Lets add a grid to hold all our widgets
        Grid grid = new Grid(4, 2);
        //Set the error label
        grid.setWidget(0,1, lblError);
        //Add the Label for the username
        grid.setWidget(1,0, new Label("Username"));
        //Add the UserName textBox
        grid.setWidget(1,1, txtLogin);
        //Add the label for password
        grid.setWidget(2,0, new Label("Password"));
        //Add the password widget
        grid.setWidget(2,1, txtPassword);
        //Create a button
        Button btnLogin=new Button("login");
        //Add the Login button to the form
        grid.setWidget(3,1, btnLogin );
        /*Add a click listener which is called 
        when the button is clicked */

        btnLogin.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                checkLogin(txtLogin.getText(),txtPassword.getText());

            }
        });
        initWidget(grid);

    }
    /*
     * This method is called when the button is clicked
     */

    private void checkLogin(String userName,String password) {
        System.out.println("Checking login for "+userName);

        /** 
         * Async call to the server to check for login
         */
        AsyncCallback callback = new AsyncCallback() {
            public void onSuccess(Object result) {
                User user = (User) result;
                if (user != null) {
                    setErrorText("");
                    // The user is authenticated, Set the home screen
                    Logins.get().setHomeScreen(user);
                } else {
                    setErrorText("Invalid UserName or Password");

                }
            }

            public void onFailure(Throwable ex) {
                setErrorText("Error "+ex.getMessage());   
            }
        };

        getService().checkLogin(userName, password,callback);

    }
    private void setErrorText(String errorMessage)  {
        lblError.setText(errorMessage);
    }

    private GreetingServiceAsync getService() {
        GreetingServiceAsync svc = (GreetingServiceAsync) GWT
            .create(GreetingService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) svc;
        endpoint.setServiceEntryPoint(GWT.getModuleBaseURL() + "/GreetingService");

        return svc;
    }
}

GreetingServiceImpl.java

package com.Logins.server;
import javax.servlet.http.HttpSession;

import com.Logins.client.GreetingService;
import com.Logins.client.bean.User;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GreetingServiceImpl extends RemoteServiceServlet implements
        GreetingService {

    private static final String USER_SESSION = "GWTAppUser";
    private static final long serialVersionUID = 1;

    private void setUserInSession(User user) {
        HttpSession session = getThreadLocalRequest().getSession();
        session.setAttribute(USER_SESSION, user);
    }

    private User getUserFromSession() {
        HttpSession session = getThreadLocalRequest().getSession();
        return (User) session.getAttribute(USER_SESSION);
    }

    public User checkLogin(String userName, String password) {
        if (userName.equalsIgnoreCase("gwt")) { 
            User user = new User();
            user.setUserName(userName);
            setUserInSession(user);
            return user;
        } else
            return null;
    }

    @Override
    public void logout() {
        HttpSession session = getThreadLocalRequest().getSession();
        if (session != null)
            session.invalidate();       
    }

    @Override
    public User isSessionAlive() {
        User bean = getUserFromSession();
        if ((bean != null) && (bean.getUserName().length() != 0)) {
            System.out.println("User " + bean.getUserName()
                    + " is already logged in");
            return bean;
        }
        return null;

    }

}

的HibernateUtil

package util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

      static {
        try {
          // Create the SessionFactory from hibernate.cfg.xml
          sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
          // Make sure you log the exception, as it might be swallowed
          System.err.println("Initial SessionFactory creation failed." + ex);
          throw new ExceptionInInitializerError(ex);
        }
      }

      public static SessionFactory getSessionFactory() {
        return sessionFactory;
      }
}

User.java

package com.Logins.client.bean;
import java.io.Serializable;
public class User implements Serializable{
     /**
     * Add this variable for serialization 
     */
    private static final long serialVersionUID = 1L;

    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

当我'运行为Web应用程序'出现html表单时,但当我输入凭据,用户和密码时,会收到此错误:

错误404 html head meta http-equiv =“Content-Type”content =“text / html; charset = ISO-8859-1”/ titleError 404 NOT_FOUND / title / head bodyh2HTTP错误:404 / h2preNOT_FOUND / pre pRequestURI = / logins // GreetingService / ppismalla href =“http://jetty.mortbay.org/”由Jetty提供支持:/// a / small / i / pbr / br / br / br / br / br / br / br / br / br / br / br / br / br / br / br / br / br / br / br / / body / html

如果有人可以帮我弄清楚哪些是错的或者还有什么可以实施,那将非常高兴。这对我来说非常重要。感谢

控制台错误:

Reloading web app to reflect changes in C:\Users\Martinho\Documents\SpringWorkSpace\Logins\war
[WARN] Server class 'com.google.gwt.dev.shell.jetty.JDBCUnloader' could not be found in the web app, but was found on the system classpath
   [WARN] Adding classpath entry 'file:/C:/springsource/sts-2.6.0.RELEASE/plugins/com.google.gwt.eclipse.sdkbundle_2.2.0.v201103311225/gwt-2.2.0/gwt-dev.jar' to the web app classpath for this session
   For additional info see: file:/C:/springsource/sts-2.6.0.RELEASE/plugins/com.google.gwt.eclipse.sdkbundle_2.2.0.v201103311225/gwt-2.2.0/doc/helpInfo/webAppClassPath.html
   Reload completed successfully
Checking login for 
[WARN] 404 - POST /logins//GreetingService (127.0.0.1) 1409 bytes
   Request headers
      Host: 127.0.0.1:8888
      Connection: keep-alive
      Referer: http://127.0.0.1:8888/Logins.html?gwt.codesvr=127.0.0.1:9997
      Content-Length: 161
      Origin: http://127.0.0.1:8888
      X-GWT-Module-Base: http://127.0.0.1:8888/logins/
      X-GWT-Permutation: HostedMode
      User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.0 Safari/534.30
      Content-Type: text/x-gwt-rpc; charset=UTF-8
      Accept: */*
      Accept-Encoding: gzip,deflate,sdch
      Accept-Language: pt-PT,pt;q=0.8,en-US;q=0.6,en;q=0.4
      Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
   Response headers
      Content-Type: text/html; charset=iso-8859-1
      Content-Length: 1409

1 个答案:

答案 0 :(得分:0)

您是否在web.xml中注册了服务?它应该包含类似

的内容
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaeeweb-app_2_5.xsd">

   <servlet>
       <servlet-name>greet</servlet-name>
       <servlet-class>com.Logins.server.GreetingServiceImpl</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>greet</servlet-name>
       <url-pattern>/greet</url-pattern>
   </servlet-mapping>
</web-app>
相关问题