Struts2+hibernate实现用户登录和增删改查案例
开发工具MyEclipse 10.7.1
创建一个项目 web项目project。
部署好Struts2的开发环境:
1、引入需要的类库文件 jar
2、添加struts2的配置文件 struts.xml //src路径 :classespath:
3、在web.xml添加启动struts2 MVC框架的过滤器
4、添加Hibernate所依赖的jar文件
(注意:如果Hibernate添加的jar文件与struts2添加jar文件 名称完全一致(只需其中之一)(版本不一致保留高本版) )
5、同样添加hibernate的配置文件
Classespath: src路径下面
6、需要添加对应数据库操作的驱动文件jar
在此基础上 对 admin这个类 完成 增删改查的操作。
在src下搭建开发框架,如图所示:
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>
<include file="struts-admin.xml"/>
struts>
struts-admin.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>
<package name="admin" namespace="/csdn" extends="struts-default">
<action name="adminLogin" class="www.csdn.project.action.AdminAction"
method="login">
<result name="success">/manager/index.jspresult>
<result name="login">/index.jspresult>
action>
<action name="adminlist" class="www.csdn.project.action.AdminAction"
method="getAllObjects">
<result name="success">/manager/admin/admin_list.jspresult>
action>
<action name="getAdminById" class="www.csdn.project.action.AdminAction" method="getObjectById">
<result name="success">/manager/admin/admin_sing.jspresult>
action>
<action name="adminInsert" class="www.csdn.project.action.AdminAction" method="saveObject">
<result type="redirectAction">
<param name="actionName">adminlist.actionparam>
result>
action>
<action name="deleteAdminById" class="www.csdn.project.action.AdminAction" method="deleteObjectById">
<result name="success" type="redirectAction">
<param name="actionName">adminlist.actionparam>
result>
action>
<action name="findAdminById" class="www.csdn.project.action.AdminAction" method="findAdminById">
<result name="success">/manager/admin/admin_update.jspresult>
action>
<action name="updateAdmin" class="www.csdn.project.action.AdminAction" method="updateObject">
<result name="success" type="redirectAction">
<param name="actionName">adminlist.actionparam>
result>
action>
package>
struts>
hibernate.cfg.xml文件:
xml version="1.0" encoding="UTF-8"?>
DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="myeclipse.connection.profile">localhostproperty>
<property name="connection.url">
jdbc:mysql://localhost:3306/bookstore
property>
<property name="connection.username">rootproperty>
<property name="connection.password">rootproperty>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
property>
<mapping resource="www/csdn/project/domain/Admin.hbm.xml" />
session-factory>
hibernate-configuration>
web.xml文件:
xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
首先,domain层(www.csdn.project.domain)的编写;
Admin.java文件:
package www.csdn.project.domain;
public class Admin implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer adminId;
private String adminName;
private String adminPassword;
public Admin() {
}
public Admin(String adminName, String adminPassword) {
this.adminName = adminName;
this.adminPassword = adminPassword;
}
public Admin(String adminName, String adminPassword, String adminEmail) {
this.adminName = adminName;
this.adminPassword = adminPassword;
}
public Integer getAdminId() {
return this.adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
public String getAdminName() {
return this.adminName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
public String getAdminPassword() {
return this.adminPassword;
}
public void setAdminPassword(String adminPassword) {
this.adminPassword = adminPassword;
}
@Override
public String toString() {
return "Admin [adminId=" + adminId
+ ", adminName=" + adminName + ", adminPassword="
+ adminPassword + "]";
}
}
Admin.hbm.xml配置文件;
xml version="1.0" encoding="utf-8"?>
DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="www.csdn.project.domain.Admin" table="admin" catalog="bookstore">
<id name="adminId" type="java.lang.Integer">
<column name="adminId" />
<generator class="identity" />
id>
<property name="adminName" type="java.lang.String">
<column name="adminName" length="20" not-null="true" unique="true" />
property>
<property name="adminPassword" type="java.lang.String">
<column name="adminPassword" length="10" not-null="true" />
property>
class>
hibernate-mapping>
dao层(www.csdn.project.dao)的编写;
AdminDAO.java文件:(封装了查看所有用户信息的方法)
package www.csdn.project.dao;
import java.util.List;
import www.csdn.project.domain.Admin;
public interface AdminDAO extends BaseDAO
public Admin login(String adminName,String adminPass);
public Admin findById(Integer id);
public List
}
然后,BaseDAO.java文件:(这里封装了对用户进行增删改查的方法)
package www.csdn.project.dao;
import java.util.List;
public interface BaseDAO
public List
public T getObjectById(Class
public T loadObjectById(Class
public void saveObject(T entity);
public void deleteObject(T entity);
public void deleteObjectById(PK id);
public void updateObject(T entity);
}
下面是实现两个类中的方法的AdminDAOImpl.java文件:
package www.csdn.project.dao;
import java.util.List;
import www.csdn.project.domain.Admin;
import www.csdn.project.util.BaseHibernateDAO;
import www.csdn.project.util.HiberSessionFactory;
public class AdminDAOImpl extends BaseHibernateDAO implements AdminDAO {
public Admin login(String adminName, String adminPass) {
Admin entity=null;
try{
entity = (Admin) getSession()
.createQuery(
"from Admin a where a.adminName=:adminName and a.adminPassword=:adminPassword")
.setParameter("adminName", adminName).setParameter(
"adminPassword", adminPass).uniqueResult();
}catch (RuntimeException e) {
HiberSessionFactory.closeSession();
}
return entity;
}
public List
return null;
}
public Admin findById(Integer id) {
return null;
}
@SuppressWarnings("unchecked")
public List
List
try{
entities = getSession().createCriteria(entityClass).list();
}catch (RuntimeException e) {
HiberSessionFactory.closeSession();
}
return entities;
}
public Admin getObjectById(Class
Admin entities=null;
try{
entities=(Admin) getSession().get(entityClass, id);
}catch (RuntimeException e) {
HiberSessionFactory.closeSession();
}
return entities;
}
public Admin loadObjectById(Class
Admin entities=null;
try{
entities=(Admin) getSession().load(entityClass, id);
}catch (RuntimeException e) {
HiberSessionFactory.closeSession();
}
return entities;
}
public void saveObject(Admin entity) {
getSession().save(entity);
}
public void deleteObject(Admin entity) {
getSession().delete(entity);
}
public void deleteObjectById(Integer id) {
//this.getSession().delete(this.getObjectById(Admin.class, id));
}
public void updateObject(Admin entity) {
getSession().update(entity);
}
}
这样dao层完成了其作用。
Service层(www.csdn.project.service)事务层的编写;
AdminService.java文件:
package www.csdn.project.service;
import java.util.List;
import www.csdn.project.domain.Admin;
public interface AdminService extends BaseService
public Admin login(String adminName,String adminPass);
public List
}
BaseService.java文件:
package www.csdn.project.service;
import java.util.List;
public interface BaseService
public List
public T getObjectById(Class
public T loadObjectById(Class
public void saveObject(T entity);
public void deleteObject(T entity);
public void deleteObjectById(PK id);
public void updateObject(T entity);
}
AdminServiceImpl.java文件:
package www.csdn.project.service;
import java.util.List;
import org.hibernate.Transaction;
import www.csdn.project.dao.AdminDAO;
import www.csdn.project.dao.AdminDAOImpl;
import www.csdn.project.domain.Admin;
import www.csdn.project.util.BaseHibernateDAO;
import www.csdn.project.util.HiberSessionFactory;
public class AdminServiceImpl extends BaseHibernateDAO implements AdminService{
private AdminDAO adminDAO = new AdminDAOImpl();
public Admin login(String adminName, String adminPass) {
return adminDAO.login(adminName, adminPass);
}
public List
return null;
}
public List
return adminDAO.getAllObjects(entityClass);
}
public Admin getObjectById(Class
return adminDAO.getObjectById(entityClass, id);
}
public Admin loadObjectById(Class
return adminDAO.loadObjectById(entityClass, id);
}
public void saveObject(Admin entity) {
Transaction ts=null;
try {
ts = getSession().beginTransaction();
adminDAO.saveObject(entity);
ts.commit();
} catch (Exception e) {
if (ts != null) {
ts.rollback();
}
} finally {
HiberSessionFactory.closeSession();
}
}
public void deleteObject(Admin entity) {
Transaction ts=null;
try{
ts=getSession().beginTransaction();
adminDAO.deleteObject(entity);
ts.commit();
}catch (Exception e) {
if (ts != null) {
ts.rollback();
}
} finally {
HiberSessionFactory.closeSession();
}
}
public void deleteObjectById(Integer id) {
//调用这个方法的时候,它本身是不是已经打开了一个session
Admin entity = adminDAO.getObjectById(Admin.class, id);
//session 立马关闭了
Transaction ts = null;
try {
ts = getSession().beginTransaction();
adminDAO.deleteObject(entity);
ts.commit();
} catch (Exception e) {
if (ts != null) {
ts.rollback();
}
} finally {
HiberSessionFactory.closeSession();
}
}
public void updateObject(Admin entity) {
Transaction ts=null;
try{
ts=getSession().beginTransaction();
ts.commit();
}catch (Exception e) {
if(ts!=null){
ts.rollback();
}
}finally{
HiberSessionFactory.closeSession();
}
}
}
下面写struts2所需要的action层(www.csdn.action)的编写:
AdminAction.java文件:
package www.csdn.project.action;
import java.util.List;
import www.csdn.project.domain.Admin;
import www.csdn.project.service.AdminService;
import www.csdn.project.service.AdminServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
public class AdminAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer adminId;
private String adminName;
private String adminPassword;
private Admin entity;
private String name;
private List
private AdminService adminService = new AdminServiceImpl();
public int getAdminId() {
return adminId;
}
public void setAdminId(int adminId) {
this.adminId = adminId;
}
public List
return entities;
}
public void setEntities(List
this.entities = entities;
}
public AdminAction() {
System.out.println("action启动~~~");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
public void setAdminPassword(String adminPassword) {
this.adminPassword = adminPassword;
}
public Admin getEntity() {
return entity;
}
public String login() {
entity = adminService.login(adminName, adminPassword);
if (entity != null) {
return SUCCESS;
} else {
return LOGIN;
}
}
public String delete() {
System.out.println("删除成功......");
return SUCCESS;
}
public String getAllObjects(){
entities =adminService.getAllObjects(Admin.class);
return SUCCESS;
}
public String getObjectById(){
entity =adminService.getObjectById(Admin.class, adminId);
return SUCCESS;
}
public String saveObject(){
adminService.saveObject(new Admin(adminName,adminPassword));
return SUCCESS;
}
public String deleteObject(){
adminService.deleteObject(entity);
return SUCCESS;
}
public AdminService getAdminService() {
return adminService;
}
public void setAdminService(AdminService adminService) {
this.adminService = adminService;
}
public String deleteObjectById(){
adminService.deleteObjectById(adminId);
System.out.println("删除成功~~~");
return SUCCESS;
}
public String findAdminById(){
entity=adminService.getObjectById(Admin.class, adminId);
return SUCCESS;
}
public String updateObject(){
entity=adminService.getObjectById(Admin.class, adminId);
entity.setAdminName(adminName);
adminService.updateObject(entity);
return SUCCESS;
}
}
接着写显示页面的代码;
在WebRoot下的index.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>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
head>
<body>
<div align="center">
<h3>
后台管理登陆界面
h3>
<hr />
<form
action="${pageContext.request.contextPath}/csdn/adminLogin.action"
method="post">
用户名:
<input type="text" name="adminName" />
<br />
密 码:
<input type="password" name="adminPassword" />
<br />
<input type="submit" value="Login" />
form>
div>
<div align="center">
${name}
div>
body>
html>
其他显示页面在如图中:
index.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>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
head>
<body>
<div align="center">
<h3>
欢迎${entity.adminName}登录后台管理界面!
h3>
<a href="${pageContext.request.contextPath }/csdn/adminlist.action">管理所有用户a><br>
div>
body>
html>
admin_insert.jsp文件:
admin_list.jsp文件:
admin_sing.jsp文件:
admin_update.jsp文件:
以下是效果图: