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下搭建开发框架,如图所示:
项目开始:
目录:
org.hibernate.dialect.MySQLDialect
jdbc:mysql://localhost:3306/test
root
123456
com.mysql.jdbc.Driver
true
true
update
thread
1)创建entity包
2)Students.java
package entity;
import java.util.Date;
public class Students {
private String sid;
private String sname;
private String gender;
private Date birthday;
private String address;
@Override
public String toString() {
return "Students [address=" + address + ", birthday=" + birthday
+ ", gender=" + gender + ", sid=" + sid + ", sname=" + sname
+ "]";
}
public Students() {
}
public Students(String sid, String sname, String gender, Date birthday,
String address) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.birthday = birthday;
this.address = address;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package entity;
public class Users {
private int uid;
private String username;
private String password;
public Users() {
}
public Users(int uid, String username, String password) {
this.uid = uid;
this.username = username;
this.password = password;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
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;
}
}
1)Students.hbm.xml
//创建配置对象
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true,true);
1)UsersDao.java 接口
public interface UsersDao {
public boolean usersLogin(Users u);
}
package serviceImpl;
public class UsersDaoImpl implements UsersDao {
public boolean usersLogin(Users u) {
//事务对象
Transaction tx=null;
String sql="";
try{
Session session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
sql="from Users where username=? and password=? ";
Query query=session.createQuery(sql);
query.setParameter(0, u.getUsername());
query.setParameter(1,u.getPassword());
List list=query.list();
tx.commit();//提交事务
if(list.size()>0){
return true;
}else{
return false;
}
}catch (Exception e) {
e.printStackTrace();
return false;
}finally{
if(tx!=null){
tx=null;
}
}
}
}
package test.userImpl;
public class TestUserDaoImpl {
@Test
public void testUserLogin(){
Users u=new Users(1,"张三","123");
UsersDaoImpl udao=new UsersDaoImpl();
Assert.assertEquals(true, udao.usersLogin(u));
}
}
SuperAction.java
public class SuperAction extends ActionSupport implements ServletContextAware,
ServletRequestAware, ServletResponseAware ,SessionAware{
private static final long serialVersionUID = 1L;
protected ServletContext context;
protected HttpServletRequest request;
protected HttpServletResponse response;
protected Map session;
public void setServletContext(ServletContext context) {
this.context=context;
}
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public void setServletResponse(HttpServletResponse response) {
this.response=response;
}
public void setSession(Map session) {
this.session = session;
}
}
package action;
import com.opensymphony.xwork2.ModelDriven; //模型驱动
import entity.Users;
public class UsersAction extends SuperAction implements ModelDriven{
private static final long serialVersionUID = 4317500994450323565L;
private Users user=new Users();
//用户登录动作
public String login(){
UsersDao udao=new UsersDaoImpl();
if(udao.usersLogin(user)){
return "login_success";
}else{
return "login_failure";
}
}
public Users getModel() {
return this.user;
}
}
/users/users_login_success.jsp
/users/users_login.jsp
//用户登录动作
public String login(){
UsersDao udao=new UsersDaoImpl();
if(udao.usersLogin(user)){
//在session中保存登录成功的用户名
session.put("loginUserName", user.getUsername());
return "login_success";
}else{
return "login_failure";
}
}
@SkipValidation
//用户注销操作,本操作不进行表单输入验证
public String logout(){
if(session.get("loginUserName")!=null){
session.remove("loginUserName");
}
return "logout_success";
}
/users/users_login.jsp
欢迎${sessionScope.loginUserName}使用本系统
@Override
public void validate() {
if("".equals(user.getUsername().trim()) ){
this.addFieldError("usernameError", "用户名不能为空!");
}
if(user.getPassword().trim().length()<6){
this.addFieldError("userpasswordError", "密码不能小于6位!");
}
}
@SkipValidation
//用户注销操作,本操作不进行表单输入验证
public String logout(){}
/users/Users_login_success.jsp
/users/Users_login.jsp
/users/Users_login.jsp
/users/Users_login.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
@Test
public void testSaveStudents(){
Session session=HibernateSessionFactory.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
Students s1=new Students("800001","张三丰","男",new Date(),"武当山");
Students s2=new Students("800002","郭靖","男",new Date(),"桃花岛");
Students s3=new Students("800003","黄蓉","女",new Date(),"桃花岛");
session.save(s1);
session.save(s2);
session.save(s3);
tx.commit();
session.close();
}
//学生业务逻辑接口
public interface StudentsDao {
//查询所有
public List queryAllStudents();
//查询单个
public Students queryStudentsBySid(String sid);
//增
public boolean addStudents(Students s);
//改
public boolean updateStudents(Students s);
//删
public boolean deleteStudents(String sid);
}
//查询所有
public List queryAllStudents() {
Transaction tx=null;
List list=null;
String sql="";
try{
Session session=HibernateSessionFactory.getSessionFactory().openSession();
tx=session.beginTransaction();
sql="from Students ";
Query query=session.createQuery(sql);
list=query.list();
tx.commit();
}catch(Exception ex){
ex.printStackTrace();
tx.commit();
}finally{
if(tx!=null){
tx=null;
}
}
return list;
}
1)Students.xml
public String query(){
StudentsDao sDao=new StudentsDaoImpl();
List list=sDao.queryAllStudents();
if(list!=null && list.size()>0){
session.setAttribute("stundesList", list);
}
return "Students_query_success";
/stundents/Students_query_success.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
">
" οnclick="javascript: return confirm('真的要删除吗?');">删除
1)StudentsDaoImpl.java
public boolean deleteStudents(String sid) {
Transaction tx=null;
List list=null;
String sql="";
try{
Session session=HibernateSessionFactory.getSessionFactory().openSession();
tx=session.beginTransaction();
Students s=(Students) session.get(Students.class,sid);
session.delete(s);
tx.commit();
return true;
}catch(Exception ex){
ex.printStackTrace();
tx.commit();
return false;
}finally{
if(tx!=null){
tx=null;
}
}
}
public String delete(){
StudentsDao sDao=new StudentsDaoImpl();
String sid= request.getParameter("sid");
sDao.deleteStudents( sid );
return "delete_success";
}
/students/Students_query_success.jsp
Students_query.action
" οnclick="javascript: return confirm('真的要删除吗?');">删除
public String getNewSid(){
Transaction tx=null;
String sid=null;
String sql="";
try{
Session session=HibernateSessionFactory.getSessionFactory().openSession();
tx=session.beginTransaction();
sql="select max(sid) from Students ";
Query query=session.createQuery(sql);
sid=(String) query.uniqueResult();
if(sid==null || "".equals(sid.trim())){
sid="S00001";
}else{
String temp=sid.substring(1); //取后几位
int tempI=Integer.parseInt(temp)+1; //int + 1
temp=String.valueOf(tempI); //转成string
int len=temp.length(); //数字位数
for(int i=0;i<5-len;i++){
temp="0"+temp;
}
sid="S"+temp;
}
tx.commit();
}catch(Exception ex){
ex.printStackTrace();
tx.commit();
}finally{
if(tx!=null){
tx=null;
}
}
return sid;
}
3-9 添加学生资料-实现添加学生资料业务逻辑
2)StudentsDaoImpl.java
public boolean addStudents(Students s) {
s.setSid(getNewSid());
Transaction tx=null;
String sql="";
try{
Session session=HibernateSessionFactory.getSessionFactory().openSession();
tx=session.beginTransaction();
session.save(s);
tx.commit();
}catch(Exception ex){
ex.printStackTrace();
tx.commit();
return false;
}finally{
if(tx!=null){
tx=null;
}
}
return true;
}
public String add(){
StudentsDao sDao=new StudentsDaoImpl();
try {
Students s=new Students();
s.setSname(request.getParameter("sname"));
s.setGender(request.getParameter("gender"));
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date birthday;
birthday = sdf.parse(request.getParameter("birthday"));
s.setBirthday(birthday);
s.setAddress(request.getParameter("address"));
sDao.addStudents(s);
} catch (ParseException e) {
e.printStackTrace();
}
return "add_success";
}
/students/Students_add_success.jsp
添加学生
继续添加?
public Students queryStudentsBySid(String sid) {
Transaction tx=null;
Students s=null;
String sql="";
try{
Session session=HibernateSessionFactory.getSessionFactory().openSession();
tx=session.beginTransaction();
sql="from Students where sid=?";
Query query=session.createQuery(sql);
query.setParameter(0,sid);
s=(Students) query.uniqueResult();
tx.commit();
}catch(Exception ex){
ex.printStackTrace();
tx.commit();
}finally{
if(tx!=null){
tx=null;
}
}
return s;
}
public String modify(){
StudentsDao sDao=new StudentsDaoImpl();
Students s=sDao.queryStudentsBySid(request.getParameter("sid"));
session.put("modify_students", s);
return "modify_success";
}
/students/Students_modify.jsp
4)Students_query_success.jsp
">
3-12 修改学生资料-实现修改学生资料action和页面调用测试
5)StudentsAction.java
public String save(){
StudentsDao sDao=new StudentsDaoImpl();
try {
Students s=new Students();
s.setSid(request.getParameter("sid"));
s.setSname(request.getParameter("sname"));
s.setGender(request.getParameter("gender"));
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date birthday;
birthday = sdf.parse(request.getParameter("birthday"));
s.setBirthday(birthday);
s.setAddress(request.getParameter("address"));
sDao.addStudents(s);
} catch (ParseException e) {
e.printStackTrace();
}
return "save_success";
}
6)Struts.xml
/students/Students_modify_success.jsp
7)Students_modify.jsp
你可能感兴趣的:(数据库--数据为王,关于框架--方便)