strust2 和 hibernate的整合------登录的实现
2024-08-25 04:42:23
初步认识了struts2,并与hibernate进行整合,完成了一个登录的案例,下面贴源码
1.实体类User
public class User { private Integer id;
private String uname;
private String upass; ...省略set和get方法 }
2.实体类的映射文件
<class name="www.change.tm.bean.User" table="USERS">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="uname" type="java.lang.String">
<column name="UNAME" />
</property>
<property name="upass" type="java.lang.String">
<column name="UPASS" />
</property>
</class>
3.hibernate.cfg.xml
<session-factory>
<!-- 配置hibernate的基本信息 -->
<property name="connection.username">****</property>
<property name="connection.password">****</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///hibernate3</property> <!-- hibernate的基本配置 -->
<!-- 数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 是否打印sql -->
<property name="show_sql">true</property>
<!-- 是否格式化sql -->
<property name="format_sql">true</property>
<!-- 生成表的策略 -->
<property name="hbm2ddl.auto">update</property> <mapping resource="www/change/tm/bean/User.hbm.xml"/> </session-factory>
4.action类
package www.change.tm.action; import java.util.Map; import org.apache.struts2.ServletActionContext; import www.change.tm.bean.User;
import www.change.tm.dao.UserDao;
import www.change.tm.dao.UserDaoImpl; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class Login extends ActionSupport{ //声明dao对象
UserDao userdao = new UserDaoImpl(); private String uname;
private String upass; public String login(){ User user = userdao.login(uname, upass); if (user != null ) {
// 存入到session会话中
ServletActionContext.getRequest().getSession()
.setAttribute("user", user); return SUCCESS; } else {
ServletActionContext.getRequest().setAttribute("msg", "用户名或者密码");
return ERROR;
}
} public void setUname(String uname) {
this.uname = uname;
} public void setUpass(String upass) {
this.upass = upass;
} }
5.dao层
5.1 BaseDao
public interface BaseDao {
public Session getSession();
}
5.2 UserDao
public interface UserDao { /*
* 登录验证处理
*/ public User login(String uname,String upass);
}
5.3 UserDaoImpl
public class UserDaoImpl extends BaseDaoImpl implements UserDao{ @Override
public User login(String uname, String upass) {
//1.获取session对象
Session session = getSession(); //2.执行查询
Query createQuery = session.createQuery("from User u where u.uname=? and u.upass=?");
User user = (User)createQuery.setString(0, uname).setString(1, upass).uniqueResult(); /*总的写
User user =(User) getSession().createQuery("").setString(0, uname).setString(1, upass).uniqueResult();
*/ //3.session关闭
HiberSessionFactory.closeSession(); return user;
} }
5.4 BaseDaoImpl
public class BaseDaoImpl implements BaseDao{ @Override
public Session getSession() {
// TODO Auto-generated method stub
return HibernateControl.getSession();
} }
6.util包里
引入HiberSessionFactory.java文件
package www.change.tm.util; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder; /**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HiberSessionFactory { /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry; static {
try {
System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@");
configuration.configure();
System.out.println("configuration="+configuration);
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
System.out.println("serviceRegistry="+serviceRegistry);
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
System.out.println();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HiberSessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }
7.数据库
最新文章
- ENode 1.0 - 框架的物理部署思路
- 【JAVA】调用类中的属性
- SQLite剖析之功能特性
- bzoj1104: [POI2007]洪水pow
- JQuery Easy Ui 可装载组合框 - ComboBox
- CSS缩放函数, 旋转函数与倾斜函数
- 使用AjaxPro
- poj 2299 Ultra-QuickSort :归并排序求逆序数
- 【Linux安全】系统资源监控与进程终止
- 【转】Win7与Ubuntu 14.04双系统修改启动项顺序
- VisualStudio中的代码段
- Git简略教程
- 对java多线程里Synchronized的思考
- 02-创建 TLS CA证书及密钥
- 三种方法,刷新 Android 的 MediaStore!让你保存的图片立即出现在相册里!
- Android-MVVM架构-Data Binding的使用
- 《java入门第一季》之面向对象面试题(fianl关键字)
- 目录的rwx权限的意义
- IIS Service Unavailable HTTP Error 503. The service is unavailable.
- MyISAM和InnoDB区别详解
热门文章
- Exercise03_03
- Scala实战高手****第12课:Scala函数式编程进阶(匿名函数、高阶函数、函数类型推断、Currying)与Spark源码鉴赏
- SQL Server Latch Classes Library
- JavaScript中的模块化之AMD和CMD
- 直接拿来用!最火的iOS开源项目(三)
- webpack配置:打包第三方类库、第三方类库抽离、watch自动打包、集中拷贝静态资源
- 前端传递参数,由于控制器层类实现了struts2的ModelDriven而产生的一个异常
- mysql 将查询出来的某一字段组合成字符串
- Kubernetes用户指南(三)--在生产环境中使用Pod来工作、管理部署
- django dispatch