简单用户登录页面struts2整合hibernate3演示步骤:

第一步先加入struts2框架,引入struts2.3.5文档库,

struts2.3.5整合hibernate3.2.0 实例详解_hibernate

在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">&nbsp;</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">&nbsp;</td>

</tr>

</table>

</td>

</tr>

</table>

</td>

<td width="1%">&nbsp;</td>

<td width="50%" valign="middle">

<table width="100%"height="59" border="0" cellpadding="0" cellspacing="0">

<tr>

<td width="4%">&nbsp;</td>

<td width="96%" height="30" valign="top"></td>

</tr>

<tr>

<td>&nbsp;</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= class="easyui-linkbutton" οnclick="submitForm()">登 录</a>

<a href= class="easyui-linkbutton" οnclick="clearForm()">清 除</a>

</tr>

</table>

</form>

</td>

</tr>

<tr>

<td height="29" align="right" valign="bottom">

<div align="center" style="height:20px;">

</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文档库

struts2.3.5整合hibernate3.2.0 实例详解_java_02

在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;

}

}

​​