一.导入ssh所需要的jar包
二.整合struts2
1.创建web.xml
<?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>spring_ssh</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-h1.xml</param-value>
</context-param>
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 注意filteropenSessionInView 必须在 struts2页面之前 否则先关闭session延迟加载,
在进行页面加载就报错-->
<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>
</web-app>
jsp文件:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>添加用户</h1>
<s:form action="userAction" method="post" namespace="/">
<p>用户名:<s:textfield name="user.username"></s:textfield></p>
<p>密码:<s:textfield name="user.password"></s:textfield></p>
<s:submit type="submit" value="提交"></s:submit>
</s:form>
</body>
</html>
index2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index2.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP index2. <br>
</body>
</html>
3.创建实体类,数据层,业务层,表现层
实体类:
public class User {
private String username;
private String password;
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
数据层
//hibernat事务必须映射实体类
public class UserDao extends HibernateDaoSupport{
public void save(User user) {
System.out.println("userDao save....");
this.getHibernateTemplate().save(user);
}
public void delete(Integer id) {
System.out.println("userDao delete....");
this.getHibernateTemplate().delete(id);
}
public void update(User user) {
System.out.println("userDao update....");
this.getHibernateTemplate().update(user);
}
public User getUserById(Integer id) {
System.out.println("userDao findid....");
return this.getHibernateTemplate().get(User.class, id);
}
public List<User> getAll() {
String sql = "from User u";
return this.getHibernateTemplate().find(sql);
}
//count
//这里有个大坑,必须这样写 select COUNT(*) from User u
//from后面的是实体类不是表名,否则报错 test1 is not mapped [select COUNT(*) from test1];
/**
*
* 查询数据有多少条数
* 方法名:getCount
* 创建人:蒋川阳
* 时间:2018年7月15日-下午1:34:51
* 手机:13199657597
* @return Integer
* @exception
* @since 1.0.0
*/
public Integer getCount() {
String sql = "select COUNT(*) from User u";
List<Long> count = this.getHibernateTemplate().find(sql);
return count.get(0).intValue();
}
//分页
public List<User> getUserByPage(int pageNum,int pageCount) {
DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
return this.getHibernateTemplate().findByCriteria(criteria, (pageNum-1)*pageCount, pageCount);
}
}
业务层
@Transactional
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void save(User user) {
System.out.println("userService save..."+user);
userDao.save(user);
}
}
表现层
public class UserAction extends ActionSupport{
public User user = new User();
private UserService userService;
public void setUser(User user) {
this.user = user;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String execute() throws Exception {
System.out.println("user Action running..."+user.getUsername()+"--"+user.getPassword());
//1.直接使用applicationContext对象完成对bean的获取
/**
* 优点:掌握简单
* 缺点:每次使用bean都要加载配置文件,io读取配置速度地下
* 解决方案:减少spring配置文件的加载次数,每次使用加载的配置信息都是相同的,可以只加载一次,服务器启动时加载
* 制作一个监听器,服务器启动时加载,对象放在公共的共享区域servletContext
*/
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext-h1.xml");
UserService userService = (UserService) act.getBean("userService");
//System.out.println(userService.getUserByPage());
//System.out.println(userService.getCount());
System.out.println(userService.getAll());
//2.服务器启动时将applicationContext加载到ServletContext范围内
/**
* 优点:applicationContext使用只加载一次,提高了速度
* 缺点:加载方式过于繁琐
*/
/*ServletContext scContext =ServletActionContext.getServletContext();
WebApplicationContext act =WebApplicationContextUtils.getWebApplicationContext(scContext);
UserService userService = (UserService) act.getBean("userService");
userService.save(user);*/
//3.private UserService userService直接注入servie
/*
*使用struts2.spring.plugin.jar提供的 struts获取spring对象的自动按名称装配模式
*优点:格式简洁
*缺点:当前模式struts的对象是由struts自己控制产生的
*解决方法:将struts创建对象的功能交给spring管理
*
userService.save(user);*/
//4.spring管理创建对象
/**
* 优点:所有对象交由spring进行管理
* 缺点:无
*/
//userService.save(user);
return "array";
}
}
三.Spring文件配置+hibernate整合
hibernate引入式整合
1.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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="userAction" class="com.array.ssh.action.UserAction" scope="prototype">
<property name="userService" ref="userService"/>
</bean>
<bean id="userService" class="com.array.ssh.service.UserService" >
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="com.array.ssh.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 独立整合 -->
<!-- sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 数据库连接的配置 -->
<property name="dataSource" ref="dataSource"/>
<!-- 可选配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
<!-- 资源注册 方式一 ,这种方式比较麻烦注册一个要写一个-->
<!-- <property name="mappingResources">
<list>
<value>com/array/ssh/bean/User.hbm.xml</value>
</list>
</property> -->
<!-- 资源注册 方式-->
<!-- <property name="mappingDirectoryLocations">
<value>classpath:com/array/ssh/bean</value>
</property> -->
<!-- 资源注册 方式3 方便-->
<property name="mappingLocations">
<value>classpath:com/array/ssh/bean/*.hbm.xml</value>
</property>
<!--二级缓存 搬家到hbm.xml中 -->
</bean>
<!-- dataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="username" value="array"></property>
<property name="password" value="array"></property>
</bean>
</beans>
User.hbm.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="true">
<class name="com.array.ssh.bean.User" table="test1" >
<id name="id">
<generator class="native"/>
</id>
<property name="username"/>
<property name="password"/>
</class>
</hibernate-mapping>