ssh初步整合(一)——实现简单的单表CRUD

博主基于前面对spring、struts2、hibernate的简单学习,进行ssh整合实现单表的CRUD,此版本中spring未对事物进行控制且没有采用注解的方式。
项目结构图:
这里写图片描述
开发环境:win7、eclipse、Oracle
框架:spring 2.5、hibernate3.6、struts2.3

一、整合spring

1.导入jar包:
这里写图片描述
2.添加spring配置文件applicationContext.xml
在eclipse中需要手动在src下创建:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
           <bean id="..." class="....">
           <property name="...." value="...."></property>
           </bean>
</beans>

我们需要在…的地方进行配置。

二、整合hibernate

1.导入jar包,整合数据库连接:
这里写图片描述
lib下的required中的jar包
这里写图片描述
orcale包
这里写图片描述
日志包及连接池包
这里写图片描述
2.在applicationContext.xml中配置dateSource设置数据库连接字符串、用户名、密码、驱动

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
           <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
           <property name="username" value="scott"></property>
           <property name="password" value="tiger"></property>
           <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"></property>
           </bean>

2.applicationContext.xml中得到sessionFactory:

<bean id="sessionFactroy" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
             <!--获取数据源       -->
            <property name="dataSource" ref="dataSource"></property>
            <property name="hibernateProperties">
             <!--设置sql语句为展示 -->
            <props>
            <prop key="hibernate.show_sql">true</prop>
            </props>
            </property>
            <property name="mappingResources">
            <!--建立关系映射 -->
            <list>
            <!--配置关系映射路径 -->
            <value>com/it/ssh/entity/Person.hbm.xml</value>
            </list>
            </property>
            </bean>

引用第一步设置好的datasource及设置sql_show、获取获取sessionfactory,并将实体类配置文件的引入。
注意:这里需要创建Person实体、数据库创建对应表、以及Person.hbm.xml文件,共有三个属性:

public class Person {

    private int pid;
    private String pname;
    private String pwd;
    //set、get及构造省略

Person.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
        <!-- 映射定义根元素 -->
<hibernate-mapping package="com.it.ssh.entity">
    <!--class中name为java类的名称 ,table则为数据库中的表名  -->
    <class name="Person" table="person">
        <!--id为主键  type为主键类型  colum为字段名  -->
        <id name="pid" type="int" column="pid">
            <!-- 为id添加唯一标示  hibernate中部分生成器-->
            <generator class="sequence">
            <!-- 在oracle中使用序列生产自增id  此序列名为数据库中已建立的序列名-->
                <param name="sequence">seq_person</param>
            </generator>
        </id>
        <property name="pname" type="string"  />
        <property name="pwd" type="string"></property>  
    </class>
</hibernate-mapping>

3.建立dao层并将 sessionfactory注入:
PersonDao.java

package com.it.ssh.dao;

import java.util.List;

import com.it.ssh.entity.Person;

public interface PersonDao {

    public boolean login(Person person);
    public boolean add(Person person);
    public boolean update(Person person);
    public boolean delete(Person person);
    public Person queryById(Person person);
    public List<Person> queryAll();
}

PersonDaoImpl.java

package com.it.ssh.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.it.ssh.dao.PersonDao;
import com.it.ssh.entity.Person;

public class PersonDaoImpl implements PersonDao {
    //此时采用的就是设置注入法
    private SessionFactory sessionFactory;
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public boolean login(Person person) {
        String hql = "from Person where pid = ? and pwd = ?";
        Session session = sessionFactory.openSession();
        Query q = session.createQuery(hql);
        q.setInteger(0, person.getPid());
        q.setString(1, person.getPwd());
        Object obj = q.uniqueResult();
        boolean flag = false;
        if(obj!=null){
            flag = true;
        }
        session.close();
        return flag;
    }

    @Override
    public boolean add(Person person) {
         Session session = sessionFactory.openSession();
            //开启事务
            Transaction tran = session.beginTransaction();
            session.save(person);
            //提交事物
            tran.commit();
            //关闭session
            session.close();
            return true;
    }

    @Override
    public boolean update(Person person) {

       Session session = sessionFactory.openSession();

        Transaction tran = session.beginTransaction();
        session.update(person);;

        tran.commit();
        session.close();
        return true;
    }

    @Override
    public boolean delete(Person person) {
        Session session = sessionFactory.openSession();

        Transaction tran = session.beginTransaction();
        session.delete(person);

        tran.commit();
        session.close();
        return true;
    }

    @Override
    public Person queryById(Person p) {

        Session session = sessionFactory.openSession();
        Transaction tran = session.beginTransaction();
        Person person = (Person) session.get(Person.class, p.getPid());

        tran.commit();
        session.close();
        return person;
    }

    @Override
    public List<Person> queryAll() {

        String hql = "from Person";
        Session session = sessionFactory.openSession();
        Transaction tran = session.beginTransaction();
        Query q = session.createQuery(hql);

        List<Person> list = q.list();
        tran.commit();
        return list;
    }

}

此时需将dao层配置在applicationContext.xml:

 <bean id="personDao" class="com.it.ssh.dao.impl.PersonDaoImpl">
            <property name="sessionFactory" ref="sessionFactroy"></property>
            </bean>

4.建立service层并进行配置:
PersonService.java

package com.it.ssh.service;

import java.util.List;

import com.it.ssh.entity.Person;

public interface PersonService {

    public boolean login(Person person);
    public boolean add(Person person);
    public boolean update(Person person);
    public boolean delete(Person person);
    public Person queryById(Person person);
    public List<Person> queryAll();
}

PersonServiceImpl.java

package com.it.ssh.service.impl;

import java.util.List;

import com.it.ssh.dao.PersonDao;
import com.it.ssh.entity.Person;
import com.it.ssh.service.PersonService;

public class PersonServiceImpl implements PersonService {

    private PersonDao personDao;

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }


    public boolean login(Person person) {
        return personDao.login(person);
    }


    public boolean add(Person person) {
        return personDao.add(person);
    }


    public boolean update(Person person) {
        return personDao.update(person);
    }


    public boolean delete(Person person) {
        return personDao.delete(person);
    }


    public Person queryById(Person person) {
        return personDao.queryById(person);
    }


    public List<Person> queryAll() {
        return personDao.queryAll();
    }

}
此时需将Service层配置在applicationContext.xml:
     <bean id="personService" class="com.it.ssh.service.impl.PersonServiceImpl">
            <property name="personDao" ref="personDao"></property>
    </bean>

三、整合struts2

1.导入jar包
这里写图片描述
2.将struts过滤器配置在web.xml

  <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>

3.action类设置 模型驱动
PersonAction.java

package com.it.ssh.action;

import java.util.List;
import com.it.ssh.entity.Person;
import com.it.ssh.service.PersonService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class PersonAction extends ActionSupport implements ModelDriven<Person> {
    //模型驱动
    Person person = new Person();
    //spring设值注入
    private PersonService personService;
    //域模型
    private Person p;

    public Person getP() {
        return p;
    }


    public void setP(Person p) {
        this.p = p;
    }
    //域模型
    private List list;

    public List getList() {
        return list;
    }


    public void setList(List list) {
        this.list = list;
    }


    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    //模型驱动方法
    @Override
    public Person getModel() {
        // TODO Auto-generated method stub
        return person;
    }


    public String login() throws Exception {
        boolean flag = personService.login(person);
        String path = "input";
        if(flag){
            show();
            path = "success";
        }
        return path;
    }
    public String show() {
        list = personService.queryAll();
        return "success";
    }
    public String del() {
        boolean result = personService.delete(person);
        String path = "false";
        if(result) {
            show();
            path = "success";
        }
        return path;
    }
    public String showId() {

    p = personService.queryById(person);

    String path = "input";
    if (person!=null) {
        path = "findsuccess";
    }
    return path;
    }
    public String upd() {

        boolean flag = personService.update(p);
        String path = "input";
        if (flag) {
            show();
            path = "success";
        }
        return path;
    }
    public String add() {

                boolean flag = personService.add(person);
                show();
                return "success";

    }
}

4struts.xml配置

<action name="personAction" class="personAction">
            <result>show.jsp</result>
            <result name="findsuccess">upUser.jsp</result>
            <result name="input" type="redirect">login.jsp</result>
        </action>

5.将action注入applicationContext.xml,引用spring设置好的dao层

  <bean name="personAction" class="com.it.ssh.action.PersonAction">
            <property name="personService" ref="personService"></property>
            </bean>

此时应注意将struts中action的class与applicationContext中bean的name一致,这样在程序启动时,才会将personService注入personAction,否则personService为空值;
6.将applicationContext.xml配置到web.xml,使得在服务器启动时自动加载applicationContext.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

还需加入spring监听器

<listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

四、jsp页面

这里只给出body中内容,头部除需要引入<%@ taglib prefix="s" uri="/struts-tags" %>外没有需要修改的的地方。
login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>   

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<s:form action="personAction!login" method="post">
    <s:textfield name="pid" label="帐号"></s:textfield>
    <s:password name="pwd" label="密码"></s:password>
    <tr>
        <td colspan="2">
            <s:submit value="提交" theme="simple"></s:submit>
            <s:reset value="重置" theme="simple"></s:reset>
        </td>
    </tr>
</s:form>

</body>
</html>

show.jsp

<center>
<a href="addUser.jsp" >添加用户</a>
<a href="personAction!show" >显示用户</a>

<table border="1">
<tr>
<th>pid</th>
<th>pname</th>
<th>pwd</th>
<th colspan="2">操作</th>
</tr>
<s:iterator value="list" status="st" var="user" >
<tr>
        <td><s:property value="#user.pid"/></td>
        <td><s:property value="#user.pname"/></td>
        <td><s:property value="#user.pwd"/></td>
        <td><a href="personAction!del?pid=<s:property value='pid'/>" >删除</td>
        <td><a href="personAction!showId?pid=<s:property value='pid'/>" >更新</td></td>
    </tr>
  </s:iterator>
</table>
</center>
</body>

adduser.jsp

<body >
<center>
<s:form action="personAction!add" method="post">
<s:textfield name="pname" label="用户名"></s:textfield>
<s:textfield name="pwd" label="密码"></s:textfield>
<tr>
<td colspan="2">
    <s:submit theme="simple" value="提交"></s:submit>
    <s:submit theme="simple" value="重置"></s:submit>
</td>
</tr>
</s:form>
</center>
</body>

upuser.jsp

<body>
<center>
<s:form action="personAction!upd" method="post">
<s:hidden name="p.pid" ></s:hidden>
<s:textfield name="p.pname" label="用户名"></s:textfield>
<s:textfield name="p.pwd" label="密码"></s:textfield>
<tr>
<td colspan="2">
    <s:submit theme="simple" value="提交"></s:submit>
    <s:submit theme="simple" value="重置"></s:submit>
</td>
</tr>
</s:form>
</center>
</body>

效果图:
这里写图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值