博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ssh整合
阅读量:6546 次
发布时间:2019-06-24

本文共 14127 字,大约阅读时间需要 47 分钟。

 

 

 

一.spring和hibernate进行整合

 创建web项目,引入所需要的jar包

创建对应的数据库

创建数据库对应的实体类以及映射文件

Teacher实体类

public class Teacher {  private   Integer  tId;  //编号  private   Integer  tage; //年龄  private   String  tName;//姓名  private   Date  tDate;      @Overridepublic String toString() {    return "Teacher [tId=" + tId + ", tage=" + tage + ", tName=" + tName            + ", tDate=" + tDate + "]";}public Teacher() {    super();}public Teacher(Integer tId, Integer tage, String tName, Date tDate) {    super();    this.tId = tId;    this.tage = tage;    this.tName = tName;    this.tDate = tDate;}public Integer gettId() {    return tId;}public void settId(Integer tId) {    this.tId = tId;}public Integer getTage() {    return tage;}public void setTage(Integer tage) {    this.tage = tage;}public String gettName() {    return tName;}public void settName(String tName) {    this.tName = tName;}public Date gettDate() {    return tDate;}public void settDate(Date tDate) {    this.tDate = tDate;}  }

Teacher.hbm.xml

创建对应的dao层文件

TeacherDao

public interface TeacherDao {    //新增    void  addTeacher(Teacher teacher);     //删除    void  deleteTeacher(Teacher teacher);    //修改    void  updateTeacher(Teacher teacher);    //查询    List
findTeachers();}

TeacherDaoImpl

/** * HibernateDaoSupport:是spring为hibernate提供的工具类 * getHibernateTemplate()是获取模版! * 什么时候给它赋值的???? * spring容器 通过setHibernateTemplate! */public class TeacherDaoImpl extends HibernateDaoSupport implements TeacherDao {    // 新增    public void addTeacher(Teacher teacher) {        getHibernateTemplate().save(teacher);    }    // 删除    public  void deleteTeacher(Teacher teacher){        getHibernateTemplate().delete(teacher);    }    // 修改    public void updateTeacher(Teacher teacher){        getHibernateTemplate().update(teacher);    }    // 查询    public List
findTeachers(){ return getHibernateTemplate().find("from Teacher"); }}

创建对应的service层文件

 TeacherService

public interface TeacherService {    // 新增    void addTeacher(Teacher teacher);    // 删除    void deleteTeacher(Teacher teacher);    // 修改    void updateTeacher(Teacher teacher);    // 查询    List
findTeachers();}

TeacherServiceImpl

public class TeacherServiceImpl implements TeacherService {    private TeacherDao dao;        //新增    public void addTeacher(Teacher teacher) {       dao.addTeacher(teacher);    }    //删除    public void deleteTeacher(Teacher teacher) {        dao.deleteTeacher(teacher);    }    //修改    public void updateTeacher(Teacher teacher) {        dao.updateTeacher(teacher);    }    //查询所有    public List
findTeachers() { return dao.findTeachers(); } public TeacherDao getDao() { return dao; } public void setDao(TeacherDao dao) { this.dao = dao; } }

创建spring的配置文件以及需要的properties文件

 applicationContext.xml

update
true
true
org.hibernate.dialect.MySQLInnoDBDialect

创建对应的测试类

 TeacherTest

public class TeacherTest {    //新增    @Test    public void  testAdd(){        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");    TeacherService service=    (TeacherService) context.getBean("teacherService");    service.addTeacher(new Teacher(1, 50, "xxxx", new Date()));    }    //删除    @Test    public void  testDel(){        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        TeacherService service=    (TeacherService) context.getBean("teacherService");        Teacher teacher=new Teacher();        teacher.settId(3);        service.deleteTeacher(teacher);    }    //修改    @Test    public void  testUpdate(){        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        TeacherService service=    (TeacherService) context.getBean("teacherService");        Teacher teacher=new Teacher();        teacher.settId(2);        teacher.setTage(50);        service.updateTeacher(teacher);    }    //查询所有    @Test    public void  testFind(){        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");        TeacherService service=    (TeacherService) context.getBean("teacherService");        List
teachers = service.findTeachers(); for (Teacher teacher : teachers) { System.out.println(teacher); } }}

与hibernate整合 不使用 hibernate模版     这种方式 推荐使用  

底层代码

更改之后的TeacherDaoImpl

/** *  */package cn.bdqn.dao.impl;import java.util.List;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import cn.bdqn.bean.Teacher;import cn.bdqn.dao.TeacherDao;/** * HibernateDaoSupport:是spring为hibernate提供的工具类 * getHibernateTemplate()是获取模版! * 什么时候给它赋值的???? * spring容器 通过setHibernateTemplate! *  *  *  * 我们发现 在底层  其实 还是默认调用了 getCurrentSession * 所以我们 直接创建我们自己的SessionFactory *  */public class TeacherDaoImpl implements TeacherDao {    private SessionFactory sessionFactory;        // 新增    public void addTeacher(Teacher teacher) {        sessionFactory.getCurrentSession().save(teacher);    }    // 删除    public  void deleteTeacher(Teacher teacher){        sessionFactory.getCurrentSession().delete(teacher);    }    // 修改    public void updateTeacher(Teacher teacher){        sessionFactory.getCurrentSession().update(teacher);    }    // 查询    public List
findTeachers(){ return sessionFactory.getCurrentSession().find("from Teacher"); } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }

getCurrentSession

/*getCurrentSession 和 OpenSession的区别01.getCurrentSession创建的session会绑定到当前的线程!OpenSession不会    每次都是创建一个新的session02.getCurrentSession创建的session 在事务回滚或者提交的时候,都会自动或关闭 OpenSession不会在sessionFactory创建的时候。hibernate会根据配置创建响应的CurrenSessionContext在getCurrentSession的时候,实际被执行的是CurrenSessionContext.currentSession()如果CurrenSessionContext.currentSession()为空,则调用sessionFactory的OpenSession!*/

底层代码片段

 

 

 

在applicationContext.xml文件中增加currentSession的配置

需要更改的代码块

update
true
true
org.springframework.orm.hibernate3.SpringSessionContext
org.hibernate.dialect.MySQLInnoDBDialect

 二.spring与struts的整合

 创建一个注册界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() + "://"            + request.getServerName() + ":" + request.getServerPort()            + path + "/";%>My JSP 'index.jsp' starting page
用户名:
年龄:

创建对应的servlet处理

public class AddServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8"); //解决乱码问题        String age = request.getParameter("age");        String name = request.getParameter("name");        Teacher teacher = new Teacher();        teacher.settAge(Integer.parseInt(age));        teacher.settName(name);        /*         * 创建Spring容器 这种方式 性能低下! 每次访问servlet都会创建一个容器对象 放在当前新增servlet的init方法中 修改         * 删除 查询 等。。。。。 这样一来 有几个servlet就会有几个spring容器!          * ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");         *          * 怎么能保证 在整个应用程序中 只有一个容器对象! ServletContextListener 整个应用程序的监听器         */        WebApplicationContext context = (WebApplicationContext) this                .getServletContext()                .getAttribute(                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);        System.out.println(context);        // 从容器获取service        TeacherService service = (TeacherService) context                .getBean("teacherService");        // 调用新增的方法        service.addTeacher(teacher);        // 转发到成功界面        request.getRequestDispatcher("success.jsp").forward(request, response);    }}

修改后的web.xml文件

org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:applicationContext.xml
AddServlet
cn.bdqn.servlet.AddServlet
AddServlet
/AddServlet
index.jsp

相应的底层代码

 

 源代码

public WebApplicationContext initWebApplicationContext(ServletContext servletContext)            throws IllegalStateException, BeansException {        if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {            throw new IllegalStateException(                    "Cannot initialize context because there is already a root application context present - " +                    "check whether you have multiple ContextLoader* definitions in your web.xml!");        }        servletContext.log("Initializing Spring root WebApplicationContext");        if (logger.isInfoEnabled()) {            logger.info("Root WebApplicationContext: initialization started");        }        long startTime = System.currentTimeMillis();        try {            // Determine parent for root web application context, if any.            ApplicationContext parent = loadParentContext(servletContext);            // Store context in local instance variable, to guarantee that            // it is available on ServletContext shutdown.            this.context = createWebApplicationContext(servletContext, parent);            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);            currentContextPerThread.put(Thread.currentThread().getContextClassLoader(), this.context);            if (logger.isDebugEnabled()) {                logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +                        WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");            }            if (logger.isInfoEnabled()) {                long elapsedTime = System.currentTimeMillis() - startTime;                logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");            }            return this.context;        }        catch (RuntimeException ex) {            logger.error("Context initialization failed", ex);            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);            throw ex;        }        catch (Error err) {            logger.error("Context initialization failed", err);            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);            throw err;        }    }

 

 开始正式的与struts2进行整合

struts.xml

/success.jsp

 

对应的action

public class AddAction extends ActionSupport {    private  String  name;    private  Integer  age;    /*     * 默认采用了    byName 方式 注入   但是前提 TeacherService的属性名称必须和容器中的service名称一致     * 可以查看default.properties文件  查看     * 我们现在写的方式不是byName     */    private TeacherService  service;         public  String add(){         System.out.println("进入add");         Teacher teacher=new Teacher();         teacher.settAge(age);         teacher.settName(name);         service.addTeacher(teacher);         return  SUCCESS;     }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public TeacherService getService() {        return service;    }    public void setService(TeacherService service) {        this.service = service;    }}

在applicationContext.xml文件中新增

OpenSessionInView模式

在 dao层以及service层创建对应的 根据ID获取Teacher的信息!使用get方式 不会报错!但是使用load方式获取数据的话,就会出现No  Session!因为在前台真正获取数据的时候,事务已经提交了,session也关闭了!这时候 我们需要配置 OpenSessionInView模式!来保证用户获取数据的时候还有session!只需要在web.xml文件中配置如下节点:      
open
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
open
/*
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*

 

转载于:https://www.cnblogs.com/xtdxs/p/6560240.html

你可能感兴趣的文章
hdu 2504
查看>>
Axure产品原型设计工具
查看>>
ASM文件系统
查看>>
ajax学习笔记(原生js的ajax)
查看>>
Hadoop体系结构介绍
查看>>
白话经典算法系列之六 快速排序 快速搞定
查看>>
mysql 函数 事务
查看>>
AJAX2.0
查看>>
将100到200之间的素数输出
查看>>
[故障解决]图文:windows apache无法启用 端口被占用
查看>>
1312 连续自然数和
查看>>
进程/线程介绍
查看>>
SPSS-Friedman 秩和检验-非参数检验-K个相关样本检验 案例解析
查看>>
RabbitMQ数据同步一致性解决方案
查看>>
java UDP server
查看>>
Windows MongoDB安装配置
查看>>
大数据开发实战:Hive优化实战3-大表join大表优化
查看>>
大数据开发实战:Stream SQL实时开发一
查看>>
vue里面的this指向
查看>>
Centos系统安装
查看>>