SSH顾名思义指的就是struts2,spring,Hibernate,三个框架。
我们先看Hibernate这个框架需要做什么
1.导包
2.配置hibernate.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ssh</property>
<property name="connection.username">root</property>
<property name="connection.password">570044</property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property> -->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">create</property> -->
<mapping resource="com/bdqn/web/po/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3.编写SessionFactory工具类
package com.bdqn.web.config;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static SessionFactory sf;
static{
sf = new Configuration().configure().buildSessionFactory();
}
public static final ThreadLocal<Session> localThread = new ThreadLocal<Session>();
/**
* @description:获取当前session
**/
public static Session currentSession() {
Session s = (Session) localThread.get();
if (s == null) {
s = sf.getCurrentSession();
localThread.set(s);
}
return s;
}
/**
* @description:关闭当前session
**/
public static void closeSession() {
Session s = localThread.get();
localThread.set(null);
if (s != null && s.isOpen()) {
s.close();
}
}
}
4.创建数据库对应的实体类bean
package com.bdqn.web.po;
public class User {
private int id;//编号
private String username;//用户名
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;
}
}
5.实体映射关系配置文件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 >
<class table="yx" name="com.bdqn.web.po.User">
<id name="id" type="int" column="id">
<generator class="native"></generator>
</id>
<property name="username" type="string" column="name"></property>
</class>
</hibernate-mapping>
6.测试
public class Test {
public static void main(String[] args) {
Session session = HibernateSessionFactory.currentSession();
Transaction tx = session.beginTransaction();
tx.begin();
User user = new User();
user.setId(1);
user.setUsername("张三");
session.save(user);
tx.commit();
HibernateSessionFactory.closeSession();
再看下spring应该怎么办
1.导入jar包
2.编写jdbc.properties配置文件
jdbcUrl = jdbc:mysql://localhost:3306/ssh
driverClass = com.mysql.jdbc.Driver
user = root
password =570044
3.编写hibernate.hbm.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 1,数据库连接信息 -->
<property name="dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</property>
<!-- 2,其他配置 -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 3,导入映射文件 -->
<mapping resource="com/bdqn/web/po/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
4.编写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: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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 导入外部的properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- session factory -->
<bean id="sessionfactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 指定hibernate的配置文件位置 -->
<property name="configLocation" value="classpath:hibernate.cfg1.xml"></property>
<!-- 配置c3p0数据库连接池 -->
<property name="dataSource">
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据连接信息 -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<!-- 初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!-- 连接池中保留的最小连接数。Default: 3 -->
<property name="minPoolSize" value="3"></property>
<!-- 连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="5"></property>
<!-- 连接的最大空闲时间,超时的连接将被丢弃;单位(秒) -->
<property name="maxIdleTime" value="60"></property>
<!-- 没有连接可用时,等待连接的时间;单位(毫秒) -->
<property name="checkoutTimeout" value="2000"></property>
</bean>
</property>
</bean>
<!-- 事务 start 配置声明式事务管理(采用注解的方式) -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionfactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceMethod" expression="execution(public void addUser(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
</aop:config>
<!-- 事务 end -->
<!-- 拆分 -->
<import resource="spring-dao.xml" />
<import resource="spring-service.xml" />
<!-- spring-dao.xm -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="userDaoImpl" class="com.bdqn.web.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionfactory"></property>
</bean>
</beans>
<!-- spring-service.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="iServiceImpl" class="com.bdqn.web.service.impl.IServiceImpl">
<property name="userDaoImpl" ref="userDaoImpl"></property>
</bean>
</beans>
</beans>
5.编写dao层,service层
5.1编写dao层基类,daoImpl实现类
package com.bdqn.web.dao;
public interface IBaseDao<T> {
public void save(T intance);
public void delete(T intance);
public void update(T intance);
public T findById(int id);
}
package com.bdqn.web.dao.impl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.bdqn.web.dao.IBaseDao;
public class IBaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T>{
private Class<T> entityClass;
@Override
public void save(T intance) {
getHibernateTemplate().save(intance);
}
@Override
public void delete(T intance) {
// TODO Auto-generated method stub
getHibernateTemplate().delete(intance);
}
@Override
public void update(T intance) {
// TODO Auto-generated method stub
getHibernateTemplate().update(intance);
}
@Override
public T findById(int id) {
// TODO Auto-generated method stub
T t = getHibernateTemplate().get(entityClass, id);
return t;
}
public Class<T> getEntityClass() {
return entityClass;
}
public void setEntityClass(Class<T> entityClass) {
this.entityClass = entityClass;
}
}
5.2编写业务dao类
package com.bdqn.web.dao.impl;
import java.util.List;
import com.bdqn.web.po.User;
public class UserDaoImpl extends IBaseDaoImpl<User>{
public void saveUser(User user){
save(user);
}
public void delete(User user){
this.getHibernateTemplate().delete(user);
}
public void update(int id){
this.getHibernateTemplate().update(id);
}
public User findUsreById(int id){
User user = this.getHibernateTemplate().get(User.class, id);
return user;
}
public List<User> findAll(String sql){
sql = "from User";
List<User> list = this.getHibernateTemplate().find(sql);
return list;
}
}
5.3编写service业务层(接口)
package com.bdqn.web.service;
import java.util.List;
import com.bdqn.web.po.User;
public interface IService {
public void addUser(User user);
public void delete(User user);
public void update(User user);
public User findUserById(int id);
public List<User> findAll(String sql);
}
5.4编写service业务实现层
package com.bdqn.web.service.impl;
import java.util.List;
import javax.management.RuntimeErrorException;
import com.bdqn.web.dao.impl.UserDaoImpl;
import com.bdqn.web.po.User;
import com.bdqn.web.service.IService;
public class IServiceImpl implements IService{
public UserDaoImpl getUserDaoImpl() {
return userDaoImpl;
}
public void setUserDaoImpl(UserDaoImpl userDaoImpl) {
this.userDaoImpl = userDaoImpl;
}
UserDaoImpl userDaoImpl;
public void addUser(User user) {
// TODO Auto-generated method stub
userDaoImpl.saveUser(user);
//throw new RuntimeException("抛出异常");
}
@Override
public void delete(User user) {
// TODO Auto-generated method stub
userDaoImpl.delete(user);
}
@Override
public void update(User user) {
// TODO Auto-generated method stub
userDaoImpl.update(user);
}
@Override
public User findUserById(int id) {
// TODO Auto-generated method stub
User user = userDaoImpl.findUsreById(id);
return user;
}
@Override
public List<User> findAll(String sql) {
sql = "from User";
List<User> list =userDaoImpl.findAll(sql);
return list;
}
}
6.编写测试类
main方法内
User user = new User();
user.setId(2);
user.setUsername("李四");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IService iServiceImpl = (IService) context.getBean("iServiceImpl");
iServiceImpl.addUser(user);
最后是Struts2
1.导入struts包
2.编写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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>SSH_YX</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>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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>
<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>
3.新建UserAction类
package com.bdqn.web.action;
import java.util.List;
import com.bdqn.web.po.User;
import com.bdqn.web.service.IService;
import com.bdqn.web.service.impl.IServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
IService iService;
User user;
List<User> list;
public void setiService(IService iService) {
this.iService = iService;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//提交
public String editUser(){
return "success";
}
//添加用户
public String addUser(){
iService.addUser(user);
return "success";
}
//通过ID提交
public String tijiao(){
return "success";
}
//删除用户
public String deleteUser(){
iService.delete(user);
return "success";
}
//修改用户
public String updateUser(){
iService.update(user);
return "success";
}
//查询用户
public String findUserById(){
user = iService.findUserById(user.getId());
return "success";
}
//显示表全部内容
public String findAll(){
list = iService.findAll("from User");
return "success";
}
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
}
4.action 组件的注入
<!-- action注入 -->
<bean id="UserAction" class="com.bdqn.web.action.UserAction">
<property name="iService" ref="iServiceImpl"></property>
</bean>
5.编写Struts.xml注意:action的class属性值= action bean id
<?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.enable.DynamicMethodInvocation" value="false" />
<!-- 关键字action-->
<package name="user" namespace="" extends="struts-default">
<!-- 关键字添加view -->
<action name="editUser" class="UserAction" method="editUser">
<result name="success">/html/key_edit.html</result>
</action>
<!-- 关键字添加操作 -->
<action name="addUser" class="UserAction" method="addUser">
<result name="success">/html/key_list.html</result>
</action>
<!-- 删除 -->
<action name="tijiao" class="UserAction" method="tijiao">
<result name="success">/html/delete.html</result>
</action>
<action name="deleteUser" class="UserAction" method="deleteUser">
<result name="success">/html/user_delete.html</result>
</action>
<action name="updateUser" class="UserAction" method="updateUser">
<result name="success">/html/user_update.html</result>
</action>
<action name="findUserById" class="UserAction" method="findUserById">
<result name="success">\html\xiugaiyemian.jsp</result>
</action>
<action name="findAll" class="UserAction" method="findAll">
<result name="success">\html\user_find.jsp</result>
</action>
</package>
</struts>
6.新建html页面
delete
<!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>
</head>
<body>
<form action="deleteUser" method="post">
ID:<input name="user.id" />
<button type="submit" >删除</button>
</form>
<form action="findUserById" method="post">
ID:<input name="user.id" />
<button type="submit" >修改</button>
</form>
<form action="findUserById" method="post">
ID:<input name="user.id" />
<button type="submit" >修改</button>
</form>
<form action="findAll" method="post">
<input type="submit" value="显示全部内容">
</form>
</body>
</html>
key_edit.html
<!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>
</head>
<body>
<form action="addUser" method="post">
关键字<input name="user.username" />
<button type="submit" >提交</button>
</form>
</body>
</html>
key_list.html
<!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>
</head>
<body>
添加成功
</body>
</html>
user_delete.html
<!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>
</head>
<body>
<h1>删除成功</h1>
</body>
</html>
user_find.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@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>
</head>
<body>
<h1>查询成功</h1>
<s:iterator var="userList" value="list" status="status">
ID:<s:property value="#userList.id"/>
Name:<s:property value="#userList.username"/><br/>
</s:iterator>
<s:debug></s:debug>
</body>
</html>
user_update.html
<!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>
</head>
<body>
<h1>修改成功</h1>
</body>
</html>
xiugaiyemian.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@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>
</head>
<body>
<form action="updateUser" method="post">
<s:property value="user.username"/>
<input type="text" name="user.username">
<input type="submit" value="修改">
</form>
</body>
<s:debug></s:debug>
</html>