本章简介
1.项目分层
2.创建MyHibernateSessionFactory
3.设计用户接口和实现类
4.设计所有Action父类
5.设计用户Action类
6.页面调用
7.完成显示登录成功用户名和注销功能
8.显示报错信息
1.项目分层
- 实体层(模型层):entity包 学生类、用户类
- 数据库层(模型层):db包
- 接口层(模型层):service包
- 接口实现层(模型层):service.impl包
- 动作层(控制层):action包
- Jsp页面(视图层):整个项目所有的JSP页面
2.创建MyHibernateSessionFactory(会话工厂工具类)
- 创建自定义的session工厂类
将来我们可以调用工具类getSessionFactory()静态方法,返回会话工厂的一个实例
会话工厂工具类MyHibernateSessionFactory.java
package db;import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;public class MyHibernateSessionFactory {private static SessionFactory sessionFactory;//会话工厂属性//构造方法私有化。保证单例模式private MyHibernateSessionFactory(){}//公有的静态方法,获得会话工厂对象public static SessionFactory getSessionFactory(){if(sessionFactory==null){Configuration config=new Configuration().configure();ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();sessionFactory=config.buildSessionFactory(serviceRegistry);return sessionFactory;}else{return sessionFactory;}}}
3.设计用户接口和实现类
- 用户业务逻辑接口:包含跟用户相关的所有一些方法,比方说用户的登录、注销等
- 用户业务逻辑实现类:接口当中的方法都是抽象的,没有实现,我们还要实现它具体的接口实现类
用户业务逻辑接口
package service;import entity.Users;//用户业务逻辑接口
public interface UsersDAO {//用户登录方法public boolean usersLogin(Users u);}
用户业务逻辑实现类
package service.impl;import java.util.List;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;import db.MyHibernateSessionFactory;import entity.Users;
import service.UsersDAO;public class UsersDAOImpl implements UsersDAO{public boolean usersLogin(Users u) {// TODO Auto-generated method stub//事务对象Transaction tx = null;String hql = "";try{Session session = MyHibernateSessionFactory.getSessionFactory().getCurrentSession();tx=session.beginTransaction();//开启事务hql = "from Users where username=? and password=?";//?是占位符,两个问号表示两个参数Query query = session.createQuery(hql);//传入hql语句query.setParameter(0, u.getUsername());//传递参数(由于上面的hql语句用了两个占位符表示要传入两个参数)query.setParameter(1, u.getPassword());List list=query.list();//查询,返回结果集tx.commit();//提交事务//判断是否查到用户if(list.size()>0){return true;}else{return false;}}catch(Exception ex){ex.printStackTrace();//打印异常堆栈return false;}finally{if(tx!=null){//tx.commit();//不能重复提交事务tx=null;}}}}
测试方法是否正确
package service.impl;import junit.framework.Assert;import org.junit.Test;import service.UsersDAO;import entity.Users;public class TestUsersDAOImpl {@Testpublic void testUsersLogin(){Users u= new Users(1,"zhangsan","123456");UsersDAO udao=new UsersDAOImpl();Assert.assertEquals(true, udao.usersLogin(u));//断言}}
4.设计所有Action父类
- 设计action父类
- 继承ActionSupport(ActionSupport内置了很多拦截器,方便我们以后的使用)
- 为了获得常用的内置对象采用耦合IOC方式注入属性。
需要实现以下三个接口:
ServletRequestAware
ServletResponseAware
ServletContextAware
package action;import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;import com.opensymphony.xwork2.ActionSupport;//所有Action动作的父类
public class SuperAction extends ActionSupport implements ServletRequestAware,ServletResponseAware,ServletContextAware{/*** */private static final long serialVersionUID = 1L;protected HttpServletRequest request;//请求对象protected HttpServletResponse response;//响应对象protected HttpSession session;//会话对象protected ServletContext application;//全局对象public void setServletContext(ServletContext application) {// TODO Auto-generated method stubthis.application=application;}public void setServletResponse(HttpServletResponse response) {// TODO Auto-generated method stubthis.response=response;}public void setServletRequest(HttpServletRequest request) {// TODO Auto-generated method stubthis.request=request;this.session=this.request.getSession();}}
5.设计用户Action类
- 设计用户Action类,采用模型驱动接收表单数据。
struts2接收表单数据的方式:普通属性、领域对象、模型驱动
设计用户Action类
package action;import service.UsersDAO;
import service.impl.UsersDAOImpl;import com.opensymphony.xwork2.ModelDriven;import entity.Users;public class UsersAction extends SuperAction implements ModelDriven<Users>{/*** */private static final long serialVersionUID = 1L;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() {// TODO Auto-generated method stubreturn this.user;} }
需要在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><package name="default" namespace="/" extends="struts-default"></package><package name="users" namespace="/users" extends="default"><action name="*_*" class="action.{1}Action" method="{2}"><result name="login_success">/users/Users_login_success.jsp</result><result name="login_failure">/users/Users_login.jsp</result></action> </package></struts>
6.页面调用
- 登录页面调用用户登录动作。
User_login.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!-- 这是一个html5 doctype声明 -->
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8" /><title>用户登录</title></head>
<style type="text/css">
body{margin:0px;padding:0px;overflow:hidden;
}
#wrapper{position:absolute;width:100%;height:100%;min-width:1280px;min-height:680px;overflow-x:hidden;overflow-y:hidden;background-image: -moz-linear-gradient(top,#77D1F6, #2F368F);background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #77D1F6),color-stop(1, #2F368F));
}
#header{height:100px;width:100%;
}
#logo{position:absolute;float:left;margin-left:5%;margin-top:30px;height:40px;width:160px;text-align:center;
}
#heading{position:relative;float:left;margin-left:20%;margin-top:-18px;height:110px;width:60%;border-radius: 18px;background-color:#1C75BC;opacity:0.6;
}
#heading #title{margin-top:40px;text-align:center;font-family:微软雅黑;font-size:24px;font-weight:bold;
}
#heading #subTitle{margin-top:10px;text-align:center;font-family:Courier New;
}
#main{margin-top:20px;height:500px;width:100%;
}
#mainBg{position:relative;float:left;margin-left:20%;margin-top:0px;height:500px;width:60%;border-radius: 18px;background-color:#000000;opacity:0.5;
}
#mainPanel{position:relative;margin:25px;height:450px;border-radius: 18px;background-image: -moz-linear-gradient(top,#EBEBEB, #BFBFBF);background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #EBEBEB),color-stop(1, #BFBFBF));
}
#mainPanel #left{float:left;border-right:2px solid #F6F6F6;position:relative;top:10%;height:80%;width:49%;border-right-style:groove;
}
#mainPanel #image{position:relative;height:256px;width:256px;left:15%;top:12%;background-image:url('../images/admin.png');
}
#mainPanel #right{float:left;position:relative;height:90%;width:49%;top:5%;
}
#welcome{margin-top:20px;height:60px;width:100%;vertical-align: middle;display: inline-block;line-height: 60px;text-align:center;
}
#welcome #welcome-text{font-size:38px;font-weight:bold;font-family:微软雅黑;text-shadow: 0 1px 1px #F6F6F6;
}
#user-name{height:35px;width:100%;margin-top:20px;vertical-align: middle;display: inline-block;line-height: 35px;
}
#user-password{margin-top:20px;height:35px;width:100%;vertical-align: middle;display: inline-block;line-height: 35px;
}
#user-checkcode{margin-top:20px;height:35px;width:100%;vertical-align: middle;display: inline-block;line-height: 35px;
}
#button-group{margin-top:10px;height:35px;width:100%;vertical-align: middle;display: inline-block;line-height: 35px;text-align:center;
}
#error-tip{margin-top:20px;margin-left:5%;height:40px;width:90%;vertical-align: middle;display: inline-block;line-height: 35px;text-align:center;border-bottom:2px solid #F6F6F6;border-bottom-style:groove;
}
#error-tip #tip-text{font-size:18px;font-weight:bold;font-family:微软雅黑;color:red;
}
.item{margin-left:20px;font-family:微软雅黑;font-size:20px;font-weight:bold;float: left;width:80px;margin-top: 3px;text-align: center;text-shadow: 0 1px 1px #F6F6F6;
}
.input{vertical-align: middle;display: inline-block;
}
#checkcode-img{margin-top:3px;height:20px;width:60px;
}
.form-input{height:20px;
}
.btn{border:1px solid #cccccc;cursor:pointer;margin:10px 5px;height:40px;width:80px;text-align:center;border-radius: 4px;border-color: #636263 #464647 #A1A3A5;text-shadow: 0 1px 1px #F6F6F6;background-image: -moz-linear-gradient(center top, #D9D9D9, #A6A6A6 49%, #A6A6A6 50%);background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #D9D9D9),color-stop(1, #A6A6A6));
}
#footer{margin-top:20px;width:100%;
}
#footer #text{text-align:center;font-size:14px;font-family:微软雅黑;font-weight:bold;
}
</style>
<body>
<div id="wrapper"><div id="header"><div id="logo"></div><div id="heading"><div id="title">后台管理系统</div><div id="subTitle">Ver 1.0</div></div></div><div id="main"><div id="mainBg"><div id="mainPanel"><div id="left"><div id="image"></div></div><div id="right"><form name="loginForm" action="<%=path%>/users/Users_login.action" method="post"><!-- start of login form --><div id="welcome"><span id="welcome-text">管 理 登 录</span></div><div id="user-name"><span class="item">用户名:</span><span><input type="text" name="username" class="form-input"></span></div><div id="user-password"><span class="item">密 码:</span><span class="input"><input type="password" name="password" class="form-input"></span></div><div id="button-group"><input type="submit" class="btn" value="登录"/><input type="reset" class="btn" value="重置"/></div><div><s:fielderror/> <!-- 显示表单验证的出错信息 --></div><!-- end of form --></form></div></div></div></div><div id="footer"><div id="text">Copyright © 2009-2015 All Rights Reserved Powered By Simoniu</div></div>
</div>
</body>
</html>
7.完成显示登录成功用户名和注销功能
8.显示报错信息
- 在登录表单上显示表单验证出错信息