开发前需要的工具要准备好,我使用的是myeclipse来做的开发,也可以使用eclipse,但需要安装插件,服务器使用Tomcat7.0,数据库使用mysql,数据库图形化界面使用navicat,开发中需要的jar包如下:struts的一些核心jar包(可以到struts官网去下载),hibernate的jar包,在hibernate官网下载后解压出其lib目录下required中的jar包,还需要连接数据库的jar包,和开发中做测试的junit的jar包。
首先,我们创建一个web项目,将我们提取准备好的jar包导入项目的WEB-INF目录下的lib文件夹,然后通过右键项目,选择build path方式来将jar添加到项目中来;
在web.xml中添加过滤器和映射如下,如何确定输入的过滤器正确,可以通过按住ctrl和鼠标移到filter-class值dispatcher.ng上,有变化说明是正确的;
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
接着在src中添加struts.xml文件,该文件可以在strust官网下的空白项目中找到,直接粘过来即可。
<package name="users" namespace="/users" extends="struts-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>
<result name="logout_success">/users/Users_login.jsp</result>
<result name="input">/users/Users_login.jsp</result><!--注意加上这句,不然表单验证会出错 -->
</action>
</package>
<package name="students" namespace="/students" extends="struts-default">
<action name="*_*" class="action.{1}Action" method="{2}">
<result name="query_success">/students/Students_query_success.jsp</result>
<result name="delete_success" type="chain">Students_query</result>
<result name="add_success">/students/Students_add_success.jsp</result>
<result name="modify_success">/students/Students_modify.jsp</result>
<result name="find_success">/students/Students_modify.jsp</result>
<result name="save_success">/students/Students_modify_success.jsp</result>
</action>
</package>
action的名称是通过通配符*来表示的,例如action名为Student_query,则class为StudentAction,方法名为query;
其次加入hibernate.cfg.xml文件,配置信息如下
<session-factory>
<property name="connection.username">root</property>
<property name="connection.password">123123</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql:///test?useUnicode=true&characterEncoding=UTF-8
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">
thread
</property>
<mapping resource="entity/Students.hbm.xml" />
<mapping resource="entity/Users.hbm.xml" />
</session-factory>
root为用户名,123123为登录密码,test为连接的数据库名.mapping 是映射的实体数据类型,
新建一个entity包,创建两个实体类,Students和Users,Students 私有属性:sid,sname,gender,birthday,address;Users 私有属性:uid,username,password
利用源码生成set/get方法和带参数和不带参数的构造方法,接着在entity中创建Students.hbm.xml和Users.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="entity.Students" table="STUDENTS">
<id name="sid" type="java.lang.String" length="8">
<generator class="assigned"/>
</id>
<property name="sname" type="java.lang.String"/>
<property name="gender" type="java.lang.String"/>
<property name="birthday" type="date"/>
<property name="address" type="java.lang.String"/>
</class>
</hibernate-mapping>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="entity.Users" table="USERS">
<id name="uid" type="int">
<generator class="native"/>
</id>
<property name="username" type="java.lang.String"/>
<property name="password" type="java.lang.String"/>
</class>
</hibernate-mapping>
generator值为native是自动增加的方式,assigned不是自动增加;
此时我们新建一个文件夹Test,创建一个entity包,新建一个测试类TestStudent,添加测试方法testSaveStudents()
@Test
public void testSaveStudents(){
//创建配置对象
Configuration config=new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建sessionFactory
SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
//创建session对象
Session session=sessionFactory.getCurrentSession();
//创建事务对象
Transaction tx=session.beginTransaction();
Students s1=new Students("001","无忌","男",new Date(),"武当");
Students s2=new Students("002","夜华","男",new Date(),"天族");
Students s3=new Students("003","白浅","女",new Date(),"青丘");
session.save(s1);
session.save(s2);
session.save(s3);
tx.commit();
sessionFactory.close();
}
打开数据库发现测试方法保存了三位同学的信息;我们发现在进行数据库操作前需要创建配置对象,服务注册对象很是麻烦,所以我们在src文件夹下创建一个db包,创建hibernate会话工厂来创建配置对象和服务注册对象;
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;
}
}
}
创建service和service.impl包,在service包下新建接口StudentsDAO和UsersDAO
//学生业务逻辑接口
public interface StudentsDAO {
//查询所有学生资料
public List<Students> queryAllStudents();
//根据学生编号查询学生资料
public Students queryStudentsById(String id);
//添加学生资料
public boolean addStudents(Students s);
//修改学生资料
public boolean updateStudents(Students s);
//删除学生资料
public boolean deleteStudents(String id);
//用户业务逻辑接口
public interface UsersDAO {
//用户登录方法
public boolean usersLogin(Users u);
紧接着在service.impl包下创建接口StudentsDAO的实现类StudentsDAOImpl,创建UsersDAO的实现类UsersDAOImpl
public class StudentsDAOImpl implements StudentsDAO{
//查询所有学生资料
public List<Students> queryAllStudents() {
Transaction tx=null;
List<Students> list=null;
String hql="";
try{
Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
session.beginTransaction();//开启事务
hql="from Students";
Query query=session.createQuery(hql);
list=query.list();
session.close();//记得关闭事务
return list;
}catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
return list;
}finally{
if(tx!=null){
tx=null;
}
}
}
//根据学号查询学生资料
public Students queryStudentsById(String sid) {
Transaction tx=null;
Students s=null;
try{
Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();//开启事务
s=(Students)session.get(Students.class, sid);
tx.commit();
return s;
}catch(Exception ex)
{
ex.printStackTrace();
tx.rollback();
return s;
}finally{
if(tx!=null){
tx=null;
}
}
}
//增加学生资料
public boolean addStudents(Students s) {
s.setSid(getNewSid());
Transaction tx=null;
try{
Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
session.save(s);
tx.commit();//事务提交
return true;
}catch(Exception ex){
ex.printStackTrace();
tx.rollback();//事务回滚
return false;
}finally{
if(tx!=null){
tx=null;
}
}
}
//更新学生资料
public boolean updateStudents(Students s) {
Transaction tx=null;
try{
Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
session.update(s);
tx.commit();//事务提交
return true;
}catch(Exception ex){
ex.printStackTrace();
tx.rollback();//事务回滚
return false;
}finally{
if(tx!=null){
tx=null;
}
}
}
//删除学生资料
public boolean deleteStudents(String id) {
Transaction tx=null;
//String hql="";
try{
Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
Students s=(Students)session.get(Students.class, id);
session.delete(s);
tx.commit();
return true;
}catch(Exception ex){
ex.printStackTrace();
tx.rollback();
return false;
}finally{
if(tx!=null){
tx=null;
}
}
}
//生成学生的学号
public String getNewSid(){
Transaction tx=null;
String hql="";
String sid=null;
try{
Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
//获得当前学生的最大编号
hql="select max(sid) from Students";
Query query=session.createQuery(hql);
sid=(String)query.uniqueResult();
if(sid==null||"".equals(sid)){
//给一个默认的最大编号
sid="001";
}else{
//String temp=sid.substring(1);//取后七位
String temp="";
int i=Integer.parseInt(sid);//转为数字
i++;
//再还原为字符串
temp=String.valueOf(i);
int len=temp.length();
//凑够三位
for(int j=0;j<3-len;j++){
temp="0"+temp;
}
//sid="s"+temp;
sid=temp;
}
tx.commit();
return sid;
}catch(Exception ex){
ex.printStackTrace();
tx.rollback();
return null;
}finally{
if(tx!=null){
tx=null;
}
}
}
}
public boolean usersLogin(Users u) {
//事务对象
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);
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 ex){
ex.printStackTrace();
return false;
}finally{
if(tx!=null){
//tx.commit();
tx=null;
}
}
}
}
注意:事务开启了完成操作后要将事务提交,出错要回滚,不然会出现事务嵌套的错误。
创建action包,新建SuperAction,UsersAction和StudentsAction三个类,
//所有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 stub
this.application=application;
}
@Override
public void setServletResponse(HttpServletResponse response) {
// TODO Auto-generated method stub
this.response=response;
}
@Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request=request;
this.session=this.request.getSession();
}
}
//学生Action类
public class StudentsAction extends SuperAction{
//查询所有学生动作
public String query(){
StudentsDAO sdao=new StudentsDAOImpl();
List<Students> list=sdao.queryAllStudents();
//放进session中
if(list!=null&&list.size()>0){
session.setAttribute("students_list", list);
//return "Students_query_success";
}
return "query_success";
}
//删除学生动作
public String delete(){
StudentsDAO sdao=new StudentsDAOImpl();
String sid=request.getParameter("sid");
sdao.deleteStudents(sid);
return "delete_success";
}
//添加学生
public String add() throws Exception{
Students s=new Students();
s.setSname(request.getParameter("sname"));
s.setGender(request.getParameter("gender"));
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
s.setBirthday(sdf.parse(request.getParameter("birthday")));
s.setAddress(request.getParameter("address"));
StudentsDAO sdao=new StudentsDAOImpl();
sdao.addStudents(s);
return "add_success";
}
//修改学生信息动作
public String modify(){
//获得传递过来的学生编号
String sid=request.getParameter("sid");
StudentsDAO sdao=new StudentsDAOImpl();
Students s=sdao.queryStudentsById(sid);
//保存在会话中
session.setAttribute("modify_students",s);
return "modify_success";
}
//保存修改学生信息动作
public String save() throws Exception{
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");
s.setBirthday(sdf.parse(request.getParameter("birthday")));
s.setAddress(request.getParameter("address"));
StudentsDAO sdao=new StudentsDAOImpl();
sdao.updateStudents(s);
return "save_success";
}
public String find(){
String sid=request.getParameter("sid");
StudentsDAO sdao=new StudentsDAOImpl();
Students s=sdao.queryStudentsById(sid);
//保存到会话中
session.setAttribute("modify_students", s);
return "find_success";
}
}
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)){
//在session中保存登录成功的用户名
session.setAttribute("loginUserName", user.getUsername());
return "login_success";
}else{
return "login_failure";
}
}
//用户注销功能
@SkipValidation
public String logout(){
if(session.getAttribute("loginUserName")!=null){
session.removeAttribute("loginUserName");
}
return "logout_success";
}
public void validate() {
// TODO Auto-generated method stub
//验证用户名不能为空
if("".equals(user.getUsername().trim())){
this.addFieldError("usernameError", "用户名不能为空");
}
//验证密码不少于6位
if(user.getPassword().length()<6){
this.addFieldError("passwordError", "密码不能少于6位");
}
}
public Users getModel() {
// TODO Auto-generated method stub
return this.user;
}
}
验证用户登录中,如果用户名为空和密码少于6位是不能登录的,同时会将出错信息添加到usernameError和passwordError,在Users_login.jsp中加入
<div> <s:fielderror/> <!-- 显示表单验证的出错信息 --></div>
我们演示一遍以上操作:
登录界面,输入用户名密码即可登录;
欢迎界面,点击学生列表可以看到学生信息,点击姓名可进入修改,点击删除即可删除该学生信息,可添加学生信息,学生人数过多时可根据学号查找学生信息;