SSH框架(Struts2+Spring4+HIbernate5)的简化

今天给大家带来的是一个简单的新闻发布系统

    首先在学习过程中我是深有体会,做事情不要浮躁,不要想着一口吃下一个胖子,

    最最重要的是理解,理解透了学什么东西都是随心所欲的。

开发环境:win10系统

     jdk1.8.0_91     

    

开发工具:

    eclipse-jee-neon-R-win32-x86_64

    mysql5.6

    apache-tomcat-8.0.36

 

接下来开始第一步,之前的那个SSH包都下载好了之后,我们开始写项目。

    首先创建一个数据库,我用的是mysql,因为它比较小,而且用习惯了。

    数据库代码:

     

创建数据库
create database 创建表 use news; create table news( id int primary key auto_increment, title varchar(50) not null, content text not null, begintime datetime not null, username varchar(20) not null );

插入数据
insert into news(title,content,begintime,username) values('美国之死','如何干掉美国...','2012-03-01','xiaowen');
insert into news(title,content,begintime,username) values('美国之死2','如何干掉美国2...','2012-03-02','xiaohong');
insert into news(title,content,begintime,username) values('美国之死3','如何干掉美国3...','2012-03-03','xiaochen');

 

接着咱还是老规矩。新建一个项目,这就不用我多说了吧!

  接着配置web文件

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>znews</display-name>
  <welcome-file-list>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 这是一只拦路虎 -->
<filter>
        <!-- 拦截的名字 -->
        <filter-name>struts2</filter-name>
        <!-- filter所需要的驱动包 -->
        <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>
    
    <!-- 给软件配置一个监听器 -->
        <context-param>
            <!-- 监听器的名字-->
            <param-name>applicationContext</param-name>
            <!-- 监听的路径 -->
            <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <!-- Spring所需要加载的驱动包 -->
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>    
</web-app>

创建一个entiry包,并编写好他的实体类:如下代码  

这是我们的实体类代码:

package news.entity;

import java.util.Date;

public class News {
    private Integer id;
    private String title;
    private String content;
    private Date begintime;
    private String username;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Date getBegintime() {
        return begintime;
    }
    public void setBegintime(Date begintime) {
        this.begintime = begintime;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    

}

给实体类配置一份映射文件  到后面这份配置文件可以用注解代替。

<?xml version="1.0" encoding="UTF-8"?>
<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
  
     <class name="news.entity.News" table="news">
        <id name="id" column="id">
            <generator class="native"></generator>
        </id>
        <property name="title" type="string" length="50" column="title" not-null="true"></property>
        <property name="content" type="text" length="50000" column="content" not-null="true"></property>
        <property name="begintime" type="date" column="begintime" not-null="true"></property>
        <property name="username" type="string" length="20" column="username" not-null="true"></property>
    </class>
</hibernate-mapping>

然后创建一个dao包编写好dao的方法和实现类

 

  

package news.dao;

import java.util.List;

public interface NewsDao {
    public List showAllNews();
    //显示首页所有数据(查询使用的。PS:本例没用到)
    public String findNews();
    public String deleteSingleNews(Integer id);
}
package news.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import news.entity.News;

//@Repository("myNewsDao")
@Repository
@Scope("prototype")
public class NewsDaoImpl implements NewsDao {
    
    @Autowired
    //@Qualifier("mySessionFactory")
    //@Resource(name="mySessionFactory")
    private SessionFactory sf;

    @Override
    public List showAllNews() {

        Session session = sf.getCurrentSession();
        Query query = session.createQuery("from News");
        List<News> allNewList  = query.getResultList();

        
    
    
        return allNewList;
    }

    @Override
    public String findNews() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String deleteSingleNews(Integer id) {
        Session session = sf.openSession();
        //Session session = sf.getCurrentSession();//它会与事务关联,并且在事务后自动关闭
        Query query = session.createQuery("from News where id=:myid");
        
        //query.setParameter(0, id);
        query.setParameter("myid", id);
        List<News> deleteList  = query.getResultList();
        //如果搜索出来是1条,就删除,如果是0条就不管了
        if ( deleteList.size()==1 ) {
            News news = deleteList.get(0);
            System.out.println("删除对象:"+news.getTitle()+ " Id:"+news.getId());
            session.getTransaction().begin();
            session.delete(news);
            session.getTransaction().commit();
            session.close();
            
        }
        
        
        return "deleteOK";
    }

}

写完dao类,接着我们写service类和它的实现类

package news.service;

import java.util.List;

public interface NewsService {
    public List showAllNews();
    //显示首页所有数据(查询使用的。PS:本例没用到)
    public String findNews();
    public String deleteSingleNews(Integer id);
}
package news.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import news.dao.NewsDao;
import news.entity.News;

//@Service("myNewsService")
@Service
@Scope("prototype")
public class NewsServiceImpl implements NewsService {

    //Autowired和Qualifier 属于spring的注解,
    
    
    //jdk自带注解resource可以替代Autowired
    /*
     * 用resource的好处:
     * 1. 代码与spring 解耦,不依赖于spring
     * 2. 代码中没有spring的存在,可以随时切换任意一套类似spring的框架
     */
    @Autowired

    private NewsDao nd;
    

    @Override
    public List showAllNews() {
        //可以增加一个业务逻辑,比如:把文章的内容进行截取为20字符
        //通过DAO获取数据
        List<News> allNewList = nd.showAllNews();
        //在return 之间,可以进行各种业务逻辑操作
        
        return allNewList;
    }

    @Override
    public String findNews() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String deleteSingleNews(Integer id) {
        //需要做以下判断,例如有没有权限删除,又或者判断下面是否有级联子子记录
        
        //当可以删除时,调用DAO给直接删除
        String returnValue = "deleteFailed";
        returnValue = nd.deleteSingleNews(id);
        // TODO Auto-generated method stub
        return returnValue;
    }

}

 然后我们写action类

  

package news.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import news.entity.News;
import news.service.NewsService;

//@Controller("myNewsAction")
@Controller               //默认就是类的首字母小写newsAction
@Scope("prototype")
public class NewsAction extends ActionSupport {
    
    private String message;
    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    //获取从客户端传递过来的值
    private Integer id;
    public Integer getId(){
        return this.id;
    }
    
    //strtus自动的赋值
    public void setId(Integer id) {
        this.id = id;
    }
    
    
    @Autowired
    //@Qualifier("myNewsService")
    //@Resource(name="myNewsService")
    private NewsService ns;
    
    //定义1个list用于前端jsp显示
    private List<News> allNewList;

    public List<News> getAllNewList() {
        return allNewList;
    }

    //显示首页所有数据
    public String showAllNews(){
        //调用service 中的showAllNews,获取所有的数据,
        //然后保存到
        allNewList = ns.showAllNews();
        return "success";
    }
    
    //显示首页所有数据(查询使用的。PS:本例没用到)
    public String findNews(){
        return "";
    }
    
    public String deleteSingleNews(){
        System.out.println("从客户端传递过来的ID:"+id);
        String returnValue = ns.deleteSingleNews(id);
        return returnValue;
    }
    
}

写好了之后,我们再来写struts2配置文件

  

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.objectFactory" value="spring" />

<!-- 第1步:先定义一个包 -->
    <package name="mypck001" extends="struts-default">
        <action name="NewsAction_*" class="newsAction" method="{1}">
            <result name="success">/WEB-INF/jsp/index.jsp</result>
            <!-- 希望删除成功后,重新执行1次首页显示内容 -->
            <result name="deleteOK" type="redirectAction">NewsAction_showAllNews.action?message=deleteok&amp;id=${id}</result>
        </action>
        
    </package>
</struts>

配置好了这份文件,我们还缺一份applicationContext文件。

  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="    
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <!-- 原理:自动注入processor解析器,用来解析注解 -->
    <!-- <context:annotation-config/> -->

    <!-- 自动扫描包,也会自动注入解释器,所以不需要 context:annotation-config -->
    <context:component-scan base-package="news"></context:component-scan>



    <!-- 引入外部属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入连接池,包含了数据库用户名,密码等等信息 -->
        <property name="dataSource" ref="myDataSource" />

        <!-- 配置Hibernate的其他的属性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
                <!-- 开机自动生成表 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>news/entity/News.hbm.xml</value>
            </list>
        </property>


    </bean>

    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 每300秒检查所有连接池中的空闲连接 -->
        <property name="idleConnectionTestPeriod" value="300"></property>
        <!-- 最大空闲时间,900秒内未使用则连接被丢弃。若为0则永不丢弃 -->
        <property name="maxIdleTime" value="900"></property>
        <!-- 最大连接数 -->
        <property name="maxPoolSize" value="2"></property>

    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="del*" propagation="REQUIRED" />
            <tx:method name="mod*" propagation="REQUIRED" />
            <tx:method name="*" propagation="REQUIRED" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="interceptorPointCuts"
            expression="execution(*   
        news.dao.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
    </aop:config>

</beans>
            

好了!这就是一个简单的新闻发布系统。虽然说没怎么详细的讲解,但是注释都在里面

 

 

  

posted @ 2016-10-25 14:55  可遇丶不可求  阅读(965)  评论(0编辑  收藏  举报