Hibernate查询返回userId =' null'

时间:2016-05-23 23:25:55

标签: java mysql hibernate jsp servlets

我想用Servlet,JSP和Hibernate创建登录系统。但我收到一个错误,userId =' null'。使用的Java类如下。你能帮帮我吗?

查询结果:

  

Hibernate:选择users0_.id为id0_,users0_.email为email0_,   users0_.firstName as firstName0_,users0_.lastName as lastName0_,   users0_.middleName为middleName0_,users0_.password为password0_,   users0_.userId as userId0_ from users users0_ where   users0_.userId ='空'

此查询结果返回重复。

登录Servlet:

@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException { 
     String userId = request.getParameter("userId");    
     String password = request.getParameter("password");
     LoginService loginService = new LoginService();
     boolean result = loginService.authenticate(userId, password);
     Users user = loginService.getUserByUserId(userId);
     if(result == true){
         request.getSession().setAttribute("user", user);       
         response.sendRedirect("deneme.jsp");
     }
     else{
         response.sendRedirect("login.jsp");
     }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
     processRequest(request, response);
}
@Override
public String getServletInfo() {
     return "Short description";
 }
}

用户模型:

Entity
@Table(name="users")
public class Users implements Serializable {

@Id @GeneratedValue
private Long id;
private String firstName;
private String middleName;
private String lastName;
private String email;
private String userId;
private String password;

//Constructor and Getter Setter methods 
}

登录服务:

public class LoginService {
public boolean authenticate(String userId, String password) {
     Users user = getUserByUserId(userId);      
     if(user!=null && user.getUserId().equals(userId) && user.getPassword().equals(password)){
         return true;
     }else{
         return false;
     }
}
public Users getUserByUserId(String userId) {
     Session session = HibernateUtil.openSession();
     Transaction tx = null;
     Users user = null;
     try {
         tx = session.getTransaction();
         tx.begin();
         Query query = session.createQuery("from Users where userId='"+userId+"'");
         user = (Users)query.uniqueResult();
         tx.commit();
     } catch (Exception e) {
         if (tx != null) {
             tx.rollback();
         }
         e.printStackTrace();
     } finally {
         session.close();
     }
     return user;
}

public List<Users> getListOfUsers(){
     List<Users> list = new ArrayList<Users>();
     Session session = HibernateUtil.openSession();
     Transaction tx = null; 
     try {
         tx = session.getTransaction();
         tx.begin();
         list = session.createQuery("from Users").list();                   
         tx.commit();
     } catch (Exception e) {
         if (tx != null) {
             tx.rollback();
         }
         e.printStackTrace();
     } finally {
         session.close();
     }
     return list;
}
}

Hibernate Util:

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
         try {
             sessionFactory = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
         } catch (Throwable ex) {
             System.err.println("Initial SessionFactory creation failed." + ex);
             throw new ExceptionInInitializerError(ex);
         }
    }

    public static Session openSession() {
         return sessionFactory.openSession();
    }
  }

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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
         <property name="hibernate.connection.url">jdbc:mysql://localhost/test?zeroDateTimeBehavior=convertToNull</property>
         <property name="hibernate.connection.username">root</property>
         <property name="hibernate.connection.password"></property>
         <property name="show_sql">true</property>
         <property name="hbm2ddl.auto">update</property>
         <mapping class="com.bookstore.model.Users" />
    </session-factory>
    </hibernate-configuration>

的login.jsp

<!-- Account Login-->

              <div align="right">
              <form role="form" action="login" method="post" >

                       <label  class="control-label">User Id:</label>                
                      <input type="text" name="userId"  class="span3">
                    <label  class="control-label"  >Password:</label>                  
                      <input type="password" name="password">  

                        <input type="submit" value="Login" >
              </form>
          </div>

1 个答案:

答案 0 :(得分:-1)

可以通过doPost或doGet两种方式调用登录servlet。如果是doGet,则使用request.getParameter(&#34; userId&#34;)或者如果是post form submit,则使用request.getAttribute(&#34; userId&#34;)。让我们知道您是如何调用登录servlet的。