目的

  通过对ssh框架有了基础性的学习,本文主要是使用注解的方式来简化ssh框架的代码编写。

注意事项:

  1、本文提纲:本文通过一个新闻管理系统的实例来简化ssh框架的代码编写,功能包括查询数据库中所有新闻信息,删除某条新闻信息。

  2、本项目的搭建环境:Windows 8-64位,Eclipse(开发工具),jdk1.8.0_91,Tomcat 8.0,struts-2.3.30-apps,spring-framework-4.2.2.RELEASE,hibernate-release-5.2.2.Final,mysql数据库

 

第一步:在eclipse(开发工具)里创建web项目(项目名称:news),并生成web.xml文件。

第二步:导入本次项目要使用到的jar包(struts2、spring4、hibernate5和mysql)。

第三步:在配置文件web.xml配置一个struts2的过滤器和spring监听器。

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>news</display-name>
<welcome-file-list>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- struts2过滤器 -->
<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>、 <!-- spring监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

注:在welcome-file-list这里我添加了一个jsp页面的链接:默认首页<welcome-file>default.jsp</welcome-file>,进行对action的跳转。

第四步:在Java Resources下的src目录下创建四个包(package)进行分层。

第五步:

1、根据数据库表的字段编写News(实体类)放到news.entity包里。

 package news.entity;

 import java.util.Date;

 import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; /*
* 跟数据库表一致,作为一个java对象
* 1个对象代表的是数据库表中的一行记录
* 1个属性代表的是表中的一个字段
*/
@Entity //声明当前类为hibernate映射到数据库中的实体类
@Table(name="news") //声明table的名称
public class News {
@Id //声明此列为主键,作为映射对象的标识符
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id; @Column(name="title",nullable=false)
private String title; @Column(name="content",nullable=false)
private String content; @Column(name="begintime",nullable=false)
private Date begintime; @Column(name="username",nullable=false)
private String username; public News() {
super();
} 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;
} }

注:在实体类未用到注解前,我们需要编写一个映射文件,使用注解后就可以将原来的映射文件删除。

2、在news.service包里编写NewsService(接口类)和NewsServiceImpl(实现类)。

NewsService(接口类):

 package news.service;

 import java.util.List;

 //创建一个NewsService接口类
public interface NewsService { public List showAllNews(); public String findNews(); public String deleteSingleNews(Integer id);
}

NewsServiceImpl(实现类):

 package news.service;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; import news.dao.NewsDao;
import news.entity.News; //创建NewsServiceImpl(实现类)实现NewsService接口
//使用@Service类注解自动注入,并且作用域范围为非单例
@Service
@Scope("prototype")
public class NewsServiceImpl implements NewsService { //使用spring内置注解@Autowired自动注入实例
@Autowired
private NewsDao nd; @Override
public List showAllNews() { //调用NewsDao的showAllNews方法存入到List<News>集合里
List<News> allNewList=nd.showAllNews();
//返回List集合
return allNewList;
} @Override
public String findNews() {
// TODO Auto-generated method stub
return null;
} @Override
public String deleteSingleNews(Integer id) { //定义一个字符串保存到returnValue变量里
String returnValue="deleteFailed"; //调用NewsDao的deleteSingleNews方法
returnValue=nd.deleteSingleNews(id); //返回returnValue
return returnValue;
} }

3、在news.dao包里编写NewsDao(接口类)和NewsDaoImpl(实现类)。

 NewsDao(接口类):

 package news.dao;

 import java.util.List;

 //创建NewsDao(接口类)
public interface NewsDao { public List showAllNews(); public String findNews(); public String deleteSingleNews(Integer id);
}

NewsDaoImpl(实现类):

 package news.dao;

 import java.util.List;

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository; import news.entity.News; //创建NewsDaoImpl(实现类)实现NewsDao接口
//使用@Repository类注解自动注入,并且作用域范围为非单例
@Repository
@Scope("prototype")
public class NewsDaoImpl implements NewsDao { //使用spring内置注解@Autowired自动注入实例
@Autowired
private SessionFactory sf; @Override
public List showAllNews() {
//重新建立一个新的session
Session session=sf.openSession();
//创建Query
Query query=session.createQuery("from News"); //将结果集保存到List<News>集合里
List<News> allNewList=query.getResultList(); //关闭session
session.close(); //返回List<News>集合
return allNewList;
} @Override
public String findNews() {
// TODO Auto-generated method stub
return null;
} @Override
public String deleteSingleNews(Integer id) {
//重新建立一个新的session
Session session=sf.openSession();
//创建Query并将id值设置为传过来的参数值
Query query=session.createQuery("from News where id=:myid");
query.setParameter("myid", id);
//将结果集保存到List<News>集合里
List<News> deleteList=query.getResultList(); //判断deleteList有没有值,如果有,则执行下面的语句,如果没有,则什么都不做
if(deleteList.size()==1){
//获取deleteList中的值并保存到News对象中
News news=deleteList.get(0);
//在控制台输出:删除对象和id值
System.out.println("删除对象:"+news.getTitle()+" Id:"+news.getId());
//创建事务
session.getTransaction().begin();
//删除对象
session.delete(news);
//提交事务
session.getTransaction().commit();
//关闭session
session.close();
} //返回字符串deleteOK
return "deleteOK";
} }

4、编写NewsAction(action类)。

 package news.action;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionSupport; import news.entity.News;
import news.service.NewsService; //创建NewsAction(action类)继承ActionSupport接口
//使用@Controller类注解自动注入,并且作用域范围为非单例
@Controller
@Scope("prototype")
public class NewsAction extends ActionSupport { //获取从客户端传递过来的值
private Integer id; //strtus自动的赋值
public void setId(Integer id) {
this.id = id;
} //使用spring内置注解@Autowired自动注入实例
@Autowired
private NewsService ns; private List<News> allNewList; public List<News> getAllNewList() {
return allNewList;
} public void setAllNewList(List<News> allNewList) {
this.allNewList = allNewList;
} //查询出所有数据
public String showAllNews(){ allNewList=ns.showAllNews(); return "success";
} //查询单条数据(本例未使用)
public String findNews(){ return "";
} //删除某条数据
public String deleteSingleNews(){ System.out.println("客户端传过来的id值是:"+id); String returnValue=ns.deleteSingleNews(id); return returnValue;
}
}

第六步:编写struts.xml(struts配置文件)、applicationContext.xml(spring配置文件)、jdbc.properties(外部属性文件)。

注:将这些配置文件放到src里。

struts.xml:

 <?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">
<!-- 上面的头,注意版本,从样例里复制过来 showcase.war\WEB-INF\src\java\struts.xml --> <struts>
<!-- 告知Struts2运行时使用Spring来创建对象 -->
<constant name="struts.objectFactory" value="spring"></constant>
<!-- 第1步:先定义一个包 -->
<package name="mynews" extends="struts-default">
<!-- 第2步:定义一个action,配置跳转信息 name 类似于Servlet 注:这里使用了通配符来指定调用的方法-->
<action name="NewsAction_*" class="newsAction" method="{1}">
<!-- 跳转是forward/WEB-INF/是防止jsp不经过action就可以访问-->
<!-- result接收返回的字符串,然后做对应的事情 -->
<result name="success">/WEB-INF/jsp/NewsIndex.jsp</result>
<!-- 删除后通过type="redirectAction"这个类型重新跳转到NewsAction_showAllNews.action刷新页面 -->
<result name="deleteOK" type="redirectAction">NewsAction_showAllNews.action</result>
</action>
</package>
</struts>

applicationContext.xml:

 <?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"> <!-- spring注解解析器 -->
<context:component-scan base-package="news"></context:component-scan> <!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 添加sessionFactory bane ,注意,该类是Spring提供的 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" scope="prototype">
<!-- 注入连接池,包含了数据库用户名,密码等等信息 -->
<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="packagesToScan">
<list>
<!-- value值填写实体类所在的包 -->
<value>news.entity</value>
</list>
</property>
</bean> <!-- 添加c3p0数据库连接池 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>
</beans>

jdbc.properties(外不属性文件):

 jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/news
jdbc.user=root
jdbc.password=123456

第七步:创建一个NewsIndex.jsp页面将所有数据取出来显示到页面上和一个default.jsp页面进行action跳转。

NewsIndex.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!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>
<style>
#showDiv{
width:1000px;
height:70px;
margin: auto;
}
</style>
</head>
<body>
<div id="showDiv" align="center">
<h1>新闻管理系统</h1>
</div>
<div id="msgDiv" align="center">
<table border="1" id="#msgTab">
<tr>
<th>序号</th>
<th>标题</th>
<th>内容</th>
<th>办卡日期</th>
<th>姓名</th>
<th>操作</th>
</tr>
<s:iterator value="allNewList">
<tr>
<td><s:property value="id"/></td>
<td><s:property value="title"/></td>
<td><s:property value="content"/></td>
<td><s:date name="begintime" format="yyyy年MM月dd日"/></td>
<td><s:property value="username"/></td>
<td><s:a value="NewsAction_deleteSingleNews?id=%{id}">删除</s:a></td>
</tr>
</s:iterator>
<s:if test="allNewList.size()==0">
<tr>
<td colspan="6">没有查找到数据</td>
</tr>
</s:if>
</table>
</div>
</body>
</html>

default.jsp:

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><%
/* 跳转到NewsAction_showAllNews.action */
response.sendRedirect("NewsAction_showAllNews.action");
%>

运行查询结果:

  浏览器显示:

  控制台输出:

运行删除结果:

  浏览器显示:

  控制台输出(删除后再查询结果):

总结:通过对本例项目搭建到功能的编写,使用注解的方式简化了ssh框架代码编写,对实例和类直接用注解注入。

SSH框架的简化(struts2、spring4、hibernate5)的更多相关文章

  1. 【SSH框架】之Struts2系列(二)

    微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联 1.Struts2常量配置 (1).Struts2默认常量配置文件路径,如下图: (2).Strut ...

  2. SSH框架的简化

    ---恢复内容开始--- 一.简易化的SSH框架,如图: SSH框架的搭建,我就不多说了. 二.简易的ssh框架的步骤: 1.重新编写applicationContext.xmlwen文件 <一 ...

  3. SSH(Struts2+Spring4+HIbernate5)的简化

    今天给大家带来的是一个简单的新闻发布系统 首先在学习过程中我是深有体会,做事情不要浮躁,不要想着一口吃下一个胖子, 最最重要的是理解,理解透了学什么东西都是随心所欲的. 开发环境:win10系统 jd ...

  4. SSH框架之Spring+Struts2+Hibernate整合篇

    回顾 -Hibernate框架 ORM: 对象关系映射.把数据库表和JavaBean通过映射的配置文件映射起来, 操作JavaBean对象,通过映射的配置文件生成SQL语句,自动执行.操作数据库. 1 ...

  5. 【SSH框架】之Struts2系列(一)

    微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系 1.Struts2框架概述 (1).什么是Struts2 Struts2是一种基于MVC模式的轻量 ...

  6. JavaEE SSH框架整合(三) struts2 异常、http错误状态码处理

    struts2的action可能出现訪问不到,或action报异常等情况,所以须要作一些处理,给用户一个友好的印象. 1. 异常处理  result声明在action中 <action name ...

  7. ssh框架的搭建

    SSH 为 struts+spring+hibernate的一个集成框架,是目前较流行的一种Web应用程序开源框架. 集成SSH框架的系统从职责上分为四层:表示层.业务逻辑层.数据持久层和域模块层,以 ...

  8. 【转载】SSH框架总结(将网上朋友写的给整合了下)

    一.Struts 在没有学习SSH框架前,我们一般采用Jsp+javabean+servlet开发,这里就是MVC架构.而Struts其实就是替代了Servlet,我们知道Servlet在一般的开发中 ...

  9. 选择J2EE的SSH框架的理由

    选择J2EE的SSH框架的理由 Struts2框架: Struts2框架的基本思想是采用MVC设计模式,即将应用设计成模型(Model).视图(View)和控制器(Control)三个部分:控制部分由 ...

随机推荐

  1. NorFlash、NandFlash、eMMC比较区别

    快闪存储器(英语:Flash Memory),是一种电子式可清除程序化只读存储器的形式,允许在操作中被多次擦或写的存储器.这种科技主要用于一般性数据存储,以及在电脑与其他数字产品间交换传输数据,如储存 ...

  2. js 以函数名作为参数动态执行 函数

    function myFunc() { console.log(11111); } test("myFunc"); function test(funcName) { if(typ ...

  3. Extjs 5 可选择日期+时间的组件DateTimeField

    我们都知道ExtJs有日期组件DateField,但直到ExtJs 5.0版本该日期组件也只能选择日期,不能选择时间(具体到时.分.秒),而实际工作中又常常会有需要日期和时间同时选择的需求,我们只能自 ...

  4. http协议知识整理

    HTTP 协议 作为web开发人员,了解一些http协议的知识很有必要.本文简单介绍了HTTP协议的知识,若有错误的地方,望大家指正. 1.HTTP协议是什么? http协议是一个应用层的协议.规定了 ...

  5. 程序设计入门-C语言基础知识-翁恺-第二周:简单的计算程序-详细笔记(二)

    目录 第二周:判断 2.1 比较 2.2 判断 2.3 课后习题 第二周:判断 2.1 比较 简单的判断语句: if(条件成立){ //执行代码 } 条件 计算两个值之间的关系,所以叫做关系运算 关系 ...

  6. THREE.OrbitControls初始化设置位移/旋转/滚轮

    let oldController;//已知的一个controller //初始化旋转(鼠标左键的操作) let position=oldController.object.position; cam ...

  7. Servlet传统配置方式和Servlet3.0使用注解的方式

    一.Servlet的传统配置方式 在JavaWeb开发中, 每次编写一个Servlet都需要在web.xml文件中进行配置,如下所示: <servlet> <servlet-name ...

  8. WebLogic配置JNDI数据源

    一.什么是jndi数据源 JNDI是Java命名与目录接口(Java Naming and Directory Interface),在J2EE规范中是重要的规范之一. 我们平时开发web程序的时候, ...

  9. Working out

    Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the ...

  10. LeetCode 424. Longest Repeating Character Replacement

    原题链接在这里:https://leetcode.com/problems/longest-repeating-character-replacement/description/ 题目: Given ...