3

問題は、ログインページに移動すると、ログインするためのユーザー名/パスワードを入力すると、それらを正しく書いてもエラーが発生することです (データベースを確認し、エントリが存在します)。ロガーを使用する必要があることはわかっていますが、Hibernate で Spring Framework をまだ学習中です。

編集:
1.テストの最初の部分で、空のユーザー名/パスワードを入力しました(空/空の場合に機能します)。2番目の部分では、機能するはずのものを使用しました。
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;
    }

}

DB エンティティの処理に使用されるプロキシ クラス:

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
}

User obj を作成し、Authorities を追加する UserServiceImpl のメソッド:

@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 セキュリティ構成。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>

ログイン.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 に投稿するのは初めてです。

4

1 に答える 1

1

問題は、 User クラスのデフォルトのコンストラクターがなかったことです。

于 2013-02-04T11:24:36.470 に答える