Hibernate在DAO查询时停止

时间:2012-09-28 14:10:26

标签: java spring hibernate spring-mvc dao

问题是,当我进入登录页面时,输入用户名/密码登录我即使我正确地写了它也会收到错误(我检查了我的数据库并且条目存在)。 我知道我应该使用Logger但我仍在学习使用Hibernate的Spring Framework。

编辑:
1.测试的第一部分我输入了一个空的用户名/密码(它适用于空/空)。对于第二部分,我使用 工作的那个 2.其他DAO与Hibernate一起正常工作(例如,他们正确检索数据,我对它们没有任何问题)

控制台输出如下所示:

-----------------------------------
User Service INVOKED
User Service-- searching for User:
DAO-- Searching for:
Hibernate: select this_.id as id9_0_, this_.accountName as accountN2_9_0_, this_.password as password9_0_, this_.secGrade as secGrade9_0_, this_.userEmail as userEmail9_0_, this_.userName as userName9_0_ from USER this_ where this_.accountName=?
DAO-- End search
DAO--Not found
User Service-- UserProxyImpl instantiated
User Service-- NOT FOUND,
null
true //<-- Error returned to the controller
-----------------------------------
User Service INVOKED
User Service-- searching for User:admin
DAO-- Searching for:admin
Hibernate: select this_.id as id9_0_, this_.accountName as accountN2_9_0_, this_.password as password9_0_, this_.secGrade as secGrade9_0_, this_.userEmail as userEmail9_0_, this_.userName as userName9_0_ from USER this_ where this_.accountName=?
UserService-- Error in retrieving user
// It stops here and i don't understand why
true // still, returns error to the controller.

这是会话超时问题吗?

登录控制器中的方法:

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String Login(@RequestParam(value="error", required=false) boolean error,ModelMap model) {

        if (error == true) {
            model.put("error", "You have entered an invalid username or password!");
        } else {
            model.put("error", "");
        }
        System.out.println(error);
        return "login";     

    }

用户实体:

@Entity
@Table(name = "USER")
public class User implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -1963505165125499005L;


    private long id;
    private int secGrade;

    private String userName;
    private String accountName;
    private String password;
    private String userEmail;

    public User(String name,
                String user_name,
                String password,
                String email,
                int secGrade){
        this.userName = name;
        this.accountName = user_name;
        this.password = password;
        this.userEmail = email;
        this.secGrade = secGrade;
    }

    @Id
    @GeneratedValue
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public int getSecGrade() {
        return secGrade;
    }
    public void setSecGrade(int secGrade) {
        this.secGrade = secGrade;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

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

    public String getUserEmail() {
        return userEmail;
    }

    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }

}

用于处理数据库实体的代理类:

public class UserProxyImpl implements UserProxy {

    private int secGrade;   
    private String name;
    private String user_name;
    private String password;
    private String email;

    public UserProxyImpl() { }

    public UserProxyImpl(User usr){
        if( usr != null){
            System.out.println("USER PROXY--- constru from "+usr.getAccountName());
            this.secGrade = usr.getSecGrade();
            this.name = usr.getUserName();
            this.user_name = usr.getAccountName();
            this.password = usr.getPassword();
            this.email = usr.getUserEmail();
        }
    }
+ GETTERS/SETTERS
}

来自UserServiceImpl的方法,它创建用户obj并添加权限:

@Override
        public UserDetails loadUserByUsername(String username) 
                throws UsernameNotFoundException,DataAccessException {
                // Declare a null Spring User
                UserDetails user = null;
                System.out.println("-----------------------------------");
                System.out.println("User Service INVOKED");


            try {
                System.out.println("User Service-- searching for User:"+username);
               // Search database for a user that matches the specified username
                UserProxyImpl dbUser = new UserProxyImpl(userDAO.searchDB(username));
                System.out.println("User Service-- UserProxyImpl instantiated");
                if(dbUser.getName() != null){
                    System.out.println("User Service-- FOUND,"+username);
                }
                else{
                    System.out.println("User Service-- NOT FOUND,"+username);
                }

               // Populate the Spring User object with details from the dbUser
               // getAuthorities() will translate the access level to the correct role type
                System.out.println(dbUser.getName());
                user = new User(
                        dbUser.getUser_name(),
                        dbUser.getPassword().toLowerCase(),
                        true,
                        true,
                        true,
                        true,
                        getAuthorities(new Integer(dbUser.getSecGrade()))
                        );
                System.out.println(user.toString());
              } catch (Exception e) {
               System.out.println("UserService-- Error in retrieving user");
               throw new UsernameNotFoundException("Error in retrieving user");
              }

              // Return user to Spring for processing.

              return user;
             }


         @Override
        public Collection<GrantedAuthority> getAuthorities(Integer access) {
               // Create a list of grants for this user
               List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);

               // All users are granted with ROLE_USER access

               authList.add(new GrantedAuthorityImpl("ROLE_USER"));

               // Check if this user has admin access
               // We interpret Integer(3) as an admin user
               if ( access.compareTo(3) == 0) {

                    authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

               }
               else if ( access.compareTo(2) == 0) {                

                   authList.add(new GrantedAuthorityImpl("ROLE_MOD"));
               }

               // Return list of granted authorities
               return authList;
               }

用于从DB中检索对象的DAO类方法:

public User searchDB(String username){

        User u = (User)this.getSessionFactory().getCurrentSession()
                    .createCriteria(User.class)
                    .add(Restrictions.eq("accountName",username))
                    .uniqueResult();
        System.out.println("DAO-- End search");
        if(u != null){
            System.out.println("DAO-- Found:"+u.getUserName());
            return u;
        }
        else{
            System.out.println("DAO--Not found");
            return null;
        }

    }

Spring Security配置。 XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans 
    xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.1.xsd">


 <http auto-config = 'true' use-expressions="true" access-denied-page="/denied" >

    <intercept-url pattern = "/home/" access="permitAll"/>
    <intercept-url pattern = "/home/login" access="permitAll"/>
    <intercept-url pattern = "/home/jobs" access="permitAll"/>
    <intercept-url pattern = "/home/info" access="permitAll"/>
    <intercept-url pattern = "/home/common" access="hasRole('ROLE_USER')"/>
    <intercept-url pattern = "/home/desk" access="hasRole('ROLE_MOD')"/>
    <intercept-url pattern = "/home/admin" access="hasRole('ROLE_ADMIN')"/>
    <form-login login-page="/login"
                default-target-url="/home"
                authentication-failure-url="/home/login?error=true"/>
    <logout logout-success-url="/home" />               
 </http> 

 <authentication-manager alias="authenticationManager">
    <authentication-provider ref="authenticationProvider"/>
</authentication-manager>

<beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <beans:property name="userDetailsService" ref="UserServiceImpl"/>
</beans:bean>


 <!-- Use a Md5 encoder  -->
 <beans:bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

 <!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
 <beans:bean id="UserServiceImpl" class="com.x.interview_management.service.impl.UserServiceImpl"/>

</beans:beans>

的Login.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>${error}</h1>
    <sec:authorize access="!isAuthenticated()">
    <div id = "login" style="text-align:center;">

                <h3 style="text-align:center">Login with Username and Password</h3>

                    <form action='/InterviewManagement/j_spring_security_check' method='POST'>
                    <table>
                    <tr>
                        <td>Username:</td>
                        <td><input type='text' name='j_username' value=''><td/>
                    <tr/>
                    <tr>
                        <td>Password:</td>
                        <td><input type='password' name='j_password'/><td/>
                    <tr/>

                    <tr>
                        <td><input name="submit" type="submit"/></td>
                        <td><input name="reset" type="reset"/></td>
                    </tr>
                    </table>
                    </form>

    </div>
    </sec:authorize>    
    <a href="/InterviewManagement/home/">return home</a>
</body>
</html>

对于代码布局感到抱歉,这是我第一次在StackExchange上发帖。

1 个答案:

答案 0 :(得分:1)

问题是我没有User类的默认构造函数。