您好,欢迎来到纷纭教育。
搜索
您的当前位置:首页第六章+SSH整合开发实例

第六章+SSH整合开发实例

来源:纷纭教育
 1 / 22

Test.java【界面】 EmployeeServiceInter Employee.java EmployeeService.java【业务操作】 Hibernate 数据库 表单 Login.jsp 失败 EmployeeServiceInter LoginAction.java 成功 MainFrame.jsp Employee.java EmployeeService.java【业务操作】 Hibernate 数据库

雇员薪资管理系统 具体的步骤: 1. 2. 3. 4.

创建web项目 引入spring开发包

编写applicationContext.xml文件(或者beans.xml),把该文件放在src目录下。 测试一下spring 是否成功。

public class TestService { public void sayHello(){ System.out.println(\"Hello\"); } }

public class Test { public static void main(String[] args) { ApplicationContext ac=new

ClassPathXmlApplicationContext(\"applicationContext.xml\"); TestService testService=(TestService)ac.getBean(\"testService\"); testService.sayHello(); } }

5. 加入hibernate开发包。

6. 因为我们是ssh,所以我们hibernate的核心文件就被spring接管了。hibernate.cfg.xml 文件对象

映射文件,SessionFactory在spring的文件中配置即可。 7. 在 applicationContext.xml中配置数据源

2 / 22

8. 配置SessionFactory对象

class=\"org.springframework.orm.hibernate3.LocalSessionFactoryBean\"> com/domain/Employee.hbm.xml

hibernate.dialect=org.hibernate.dialect.OracleDialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false

9. 编写domain对象和映射文件Employee.hbm.xml ->测试srping和hibernate是否可以结合使用->ok

public class Employee { private Integer id; private String name; private String email;

3 / 22

private String pwd; private Integer grade;

private java.util.Date hiredate; private Float salary;

public Employee(String name, String email, String pwd, Integer grade, Date hiredate, Float salary) { this.name = name; this.email = email; this.pwd = pwd; this.grade = grade; this.hiredate = hiredate; this.salary = salary; }

public Employee() { } }

\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">

4 / 22

public class Test { public static void main(String[] args) { ApplicationContext ac=new

ClassPathXmlApplicationContext(\"applicationContext.xml\"); // TestService testService=(TestService)ac.getBean(\"testService\"); // testService.sayHello(); Employee employee=new Employee(\"ddc\",\"abc@126.com\",\"111\",1,new java.util.Date(),234.56f); SessionFactory

sessionFactory=(SessionFactory)ac.getBean(\"sessionFactory\"); Session s=sessionFactory.openSession(); Transaction ts=s.beginTransaction(); s.save(employee); ts.commit(); }

}

启动mysql服务,连接数据库,观察记录是否插入成功。

10. 建立接口,考虑分层设计

public interface EmployeeServiceInter { //声明一些方法 public void addEmployee(Employee e); public List showEmployee(); public void updEmployee(Employee e); //根据id删除雇员 public void delEmployee(Integer id);

5 / 22

}

public class EmployeeService implements EmployeeServiceInter { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void addEmployee(Employee e) { Session s=sessionFactory.openSession(); Transaction ts=s.beginTransaction(); s.save(e); ts.commit(); } public void delEmployee(Integer id) { // TODO Auto-generated method stub } public List showEmployee() { // TODO Auto-generated method stub return null; } public void updEmployee(Employee e) { // TODO Auto-generated method stub }

}

11. 使用事务管理器来统一管理事务。

class=\"org.springframework.orm.hibernate3.HibernateTransactionManager\">

6 / 22

//这里配置@Transactional的作用是让spring的事务管理器接管EmployeeService中的所有事务

@Transactional

public class EmployeeService implements EmployeeServiceInter { private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void addEmployee(Employee e) { // Session s=sessionFactory.openSession(); // Transaction ts=s.beginTransaction(); // s.save(e); // ts.commit(); sessionFactory.getCurrentSession().save(e); } }

public class Test { public static void main(String[] args) { ApplicationContext ac=new

ClassPathXmlApplicationContext(\"applicationContext.xml\"); // TestService testService=(TestService)ac.getBean(\"testService\"); // testService.sayHello(); Employee employee=new Employee(\"aaddc\",\"abc@126.com\",\"111\",1,new java.util.Date(),234.56f); // SessionFactory

sessionFactory=(SessionFactory)ac.getBean(\"sessionFactory\"); // Session s=sessionFactory.openSession(); // Transaction ts=s.beginTransaction(); // s.save(employee); // ts.commit(); EmployeeServiceInter

employeeServiceInter=(EmployeeServiceInter)ac.getBean(\"employeeService\"); employeeServiceInter.addEmployee(employee); }

7 / 22

}

12. 整合struts

13. 引入struts开发包

14. 创建struts-config.xml 方法 /WEB-INF 目录下 ,创建login.jsp和mainframe.jsp

struts-config.xml

\"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd\">

login.jsp

管理员登录

id:

pw:

mainframe.jsp

8 / 22

请选择您需要的操作


添加雇员

显示雇员

删除雇员

查询雇员

退出

public class EmployeeForm extends ActionForm { private String id; private String pwd; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }

public class LoginAction extends DispatchAction { //响应登陆请求 public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //取出表单,先简单验证 EmployeeForm employeeForm=(EmployeeForm)form; System.out.println(\"success\"); if(\"123\".equals(employeeForm.getPwd())){

9 / 22

}

return mapping.findForward(\"ok\"); }else{ return mapping.findForward(\"err\"); } }

//响应注销请求

public ActionForward loginout(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return super.execute(mapping, form, request, response); } 15. 在web.xml中配置我们的struts

struts org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml 0

struts *.do 16. 修改index.jsp

10 / 22

17. 让spring接管action

问题:如果还没有在spring中配置struts组件,如何获得一个service

spring管理各层applicationContext.xml 原来的方法:每调用一次action,都需要调用

ClassPathXmlApplicationContext。因此我们

struts组件配置.. 可以让tomcat启动的时候,同时初始化spring容器

和struts容器。

我们的tomcat在启动的时候,就会实例化spring容

ApplicationContext ac=new ClassPathXml(\"xx\");

ServletContext.setAttribute(\"名字\

ac 内存: bean 对象 databaseSource... name=\"sessionFactory\"

ref=\"sessionFactory\"/>

Web.xml

contextConfigLocation

classpath:applicationContext.xml

org.springframework.web.context.ContextLoaderListener

ActionForward login

11 / 22

// 如果没有将我们的spring容器交给tomcat去管理,我们需要如下获取bean

// ApplicationContext ac=new

ClassPathXmlApplicationContext(\"applicationContext.xml\");

// 如果将spring容器交给tomcat去实例化,但是没有让spring容器来接管antion,我们需要如下获取 // 通过下列语句可以直接获取到spring容器实例,也就是ApplicationContext // WebApplicationContext ctx= // WebApplicationContextUtils. getWebApplicationContext(this.getServlet().getServletContext());

// 从spring容器中获取bean // EmployeeServiceInter

employeeServiceInter=(EmployeeServiceInter)ctx.getBean(\"employeeService\"); 添加验证方法

public interface EmployeeServiceInter { //声明一些方法 public void addEmployee(Employee e); public List showEmployee(); public void updEmployee(Employee e); //根据id删除雇员 public void delEmployee(Integer id); //如果该雇员存在,则返回该雇员的所有信息,否则返回空 public Employee checkEmployee(Employee e); }

实现验证方法 public Employee checkEmployee(Employee e) { String hql=\"from Employee where id=? and pwd=?\"; List

list=sessionFactory.getCurrentSession().createQuery(hql).setString(0, e.getId()+\"\").setString(1,e.getPwd()).list(); if (list.size()==1){ return list.get(0); }else{ return null; } }

//响应登陆请求

public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { EmployeeForm employeeForm=(EmployeeForm)form; // if(\"123\".equals(employeeForm.getPwd())){ // return mapping.findForward(\"ok\");

12 / 22

// }else{ // return mapping.findForward(\"err\"); // } WebApplicationContext ctx=WebApplicationContextUtils. getWebApplicationContext(this.getServlet().getServletContext()); EmployeeServiceInter

employeeServiceInter=(EmployeeServiceInter)ctx.getBean(\"employeeService\"); // 构建一个Employee对象 Employee e=new Employee(); e.setId(Integer.parseInt(employeeForm.getId())); e.setPwd(employeeForm.getPwd()); e=employeeServiceInter.checkEmployee(e); if(e!=null){ //把雇员信息放入session,以备后用 request.getSession().setAttribute(\"loginuser\",e) ; return mapping.findForward(\"ok\"); }else{ return mapping.findForward(\"err\"); } }

接管action

1) 在struts-config.xml文件中添加如下代码配置:

value=\"org.springframework.web.struts.DelegatingRequestProcessor\"/>

13 / 22

2) 在applicationcontext.xml文件中配置我们的action路径

Struts-config中的type就可以不要了

3) 这我们就可以通过spring容器来获取action,和配置action的一些属性. loginACtion中获取spring容器也可以不要了

public class LoginAction extends DispatchAction { EmployeeServiceInter employeeServiceInter; public EmployeeServiceInter getEmployeeServiceInter() { return employeeServiceInter; } public void setEmployeeServiceInter(EmployeeServiceInter employeeServiceInter) { System.out.println(\"通过setEmployeeServiceInter获取\"); this.employeeServiceInter = employeeServiceInter; } //响应登陆请求 public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //取出表单,先简单验证 EmployeeForm employeeForm=(EmployeeForm)form; // System.out.println(\"success\"); // if(\"123\".equals(employeeForm.getPwd())){ // return mapping.findForward(\"ok\"); // }else{ // return mapping.findForward(\"err\"); // } // 如果没有将我们的spring容器交给tomcat去管理,我们需要如下获取bean // ApplicationContext ac=new

ClassPathXmlApplicationContext(\"applicationContext.xml\");

// 如果将spring容器交给tomcat去实例化,但是没有让spring容器来接管antion,我们需要如下获取 // 通过下列语句可以直接获取到spring容器实例,也就是ApplicationContext // WebApplicationContext ctx=

14 / 22

// WebApplicationContextUtils. // getWebApplicationContext(this.getServlet().getServletContext()); // 构建一个Employee对象 Employee e=new Employee(); e.setId(Integer.parseInt(employeeForm.getId())); e.setPwd(employeeForm.getPwd());

// 从spring容器中获取bean // EmployeeServiceInter

employeeServiceInter=(EmployeeServiceInter)ctx.getBean(\"employeeService\"); e=employeeServiceInter.checkEmployee(e); if(e!=null){ //把雇员信息放入session,以备后用 request.getSession().setAttribute(\"loginuser\",e) ; return mapping.findForward(\"ok\"); }else{ return mapping.findForward(\"err\"); } } }

4) 通过使用sping来接管我们的action,还有一个好处,可以解决action 是单例的问题.

通过在applicationContext.xml文件中配置属性 session”/>

15 / 22

18. 添加欢迎信息

欢迎${loginuser.name} 请选择您需要的操作


添加雇员

显示雇员

删除雇员

查询雇员

退出

19. 完成添加雇员的任务

mainFrame.jsp EmployeeAction.java addEmpUi.jsp

public class EmployeeAction extends DispatchAction { private EmployeeServiceInter employeeServiceInter; public ActionForward addEmpUi(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(\"goAddEmpUi\"); } //处理添加雇员请求 public ActionForward addEmp(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { //简单测试 EmployeeForm employeeForm=(EmployeeForm)form;

16 / 22

// System.out.println(employeeForm.getEmail()+\" \"+employeeForm.getGrade()); // return null; //创建Employee对象 Employee e=new Employee(); e.setEmail(employeeForm.getEmail()); e.setGrade(Integer.parseInt(employeeForm.getGrade()) ); e.setHiredate(new java.util.Date()); e.setName(employeeForm.getName()); e.setPwd(employeeForm.getPwd()); e.setSalary(Float.parseFloat(employeeForm.getSalary())); try { employeeServiceInter.addEmployee(e); } catch (Exception e1) { System.out.println(e1.getMessage()); return mapping.findForward(\"opererr\"); } return mapping.findForward(\"operok\"); } public EmployeeServiceInter getEmployeeServiceInter() { return employeeServiceInter; } public void setEmployeeServiceInter(EmployeeServiceInter employeeServiceInter) { this.employeeServiceInter = employeeServiceInter; } }

在struts-config.xml中配置EmployeeAction

17 / 22

创建addEmpUi.jsp

添加雇员

name:
E-Mail:
grade:
pwd:
salary:

修改Mainframe.jsp

欢迎${loginuser.name} 请选择您需要的操作


href=\"${pageContext.request.contextPath}/Employee.do?flag=addEmpUi\">添加雇员

显示雇员

删除雇员

查询雇员

退出

在spring中配置EmployeeAction

修改EmployeeForm

public class EmployeeForm extends ActionForm { private String id; private String pwd; private String name;

18 / 22

private String email; private String grade; private String salary;

public String getSalary() { return salary; }

public void setSalary(String salary) { this.salary = salary; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getEmail() { return email; }

public void setEmail(String email) { this.email = email; }

public String getGrade() { return grade; }

public void setGrade(String grade) { this.grade = grade; }

public String getId() { return id; }

public void setId(String id) { this.id = id; }

public String getPwd() { return pwd; }

public void setPwd(String pwd) { this.pwd = pwd; }

}

创建err.jsp

操作失败

返回主界面

创建ok.jsp

19 / 22

恭喜,操作成功



返回继续添加

返回主界面

在struts-config.xml中配置全局跳转

20. 项目优化

目前这个项目的代码复用性不好,我们需要重新整理.

通过在web层和业务层间增加了一套基础接口来提高代码的复用性.

实现 继承 @Transactional EmployeeService.java[业务操作] EmployeeServiceInter 继承 BasicServiceInter (基础接口) 实现 BasicService(抽象类)

public interface BasicServiceInter { //声明一些常用方法 //1.通过id获取对象 public Object findById(Class clazz,java.io.Serializable id); //2.根据hql查询 public List executeQuery(String hql,Object []parameters); //3.带分页查询 public List executeQueryByPage(String hql,Object []parameters,int pageNow,int pageSize); //4.添加对象 public void add(Object obj); //5.统一的执行hql——>修改 “update domain对象 where ???”

20 / 22

}

public List executeUpdate(String hql,Object []parameters);

//事务的实现也放在这里 @Transactional

public abstract class BasicService implements BasicServiceInter { private SessionFactory sessionFactory; //EmployeeService中的定义sessionFactory就可以不要了 public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void add(Object obj) { this.sessionFactory.getCurrentSession().save(obj); } public List executeQuery(String hql, Object[] parameters) { Query

query=this.sessionFactory.getCurrentSession().createQuery(hql); //注入??值 if(parameters!=null && parameters.length>0){ for(int i=0;i21 / 22

}

public Object findById(Class clazz, Serializable id) { // TODO Auto-generated method stub return null; }

修改EmployeeServiceInter

public interface EmployeeServiceInter extends BasicServiceInter{ //如果该雇员存在,则返回该雇员的所有信息,否则返回空 public Employee checkEmployee(Employee e); }

修改EmployeeService

public class EmployeeService extends BasicService implements EmployeeServiceInter { public Employee checkEmployee(Employee e) { String hql=\"from Employee where id=? and pwd=?\"; Object []parameters={e.getId(),e.getPwd()}; List list=this.executeQuery(hql, parameters); if(list.size()==1){ return (Employee)list.get(0); }else{ return null; } }

}

修改EmployeeAction

try { employeeServiceInter.add(e); } catch (Exception e1) { System.out.println(e1.getMessage()); return mapping.findForward(\"opererr\"); }

22 / 22

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- fenyunshixun.cn 版权所有 湘ICP备2023022495号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务