【SSH】添加数据到Student表

简介

  在项目开发中,为了充分利用各个框架的优点,优势互补,常常将Struts2、Spring、Hibernate这三个框架整合使用。这个整合的过程也有多种,比如:是否使用hibernate.cfg.xml,是否使用注解等。本实例使用hibernate.cfg.xml和注解。

实例

Tools:Eclipse、MySQL、Struts2、Spring4、Hibernate3
1、导包。本实例所需基础jar包:单击下载。
2、项目目录和代码。项目结构如图1-1所示,代码也在下面一并列出。

【SSH】添加数据到Student表_第1张图片
图1-1 项目目录结构

@Namespace("/")
@ParentPackage("struts-default")
@Controller
public class StudentAction extends ActionSupport implements ModelDriven<Student> {
    //封装数据
    private Student student = new Student();

    @Override
    public Student getModel() {
        return this.student;
    }

    @Autowired
    private StudentService studentService;
    @Action(value ="studentAction_add",results={@Result(name="add",location="/success.jsp")})
    public String add(){
        this.studentService.saveStudent(student);
        return "add";
    }
}

其中的注解:@Namespace(“/”)、@ParentPackage(“struts-default”)、@Action()代替了Struts.xml文件中的配置。

@Repository
public class StudentDaoImpl implements StudentDao {
    //提供Hibernate模板
    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Override
    public void save(Student student) {
        this.hibernateTemplate.save(student);
    }

    @Override
    public void update(Student student) {
        this.hibernateTemplate.update(student); 
    }

    @Override
    public void delete(Student student) {
        this.hibernateTemplate.delete(student);
    }

    @Override
    public Student findById(Integer id) {
        return this.hibernateTemplate.get(Student.class, id);
    }

    @Override
    public List findAll() {
        List students = null;
        for(Object o:this.hibernateTemplate.find("from Student")){
            students.add((Student)o);
        }
        return students;
    }
}

项目中的两个接口文件代码没有列出,可根据实现类自行脑补。

@Entity
@Table(name="student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer ID;
    private Integer Sno;
    private String Sname;
    private String Saddress;
    //属性的getter和setter方法省略......
    //注解@Entity、@Table、@Id、@GeneratedValue代替了hibernate.hbm.xml
}
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;
    @Transactional
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Transactional
    public void saveStudent(Student student) {
        this.studentDao.save(student);
    }

    @Transactional
    public void updateStudent(Student student) {
        this.studentDao.update(student);    
    }

    @Transactional
    public void deleteStudent(Student student) {
        this.deleteStudent(student);    
    }

    @Transactional(readOnly = true)
    public Student findStudentById(Integer id) {
        return this.studentDao.findById(id);
    }

    @Transactional(readOnly = true)
    public List findAllStudent() {
        return this.studentDao.findAll();
    }
}

其中注解@Transactional为Spring事务操作,在applicationContext.xml中也对事务进行了配置。


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <context:component-scan base-package="cn.jujianfei">context:component-scan>
    
    <bean id ="sessionFactory" class= "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        
        <property name ="configLocation" value="classpath:hibernate.cfg.xml">property>
    bean>
    
    <bean id = "hibernateTemplate" class ="org.springframework.orm.hibernate3.HibernateTemplate">
        
        <property name ="sessionFactory" ref ="sessionFactory">property>
    bean>
    
    
    <bean id ="txManager" class ="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name ="sessionFactory" ref="sessionFactory">property>
    bean>
    
    <tx:annotation-driven transaction-manager="txManager" />
beans>

hibernate.cfg.xml文件配置



<hibernate-configuration>
    <session-factory>
        
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        property>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/dbname
        property>
        <property name="connection.username">rootproperty>
        <property name="connection.password">jujianfeiproperty>
        
        <property name="dialect">
            org.hibernate.dialect.MySQL5Dialect
        property>
        
        <property name="show_sql">trueproperty>
        <property name="format_sql">trueproperty>
        <property name="hbm2ddl.auto">updateproperty>
        
        <property name="javax.persistence.validation.mode">noneproperty>
        
        <property name="hibernate.conncetion.provider_class">
            org.hibernate.connection.C3P0ConnectionProvider
        property>
        
        <mapping class="cn.jujianfei.domain.Student" />
    session-factory>
hibernate-configuration>

web.xml配置


<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    listener-class>
listener>

<filter>
    <filter-name>struts2filter-name>
    <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    filter-class>
filter>
<filter-mapping>
    <filter-name>struts2filter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

前台页面index.jsp

<body>
    <form action="${pageContext.request.contextPath}/studentAction_add" method ="post">
        学号:<input type ="text" name ="Sno" /><br>
        姓名:<input type ="text" name ="Sname" /><br>
        地址:<input type ="text" name ="Saddress"/><br>
        <input type ="submit" value="添加" />
    form>
body>

成功跳转页面success.jsp

<title>successPagetitle>
head>
<body>
    添加成功!
body>
html>

总结

  关于本实例的数据流向,我所理解的大致路线为:

1、前台表单提交数据(Sno,Sname,Saddress)
2、加载web.xml文件
3、StudentAction通过Struts2提供的模型驱动方式获取请求数据
4、调用StudentServiceImpl-->StudentDaoImpl-->数据库
5、StudentAction返回结果,页面跳转
// applicationContext.xml文件在其中属于运筹帷幄的角色,贯穿全局

  在SSH整合的过程中,个人认为:Struts主要负责前后台数据的交互;Spring在中间控制协调控制,尤其是对实体类的管理;Hibernate负责对数据库的访问。对于Struts2的拦截器机制、值栈,Spring的事务、注解,Hibernate的缓存和数据检索等方面的知识,算是SSH的核心和重点 ,这些需要慢慢积累。

你可能感兴趣的:(Java)