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

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

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

开发环境: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>

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

  

SSH(Struts2+Spring4+HIbernate5)的简化的更多相关文章

  1. 【SSH】---【Struts2、Hibernate5、Spring4集成开发】【SSH框架整合笔记】

    Struts2.Hibernate5.Spring4集成开发步骤: 一.导入Jar包(基本的大致有41个,根据实际项目的需求自己添加) antlr-2.7.7.jar aopalliance.jar ...

  2. SSH(Struts2+Spring4+Hibernate4)框架教程之配置篇

    SSH(Struts2+Spring4+Hibernate4)框架教程之配置篇 - 若明天不见 - 博客频道 - CSDN.NEThttp://blog.csdn.net/why_still_conf ...

  3. Maven+struts2+spring4+hibernate4的环境搭建

    搭建Maven+struts2+spring4+hibernate4其实并不难!但开始弄的时候还是费了我好大的力气,老是出现这样那样的错误!好了,废话不多说,开始搭建开发环境. 一.Myeclipse ...

  4. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

  5. Struts2+Spring4+Hibernate4整合超详细教程

    Struts2.Spring4.Hibernate4整合 超详细教程 Struts2.Spring4.Hibernate4整合实例-下载 项目目的: 整合使用最新版本的三大框架(即Struts2.Sp ...

  6. 工作笔记3.手把手教你搭建SSH(struts2+hibernate+spring)环境

    上文中我们介绍<工作笔记2.软件开发经常使用工具> 从今天開始本文将教大家怎样进行开发?本文以搭建SSH(struts2+hibernate+spring)框架为例,共分为3步: 1)3个 ...

  7. 【SSH】---【Struts2、Hibernate5、Spring4】【散点知识】

    一.Struts21.1.Struts2的概念Struts2是一个用来开发MVC应用程序的框架,它提供了Web应用程序开发过程中的一些常见问题的解决方案:    ->对来自用户的输入数据进行合法 ...

  8. 【SSH】---【Struts2、Hibernate5、Spring4】【SSH框架整合笔记 】

    一.为什么要使用接口? 三层体系架构上层调用下层的时候最好使用接口,比如action层调用service的时候,private IUserDAO userDAO;这里将属性定义为接口,调用DAO的时候 ...

  9. [java web]Idea+maven+spring4+hibernate5+struts2整合过程

    摘要 最近也在网上找了些教程,试着使用maven进行包依赖关系的管理,也尝试着通过注解的方式来整合ssh框架.在这个过程中,踩了不少的坑.折腾很长时间,才算把架子折腾起来.这里把结果整理下,作为以后工 ...

随机推荐

  1. openresty 前端开发入门一

    OpenResty ™ 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库.第三方模块以及大多数的依赖项.用于方便地搭建能够处理超高并发.扩展性极高的动态 ...

  2. 数据结构:优先队列 基于堆实现(python版)

    #!/usr/bin/env python # -*- coding:utf-8 -*- ''' Author: Minion-Xu ''' #异常类 class HeapPriQueueError( ...

  3. No.004:Median of Two Sorted Arrays

    问题: There are two sorted arrays nums1 and nums2 of size m and n respectively.Find the median of the ...

  4. PHP中this,self,parent三个关键字

    this,self,parent三个关键字从字面上比较好理解,分别是指这.自己.父亲. this是指向当前对象的指针(姑且用C里面的指针来看吧)self是指向当前类的指针parent是指向父类的指针( ...

  5. VS2010中dumpbin工具的使用

    用VS2010生成的.obj文件..lib库..dll库..exe执行文件,如果想查看其中这些文件或库包含了哪些函数以及相关的信息(符号清单),可以通过VS2010自带的dumpbin工具来完成. d ...

  6. shell笔记

    shell:俗称操作系统的"外壳",就是命令解释程序.     是用户与Linux内核之间的接口.     是负责与用户交互,分析.执行用户输入的命令,并给出结果或出错提示.    ...

  7. Atitit 自然语言处理原理与实现 attilax总结

    Atitit 自然语言处理原理与实现 attilax总结 1.1. 中文分词原理与实现 111 1.2. 英文分析 1941 1.3. 第6章 信息提取 2711 1.4. 第7章 自动摘要 3041 ...

  8. Visual Studio 2013 Preview 高清多图先睹为快

    Visual Studio 2013 Preview已经发布.大家可以下载试用了哦: 选项加载明显比之前版本要快很多.

  9. 被我们忽略的HttpSession线程安全问题

    1. 背景 最近在读<Java concurrency in practice>(Java并发实战),其中1.4节提到了Java web的线程安全问题时有如下一段话: Servlets a ...

  10. 升级 python 2.6.6 系统到 2.7.10 版本

    CentOS 6 系统默认 Python 版本是:2.6.6 平时在使用中遇到很多的库要求是 2.7.x 版本的库,比如使用 ConfigParser 库,在 2.6 版本库就不支持没有 value ...