- 浏览: 41859 次
最新评论
struts2.3.5整合hibernate3.2.0 实例详解
简单用户登录页面struts2整合hibernate3演示步骤:
第一步先加入struts2框架,引入struts2.3.5文档库,
在src 下创建struts.xml 文件
struts.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 感叹号方式,需要开启 -->
<!-- <constant name="struts.enable.DynamicMethodInvocation" value="true" /> -->
<package name="default" namespace="/" extends="struts-default">
</package>
<include file="manager.xml"/>
<!-- Add packages here -->
</struts>
manager.xml文件内容如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 采用通配符方式,需要关闭DynamicMethodInvocation -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<package name="manager" extends="default">
<!--自定义拦截器配置 -->
<interceptors>
<interceptor name="loginInterceptor" class="com.hrbkejia.interceptor.LoginInterceptor"/>
</interceptors>
<!-- 配置全局结果 -->
<global-results>
<result name="login" type="redirect">/welcom_UserLogin.action</result>
</global-results>
<!-- 请求的url地址错误时 -->
<action name="welcom_*" class="com.hrbkejia.Action.UserLoginAction" method="{1}">
<result name="login">/WEB-INF/jsp/Login.jsp</result>
<result name="success">/WEB-INF/jsp/maina.jsp</result>
<!-- <interceptor-ref name="defaultStack"/> --> <!-- struts 内置的默认拦截器 -->
<!--<interceptor-ref name="loginInterceptor"/> --> <!-- struts 内置的默认拦截器 -->
</action>
</package>
<!-- Add packages here -->
</struts>
创建Login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title>网站后台 - 登录 </title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" type="text/css" href="js/jqueryEasyUI132/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="js/jqueryEasyUI132/themes/icon.css">
<link rel="stylesheet" type="text/css" href="js/jqueryEasyUI132/demo/demo.css">
<script type="text/javascript" src="js/jqueryEasyUI132/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jqueryEasyUI132/jquery.easyui.min.js"></script>
</head>
<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="top" height="" width="100%"style="background:url(img/login_bg_new.jpg) repeat;">
<tablewidth="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td id="img_td" width="49%" align="right">
<table width="91%"height="" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="138" valign="top">
<table width="89%"height="427" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="149"> </td>
</tr>
<tr>
<td height="80" align="right" valign="top">
<img src="img/default_r1_c1.gif" width="450" height="250"></td>
</tr>
<tr>
<td height="198" align="right" valign="top"> </td>
</tr>
</table>
</td>
</tr>
</table>
</td>
<td width="1%"> </td>
<td width="50%" valign="middle">
<table width="100%"height="59" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="4%"> </td>
<td width="96%" height="30" valign="top"></td>
</tr>
<tr>
<td> </td>
<td height="21">
<table cellSpacing="0" cellPadding="0" width="100%" border="0" id="table211" height="174">
<tr>
<td height="130" align="middle">
<form id="loginForm" method="post">
<div style="font-size: 14px;text-align: center;">网站后台登录</div>
<table width="56%" align="center" border="0" cellpadding="5"
cellspacing="0">
<tr>
<td width="10%" align="right">登录账号:</td>
<td width="20%" align="left">
<input class="easyui-validatebox" type="text" name="userName" data-options="required:true" style="width: 200px" missingMessage="用户名必须填写"/>
</td>
</tr>
<tr>
<td align="right">登录密码:</td>
<td align="left">
<input class="easyui-validatebox" type="password" name="passWord" data-options="required:true" style="width: 200px" missingMessage="密码必须填写"/>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">登 录</a>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()">清 除</a>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td height="29" align="right" valign="bottom">
<div align="center" style="height:20px;">
版权所有 © 2013 <a href="www.hrbkejia.com">哈尔滨市科佳通用机电有限公司</a>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script>
//登录提交验证
function submitForm(){
$('#loginForm').form('submit', {
url:'welcom_login.action',
onSubmit: function(param){
var isValid = $(this).form('validate'){
return isValid;// return false will stop the form submission
},
success:function(data){
var data = eval('(' + data + ')');
if (data.success){
var indexUrl="welcom_loginSuccess.action";
var appPath ="/"+location.pathname.split("/")[1] +"/";
alert(appPath+ indexUrl);
window.location.href =appPath+ indexUrl;
return;
}else {
$.messager.show({
title:'登录提示',
msg:data.message,
timeout:5000,
showType:'slide'
});
}
}
});
}
//登录输入清除
function clearForm(){
$('#loginForm').form('clear');
}
</script>
</body>
</html>
创建bean类
User类内容如下:
package com.hrbkejia.bean;
public class UserManager {
private String userId;
private String userName;
private String passWord;
public UserManager(){}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
创建hibernate3.2.0 ,引入hibernate3.2.0文档库
在src下加入hibernate.cfg.xml文件
hibernate.cfg.xml文件内容:
<!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="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://××××××××/××××××</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- <property name="hbm2ddl.auto">create</property> -->
<mapping resource="com/hrbkejia/bean/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
在User类同包下,加入User类关系映射文件User.hbm.xml文件内容如下
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hrbkejia.bean.User" table="user_table">
<id name="userId" column="id">
<generator class="uuid"/>
</id>
<property name="userName" not-null="true" column="userName"/>
<property name="passWord" not-null="true" column="passWord"/>
<property name="auditStauts" column="auditStauts"/>
</class>
</hibernate-mapping>
接下来编写SessionFactory工厂类
HibernateSessionFactory.java文件内容:
package com.hrbkejia.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static Log log = LogFactory.getLog(HibernateSessionFactory.class);
//Hibernate 默认配置文件路径,此处为classPath
private static String CONFIG_FILE_LOCALTION = "/hibernate.cfg.xml";
//使用ThreadLocal控制Session对象
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
//配置文件路径
private static String configFile = CONFIG_FILE_LOCALTION;
/**
* 获取Session
* @param args
*/
public static Session getSession()throws HibernateException{
//从ThreadLocal中获取已有的Session对象
Session session = (Session)threadLocal.get();
//如果ThreadLocal中不存在session,则重新建立Session对象
if(session == null || !session.isOpen()){
if(sessionFactory == null){
rebuildSessionFactory();
}
session = (sessionFactory != null)?sessionFactory.openSession():null;
//Session对象获取后,植入ThreadLocal中
threadLocal.set(session);
}
return session;
}
/**
* 建立SessionFactory对象
* @param args
*/
public static void rebuildSessionFactory(){
try{
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
log.fatal("创建SessionFactory失败");
e.printStackTrace();
}
}
/**
* 关闭Session对象
* @param args
*/
public static void closeSession()throws HibernateException{
Session session = (Session)threadLocal.get();
threadLocal.set(null);
//如果该线程中存在Session对象,则关闭它
if(session != null){
session.close();
}
}
}
添加HibernateCallback.java 类,内容如下:
package com.hrbkejia.util;
import org.hibernate.Session;
public interface HibernateCallback {
public Object doInSession(Session session);
}
添加UserDao接口:
package com.hrbkejia.dao;
import java.util.List;
import com.hrbkejia.bean.UserManager;
public interface UserManagerDao {
public List queryAllUserManager()throws Exception;
public List queryAllUserManager(int startNum, int endNum)throws Exception;
public UserManager queryUserManager(final UserManager userManager)throws Exception;
public boolean saveUserManager(UserManager userManager)throws Exception;
}
添加UserDaoImpl类
package com.hrbkejia.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.hrbkejia.bean.UserManager;
import com.hrbkejia.dao.UserManagerDao;
import com.hrbkejia.util.HibernateCallback;
import com.hrbkejia.util.HibernateSessionFactory;
public class UserManagerDaoImpl implements UserManagerDao{
private Object execute(HibernateCallback action)throws Exception{
Object ret = null;
Session session = HibernateSessionFactory.getSession();
// 定义事务Transaction对象
Transaction tx = null;
try {
tx = session.beginTransaction();
ret = action.doInSession(session);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
return ret;
}
/**
* 按照用户名和密码查询登录用户实例
*/
public UserManager queryUserManager(final UserManager userManager) throws Exception {
return (UserManager)execute(new HibernateCallback(){
public Object doInSession(Session session) {
Query query =
session.createQuery
("from com.hrbkejia.bean.UserManager as user where user.userName=? and user.passWord=?");
query.setString(0, userManager.getUserName());
query.setString(1, userManager.getPassWord());
List list = query.list();
if(list != null && list.size() >= 1){
return list.get(0);
}
return null;
}
});
}
public static void main(String [] args){
UserManagerDaoImpl s = new UserManagerDaoImpl();
UserManager userManager = new UserManager();
userManager.setUserName("adming");
userManager.setPassWord("admin");
try {
//s.saveUserManager(userManager);
UserManager u = (UserManager)s.queryUserManager(userManager);
System.out.println(u.getUserName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean saveUserManager(final UserManager userManager) throws Exception {
// TODO Auto-generated method stub
execute(new HibernateCallback(){
public Object doInSession(Session session) {
session.save(userManager);
return true;
}
});
return false;
}
public List queryAllUserManager(UserManager userManager) throws Exception {
// TODO Auto-generated method stub
return null;
}
public List queryAllUserManager() throws Exception {
// TODO Auto-generated method stub
return null;
}
public List queryAllUserManager(int startNum, int endNum) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
添加ManagerSupport.java类
package com.hrbkejia.Action;
import com.opensymphony.xwork2.ActionSupport;
public class ManagerSupport extends ActionSupport{
}
添加UserAction类:
package com.hrbkejia.Action;
import java.io.PrintWriter;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.json.simple.JSONObject;
import com.hrbkejia.bean.UserManager;
import com.hrbkejia.dao.UserManagerDao;
import com.hrbkejia.dao.impl.UserManagerDaoImpl;
import com.opensymphony.xwork2.ModelDriven;
public class UserLoginAction extends ManagerSupport implements ModelDriven<UserManager>{
private UserManagerDao userManagerDao = new UserManagerDaoImpl();
private UserManager userManager = new UserManager();
public UserManager getModel() {
return userManager;
}
/**
* 返回到登录页面
* @return 登录
* @throws Exception
*/
public String UserLogin() throws Exception {
return this.LOGIN;
}
/**
* 使用jquery 登录输入验证
* @throws Exception
*/
public void login() throws Exception{
System.out.println("-----1------");
ServletActionContext.getResponse().setCharacterEncoding("UTF-8"); //防止jsp页面乱码
ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8"); //防止jsp页面乱码
System.out.println("-----2------");
JSONObject json = new JSONObject();
System.out.println("-----3------");
PrintWriter writer = null;
writer = ServletActionContext.getResponse().getWriter();
System.out.println("-----2------");
String userName = getModel().getUserName();
String passWord = getModel().getPassWord();
System.out.println("-----3------");
if((userName == null || userName.trim().equals("")) ||
(passWord == null || passWord.trim().equals(""))){
System.out.println("-----4------");
try{
json.put("success", false);
json.put("message", "请检查用户名和密码是否填写了?");
System.out.println(json);
writer.print(json);
}catch(Exception e){
e.printStackTrace();
}finally {
if(writer != null){
writer.close();
}
}
return ;
}
UserManager user = userManagerDao.queryUserManager(getModel());
if(user == null){
System.out.println("-----5------");
try{
System.out.println("userName="+userName);
json.put("success", false);
json.put("message", "用户名或密码错误 ,请重新登录!");
System.out.println(json);
writer.print(json);
}catch(Exception e){
e.printStackTrace();
}finally {
if(writer != null){
writer.close();
}
}
}else {
System.out.println("-----6------");
try{
System.out.println("登录成工userName="+userName);
ServletActionContext.getContext().getSession().put("user", user);
json.put("success", true);
writer.print(json);
}catch(Exception e){
e.printStackTrace();
}finally {
if(writer != null){
writer.close();
}
}
}
}
/**
* 成功页面
* @return
* @throws Exception
*/
public String loginSuccess()throws Exception{
if(ServletActionContext.getContext().getSession().get("user") == null){
return this.LOGIN;
}
return this.SUCCESS;
}
}
struts2.3.15 和hibenate3.2.0 库包可以去我的资源里下载http://download.csdn.net/detail/ding43930053/6595985
相关推荐
hibernate-3.2.0源码和hibernate-3.2.0所有的jar包。
Struts2.3.15 和 Hibernate3.2.0 是两个非常重要的Java Web开发框架。Struts2是一个基于MVC(Model-View-Controller)设计模式的框架,用于构建可维护性和可扩展性极高的Web应用程序。而Hibernate则是一个对象关系...
Hibernate3.2.0中文手册,学习和使用Hibernate的必备手册。
Hibernate 3.2.0 RC1是该框架的一个版本,包含了许多增强特性和修复的问题。这个中文帮助文档是开发者理解和使用Hibernate 3.2.0 RC1的重要参考资料。 在Hibernate 3.2.0 RC1中,有以下几个核心知识点: 1. **对象...
《Hibernate 3.2.0 中文帮助文档》是一份极其宝贵的资源,它详细阐述了Hibernate 3.2.0版本的核心特性和使用方法。Hibernate是Java开发领域中广泛使用的对象关系映射(ORM)框架,它允许开发者用面向对象的方式来...
struts2.3.4+spring3.2.0+hibernate4+hibernate_generic_dao struts hibernate spring最大化使用注释 基于spring的远程调用
Hibernate 3.2.0 是该框架的一个版本,提供了许多改进和新特性,使得开发更加高效和灵活。中文官方文档为国内开发者提供了方便的学习资源,避免了语言障碍。 在Hibernate 3.2.0 中,主要知识点包括以下几个方面: ...
《符合Java习惯的关系数据库持久化Hibernate3.2.0_Reference_zh_CN》是针对Java开发者的一份详尽的中文API文档,它详细介绍了如何利用Hibernate 3.2.0框架进行关系数据库的持久化操作。Hibernate作为一个开源的对象...
SSH是Java开发中广泛使用的三大开源框架,包括Struts2、Hibernate和Spring。这三大框架在Web应用开发中各自承担着不同的职责,协同工作以提高开发效率和代码质量。 Struts2是MVC(Model-View-Controller)设计模式...
一、Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0) 1. jar包引入 Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar Hibernate 3.6.8:hibernate3.jar...
Hibernate Tools 3.2.0 beta 8Hibernate Tools 3.2.0 beta 8
这是本人周末期间,无聊时之作,说实在的,当时整的时候坑得要死,后来网上查各种资料,这个框架也并非全部由本人整合,至少jar包是借用别人已经整合好的,其它的一些配置文件和源码,要么就是太繁杂,要么就是太...
基于注解Annotation的最新版SSH(Struts2.3.7+Hibernate4.1.9+Spring3.2.0)整合开发,真正实现零配置。 最新版本Struts、Spring、Hibernate框架整合: struts-2.3.7 spring-framework-3.2.0.RELEASE hibernate-...
《Hibernate 3.2.0 API详解》 Hibernate是一个开源的对象关系映射(ORM)框架,它极大地简化了Java开发者与数据库之间的交互。在Hibernate 3.2.0版本中,该框架进一步优化了性能,增加了新特性,并修复了一些已知...
**基于Struts2.2.6+Mybatis3.2.0+Spring3.1的整合项目** 这个项目是一个典型的Java Web应用框架整合实例,它将三个流行的技术——Struts2、Mybatis和Spring——集成在一起,以实现高效、灵活的后端开发。下面将分别...
《Hibernate 3.2.0 参考指南中文版》是Java开发人员深入理解Hibernate ORM框架的重要参考资料。Hibernate是一款开源的对象关系映射(ORM)工具,它为Java开发者提供了便捷的方式来管理数据库操作,使得开发者无需...
《Hibernate 3.2.0 参考指南中文版》是一个详尽的资源,涵盖了Java对象关系映射框架Hibernate的核心概念和技术。这个压缩包包含了针对Hibernate 3.2.0版本的完整参考文档,旨在帮助开发者更好地理解和使用这一强大的...
Struts 2.3.7、Spring 3.2.0 和 MyBatis 3.1 是三个在Java企业级开发中广泛使用的开源框架,它们分别负责不同的职责,共同构建了一个强大的后端服务架构。 **Struts 2.3.7** 是一个基于MVC(Model-View-Controller...