Spring简单整合hibernate实现登录例子

数据库loginusers表

1、新建javaWeb Porject项目spring_hibernate,添加com.dao包(放置数据库操作类)、com.pojo包(放置hibernate生成的POJO类)

2、右击项目添加spring开发功能,注意这里需把spring Persistence类库勾选

3、接下来是添加hibernate组件,与单独部署时不同的是这里不生成hibernate.cfg.xml文件,而是将数据库配置当成bean,

分配id值,统一交由spring进行配置管理

4、配置映射数据库表生成POJO类,com.pojo包如下

package com.pojo;

/**
 * AbstractLoginusers entity provides the base persistence definition of the Loginusers entity. @author MyEclipse Persistence Tools
 */

public abstract class AbstractLoginusers  implements java.io.Serializable {

    // Fields    

     private Integer id;
     private String userName;
     private String password;

    // Constructors

    /** default constructor */
    public AbstractLoginusers() {
    }

	/** minimal constructor */
    public AbstractLoginusers(Integer id) {
        this.id = id;
    }
    
    /** full constructor */
    public AbstractLoginusers(Integer id, String userName, String password) {
        this.id = id;
        this.userName = userName;
        this.password = password;
    }
   
    // Property accessors

    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }

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

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

/**
 * Loginusers entity. @author MyEclipse Persistence Tools
 */
public class Loginusers extends AbstractLoginusers implements java.io.Serializable {

    // Constructors

    /** default constructor */
    public Loginusers() {
    }

	/** minimal constructor */
    public Loginusers(Integer id) {
        super(id);        
    }
    
    /** full constructor */
    public Loginusers(Integer id, String userName, String password) {
        super(id, userName, password);        
    }
   
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.pojo.Loginusers" table="loginusers" catalog="mydb">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="userName" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" />
        </property>
    </class>
</hibernate-mapping>

5、在WebRoot下新建、编写login.jsp登录主页

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>  
    <title>spring Hibernate login</title>
  </head>
  
  <body>
    <h3>User Login</h3>
    <form action="validate.jsp" method="post">
    	<label>Account:&nbsp;&nbsp;&nbsp;</label>
    	<input type="text" name="userName"/><br>
    	<label>Password:</label>
    	<input type="password" name="password"/><br><br>
    	<input type="reset" value="reset"/>
    	<input type="submit" value="submit"/>
    </form>
  </body>
</html>

6、在持久层com.dao包下编写数据库操作类完成BaseDao基类(提供SessionFactory获取Session)、InterUserDao接口类、

UserDaoImpl接口实现类,实现用户验证

package com.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class BaseDao {
	//Dao持久层访问SessionFactor获取session对象的中间组件
	//解耦Dao层与SessionFactory
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public Session getSession(){
		Session session=sessionFactory.openSession();
		return session;
	}
}
package com.dao;

import com.pojo.Loginusers;

public interface InterUserDao {
	public Loginusers validate(String name,String password);   //提供数据库操作方法:验证用户名密码
}
package com.dao;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import com.pojo.Loginusers;

public class UserDaoImpl extends BaseDao implements InterUserDao {

	@Override
	public Loginusers validate(String name,String password) {
		// TODO Auto-generated method stub
		Session session=getSession();	//从BaseDao继承的方法中得到session
		Query query=session.createQuery("from Loginusers where userName=? and password=?");
		query.setParameter(0, name);
		query.setParameter(1, password);
		List list=query.list();
		Iterator it=list.iterator();
		while(it.hasNext()){
			if(list.size()!=0){
				Loginusers user=(Loginusers)it.next();//创建持久化对象
				return user;
			}
		}
		session.close();
		return null;
	}

}

7、修改applicationContext.xml文件添加BaseDao、UserDaoImpl的bean组件,在数据库配置bean中没有

数据库驱动DriverClass属性需手动添加。完成如下

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


	<bean id="dataSource"
		class="org.apache.commons.dbcp.BasicDataSource"> 
		<!-- 配置数据库驱动 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		
		<property name="url" value="jdbc:mysql://localhost:3306/"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root123"></property>
	</bean>
	
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
			</props>
		</property>
		<property name="mappingResources">
			<list>
				<value>com/pojo/Loginusers.hbm.xml</value>
			</list>
		</property>
	</bean>
	
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	
	<bean id="baseDao" class="com.dao.BaseDao">
		<property name="sessionFactory">
			<ref bean="sessionFactory"/>
		</property>
	</bean>
	
	<bean id="userDaoImpl" class="com.dao.UserDaoImpl" lazy-init="false" parent="baseDao"></bean>
	
	
	<tx:annotation-driven transaction-manager="transactionManager" />	
	</beans>
	

8、在WebRoot下新建编写validate.jsp完成验证业务

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ page import="org.springframework.context.*,org.springframework.context.support.*" %>
<%@ page import="com.dao.*,com.pojo.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>验证业务方法</title>

  </head>
  
  <body>
    <%
    	request.setCharacterEncoding("utf-8");
    	String name=request.getParameter("userName");
    	String password=request.getParameter("password");
    	boolean flag=false;  //验证标识符
    	Loginusers user=null;
    	user=(Loginusers)session.getAttribute("user");
    	
    	if(user==null){	//判断第一次登录
    	
    		ApplicationContext context=new FileSystemXmlApplicationContext(
	    	"file:D:/JAVA-Develop/Workspaces/MyEclipse 2017 CI/spring_hibernate/src/applicationContext.xml");
	    	InterUserDao interUserDao=(InterUserDao)context.getBean("userDaoImpl");
	    	user=interUserDao.validate(name,password);
	    	if(user!=null){
	    		session.setAttribute("user",user);//保存user对象
	    		flag=true;
	    	}
    	}else{
    		flag=true;
    	}
    	if(flag)
    		response.sendRedirect("success.jsp");
    	else
    		response.sendRedirect("error.jsp");

     %>
  </body>
</html>

9、在WebRoot下编写success.jsp成功页、error.jsp失败页

<%@ page language="java" import="java.util.*" import="com.pojo.Loginusers" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title> success login</title>
  </head>
  
  <body>
  	<% 
  		Loginusers user=(Loginusers)session.getAttribute("user");
  		System.out.print(user);
  		String uName=user.getUserName();
  	 %>
    <h2 style="text-align:center;margin:200xp auto">Welcome <%=uName %>,Login Success</h2>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title> error login </title> 

  </head>
  
  <body>
    <h2 style="text-align:center;margin:100px auto">Login Error</h2>
  </body>
</html>

10、保存启动Tomcat,浏览器测试

猜你喜欢

转载自blog.csdn.net/zero_130/article/details/81217207