SSH框架的简化(struts2、spring4、hibernate5)

时间:2023-03-09 00:27:19
SSH框架的简化(struts2、spring4、hibernate5)

目的

  通过对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文件。

SSH框架的简化(struts2、spring4、hibernate5)

SSH框架的简化(struts2、spring4、hibernate5)

SSH框架的简化(struts2、spring4、hibernate5)

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

SSH框架的简化(struts2、spring4、hibernate5)

SSH框架的简化(struts2、spring4、hibernate5)

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

SSH框架的简化(struts2、spring4、hibernate5)

 <?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)进行分层。

SSH框架的简化(struts2、spring4、hibernate5)

第五步:

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

SSH框架的简化(struts2、spring4、hibernate5)

 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(实现类)。

SSH框架的简化(struts2、spring4、hibernate5)

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(实现类)。

SSH框架的简化(struts2、spring4、hibernate5)

 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类)。

SSH框架的简化(struts2、spring4、hibernate5)

 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里。

SSH框架的简化(struts2、spring4、hibernate5)

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跳转。

SSH框架的简化(struts2、spring4、hibernate5)

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框架的简化(struts2、spring4、hibernate5)

  控制台输出:

SSH框架的简化(struts2、spring4、hibernate5)

运行删除结果:

  浏览器显示:

SSH框架的简化(struts2、spring4、hibernate5)

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

SSH框架的简化(struts2、spring4、hibernate5)

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