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

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

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

开发环境: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. 【Spring】SpringMVC中浅析Date类型数据的传递

    在控制器中加入如下代码: @InitBinder public void initBinder(ServletRequestDataBinder bin){ SimpleDateFormat sdf ...

  2. python序列,字典备忘

    初识python备忘: 序列:列表,字符串,元组len(d),d[id],del d[id],data in d函数:cmp(x,y),len(seq),list(seq)根据字符串创建列表,max( ...

  3. 怎样在asp中产生10个0-99的随机数

    <% randomize for i=1 to 10 response.write cint(rnd*100) next %> randomize是随机初始化,使用rnd之前必须要先来一句 ...

  4. Django Admin 录入中文错误解决办法

    如果报错....for column 'object_repr' at row 1.就找到此列所在表为django_admin_log,然后插入: ALTER TABLE django_admin_l ...

  5. 服务器开启https协议

    开启Tomcat https服务 发布企业级应用的时候遇到一个问题,就是IOS7.1之后app的下载地址URL必须是https开头的协议,所以服务器必须支持https协议. 实验环境:Mac OSX ...

  6. Hibernate 系列 08 - 对象识别机制

    目录导读: Hibernate 系列 学习笔记 目录 本篇目录: 为了区别不同的对象,有两种识别方法: 1. 内存地址识别(“==”号识别) 2. equals()和hashCode()识别 1. 以 ...

  7. Ctrl-A全选这点事(C#,WinForm)

    所有的文本框,不管单行多行都Ctrl-A全选就好了吧?是啊,很方便.Windows的软件基本都是这样.可为什么我们自己制作的WinForm就默认不是这样呢?谁知道呢,可能是WinForm饱受诟病,要改 ...

  8. MySQL函数

    MySQL数据库提供了很多函数包括: 数学函数: 字符串函数: 日期和时间函数: 条件判断函数: 系统信息函数: 加密函数: 格式化函数: 一.数学函数 数学函数主要用于处理数字,包括整型.浮点数等. ...

  9. JS和ASP.net相互调用问题

    项目开发时,我们有时候会遇到后台asp调用前台的JS函数,又或者前台JS需要调用后台aspx.cs的函数,这里记录下如何处理这些问题 1.  ASP后台代码中,如果需要运行JS函数,则使用Regist ...

  10. ThreadLocal 源码剖析

    ThreadLocal是Java语言提供的用于支持线程局部变量的类.所谓的线程局部变量,就是仅仅只能被本线程访问,不能在线程之间进行共享访问的变量(每个线程一个拷贝).在各个Java web的各种框架 ...