Ssh框架1

SSH是 struts+spring+hibernate的一个集成框架,是目前比较流行的一种Web应用程序开源框架。区别于 Secure Shell 。
集成SSH框架的系统从职责上分为四层:表示层、业务逻辑层、数据持久层和域模块层,以帮助开发人员在短期内搭建结构清晰、可复用性好、维护方便的Web应用程序。其中使用Struts作为系统的整体基础架构,负责MVC的分离,在Struts框架的模型部分,控制业务跳转,利用Hibernate框架对持久层提供支持,Spring做管理,管理struts和hibernate

Ssh框架1_第1张图片

web+spring+struts+hibernate+杂鱼

1、导入所需要的pom依赖
2、几大框架的配置文件(web.xml/struts.xml、hibernate的配置、spring的配置)
spring与hibernate整合桥接的配置文件替换掉了hibernate.cfg.xml
spring-hibernate.xml(难点)
注册数据库连接信息文件
配置数据库连接池(新的知识点)
配置sessionfactory
配置声明式事务(aop)
配置Base模块
配置struts.xml
3、做测试

1、导入所需要的pom依赖


  4.0.0
  com.zxp
  SSHs
  war
  0.0.1-SNAPSHOT
  SSHs Maven Webapp
  http://maven.apache.org
  
		5.2.12.Final
		5.1.44
		5.0.1.RELEASE
		2.5.13
		1.7.7
		2.9.1
		3.2.0
		4.12
		4.0.0
		1.2
		1.1.2
		8.0.47
	
  
  
		
			org.hibernate
			hibernate-core
			${hibernate.version}
		
		
			org.hibernate
			hibernate-c3p0
			${hibernate.version}
		
		
			org.hibernate
			hibernate-ehcache
			${hibernate.version}
		
		
			mysql
			mysql-connector-java
			${mysql.version}
		
  
		
			org.springframework
			spring-context
			${spring.version}
		
		
			org.springframework
			spring-orm
			${spring.version}
		
		
			org.springframework
			spring-web
			${spring.version}
		
		
			org.springframework
			spring-aspects
			${spring.version}
		
  
		
			org.apache.struts
			struts2-core
			${struts2.version}
		
		
			org.apache.struts
			struts2-spring-plugin
			${struts2.version}
		
  
		
		
		
			org.slf4j
			slf4j-api
			${slf4j.version}
		
		
			org.slf4j
			jcl-over-slf4j
			${slf4j.version}
			runtime
		

		
		
			org.apache.logging.log4j
			log4j-slf4j-impl
			${log4j2.version}
		

		
		
			org.apache.logging.log4j
			log4j-api
			${log4j2.version}
		
		
			org.apache.logging.log4j
			log4j-core
			${log4j2.version}
		

		
		
			org.apache.logging.log4j
			log4j-web
			${log4j2.version}
			runtime
		
		
		
			com.lmax
			disruptor
			${disruptor.version}
		
  
		
		
			junit
			junit
			${junit.version}
			test
		

		
		
			javax.servlet
			javax.servlet-api
			${javax.servlet.version}
			provided
		

		
		
			jstl
			jstl
			${jstl.version}
		
		
			taglibs
			standard
			${standard.version}
		

		
		
			org.apache.tomcat
			tomcat-jsp-api
			${tomcat-jsp-api.version}
		
  
  
    SSHs
    
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.7.0
				
					1.8
					1.8
					UTF-8
				
			
		
  

web配置


测试
Ssh框架1_第2张图片
2、几大框架的配置文件(web.xml/struts.xml、hibernate的配置、spring的配置)



    
    
    
    


    
    
    
    
    
    
    
    
    
    
    
    


    





导log4j2.xml





	
		
		/root/workspace/lucenedemo/logs
		/root/workspace/lucenedemo/logs/error
		/root/workspace/lucenedemo/logs/warn
		%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n
	

	
		
		
			
			
			
			
			
		

		
		
		
			
		
		
		
			
			
			
			
				
				
				
				
				
				
			
		

		
			
			
			
				
				
			
			
			
		

		
			
			
			
				
				
				
			
		

	

	
	
		
		
		

		
		
		
		
		
		


		
		
			
			
			
			
		

	


集成hibernate
注入数据库配置文件
db.properties

db.username=root
db.password=123
db.driverClass=com.mysql.jdbc.Driver
db.jdbcUrl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
db.initialPoolSize=10
db.maxPoolSize=20
db.minPoolSize=5
db.maxIdleTime=60
db.acquireIncrement=5
db.maxStatements=0
db.idleConnectionTestPeriod=60
db.acquireRetryAttempts=30
db.breakAfterAcquireFailure=true
db.testConnectionOnCheckout=false

struts-base.xml




	
	
	
	
	

	
		regex:.*
	

struts-sy.xml




	
	
	/index.jsp
	
	

struts.xml




	
	
	

配置spring-context.xm
在这里插入图片描述





	
	
	
	


配置spring-hibernate.xm
注入数据库配置文件
配置c3p0连接池
注册LocalSessionFactoryBean
spring声明式事物



	
	
	
	
	

	
	
		
		
		
		

		
		
		
		
		
		
		
		

		
		

		
		

		
		

		
		

		
		

		
		
	

	
	
		
		
			
		
		
		
			
				org.hibernate.dialect.MySQLDialect
				
				true
				true
			
		
		
		
			
				com/zxp/book/entity/book.hbm.xml 
			
		
	

	
	
		
	

	
	
	

	
	

	
	
		
	

	
	
		
			
			
			

			
			

			
			

			
			
			
			

			
		
	

	
	
		
		
		
		
		
		
	
	


	
	
	
		
	
	
	

程序代码的分层(base模块)
Ssh框架1_第3张图片
工具类
BaseDao

package com.zxp.base.util;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.query.Query;


/**
 * 基于hql语句的通用查询工具类
 * 1.需要给拼接的hql语句的命名参数赋值(可以简化的)
 * 2.分页(可以简化的)
 * 
 * 基于sql的分页的查询做法
 * 1.首先要查询出符合条件的总记录数
 * 2.返回符合条件的记录
 * 
 * 参数:sql,pagebean,Class clz
 * sql = select * from t_hibernate_book where bookName like "%圣墟%"
 *1. countSql = select count(*) from (sql) t;
 *2.pageSql = sql + " limit "+start+","+rows
 *
 *基于hql的分页的查询的做法
 *hql = from Book where bookName like "%圣墟%"
 *hql = select * from Book where bookName like "%圣墟%"
 *1.countHql = select count(*) hql;
 *
 * @author 玉姬
 *
 */
public class BaseDao {
    /**
     * @param query  里面包含了带有命名参数的hql语句,需要等待赋值
     *                from Book where 1=1 and bookName like :bookName
     * @param paMap
     *                 =  request.getParameterMap();
     */
    public void setParam(Query query,Map paMap) {
    	if(paMap != null && paMap.size() > 0) {
    		Set> entrySet = paMap.entrySet();
    		for (Entry entry : entrySet) {
//    			命名参数
				String key = entry.getKey();
//				赋值
				Object value = entry.getValue();
				if(value instanceof Object[]) {
//					value可能是数组
					query.setParameterList(key, (Object [])value);
				}else if(value instanceof Collection) {
//					value可能是集合
					query.setParameterList(key, (Collection)value);
				}
				else {
					query.setParameter(key, value);
				}
			}
    	}
    }
    
    /**
     * 拼装符合条件的总记录数
     * @param hql
     * @return
     */
    public String getCountHql(String hql) {
//    	把hql全变成大写,得到fromIndex关键字下标
    	int fromIndex = hql.toUpperCase().indexOf("FROM");
		return "select count(*) "+hql.substring(fromIndex);
    }
    
    /**
     * 基于hql的通用查询方法
     * @param hql
     * @param pageBean
     * @param pMap
     * @param session
     * @return
     */
    public List executeQuery(String hql,PageBean pageBean,Map pMap,Session session) {
    	List list = null;
    	Query query = null;
    	if(pageBean != null && pageBean.isPagination()) {
//    		1.首先要查询符合条件的总记录数
    		String countHql = getCountHql(hql);
    		Query countQuery = session.createQuery(countHql);
    		this.setParam(countQuery, pMap);
    		pageBean.setTotal(countQuery.getSingleResult().toString());
    		
//    		2.返回符合条件的记录
    		query = session.createQuery(hql);
    		this.setParam(query, pMap);
    		query.setFirstResult(pageBean.getStartIndex());
    		query.setMaxResults(pageBean.getRows());
    		list = query.list();
    	}else {
    		query = session.createQuery(hql);
    		this.setParam(query, pMap);
    		list = query.list();
    	}
		return list;
    }
    
}

PageBean

package com.zxp.base.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 5;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	// 获取前台向后台提交的所有参数
	private Map parameterMap;
	// 获取上一次访问后台的url
	private String url;

	/**
	 * 初始化pagebean
	 * 
	 * @param req
	 */
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		// 只有jsp页面上填写pagination=false才是不分页
		this.setPagination(!"fasle".equals(req.getParameter("pagination")));
		this.setParameterMap(req.getParameterMap());
		this.setUrl(req.getRequestURL().toString());
	}

	public int getMaxPage() {
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}

	public int nextPage() {
		return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
	}

	public int previousPage() {
		return this.page > 1 ? this.page - 1 : 1;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setPage(String page) {
		this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setRows(String rows) {
		this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows);
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	public Map getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map parameterMap) {
		this.parameterMap = parameterMap;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", parameterMap=" + parameterMap + ", url=" + url + "]";
	}

}

StringUtils

package com.zxp.base.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

基础模块
BaseAction

package com.zxp.base.web;

import java.io.Serializable;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

public class BaseAction implements ServletRequestAware, ServletResponseAware,Serializable{
	
	private static final long serialVersionUID = 7126941004978724537L;
	/**
	 * 为了传值使用
	 */
	protected HttpServletResponse response;
	protected HttpServletRequest request;
	protected HttpSession session;
	protected ServletContext application;
	
	/**
	 * 为了配置跳转页面所用
	 */
	protected final static String SUCCESS = "success";
	protected final static String FAIL = "fail";
	protected final static String LIST = "list";
	protected final static String ADD = "add";
	protected final static String EDIT = "edit";
	protected final static String DETAIL = "detail";
	
	/**
	 * 具体传值字段	后端向jsp页面传值所用字段
	 */
	protected Object result;
	protected Object msg;
	protected int code;

	public Object getResult() {
		return result;
	}

	public Object getMsg() {
		return msg;
	}

	public int getCode() {
		return code;
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;
		
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		this.request = arg0;
		this.session = arg0.getSession();
		this.application = arg0.getServletContext();
	}

}

配置base模块

	

	
		
	
	
	

配置web.xm


  Archetype Created Web Application
  
	
		contextConfigLocation
		classpath:spring-context.xml
	
	
		
			org.springframework.web.context.ContextLoaderListener
		
	
	
	
		struts2
		
			org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
		
	
	
		struts2
		*.action
	

	
	
		encodingFilter
		
			org.springframework.web.filter.CharacterEncodingFilter
		
		true
		
			encoding
			UTF-8
		
	
	
		encodingFilter
		/*
	

Ssh框架1_第4张图片
BookBiz

package com.zxp.book.biz;

import java.util.List;

import com.zxp.base.util.PageBean;
import com.zxp.book.entity.Book;

public interface BookBiz {

	public void add(Book book);

	public void del(Book book);

	public void edit(Book book);

	public List list(Book book, PageBean pageBean) throws InstantiationException, IllegalAccessException;
}

BookBizImpl

package com.zxp.book.biz.impl;

import java.util.List;

import com.zxp.base.util.PageBean;
import com.zxp.book.biz.BookBiz;
import com.zxp.book.dao.BookDao;
import com.zxp.book.entity.Book;

public class BookBizImpl implements BookBiz {
	 private BookDao bookDao;
	    
		public BookDao getBookDao() {
			return bookDao;
		}

		public void setBookDao(BookDao bookDao) {
			this.bookDao = bookDao;
		}

		@Override
		public void add(Book book) {
			this.bookDao.add(book);
		}

		@Override
		public void del(Book book) {
			this.bookDao.del(book);
		}

		@Override
		public void edit(Book book) {
			this.bookDao.edit(book);
		}

		@Override
		public List list(Book book, PageBean pageBean) throws InstantiationException, IllegalAccessException {
			return this.bookDao.list(book,pageBean);
		}

}

BookDao

package com.zxp.book.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import com.zxp.base.dao.BaseDao;
import com.zxp.base.util.PageBean;
import com.zxp.book.entity.Book;

public class BookDao extends BaseDao{
	  public void add(Book book) {
		  this.getHibernateTemplate().save(book);
	  }
	  
	  public void del(Book book) {
		  this.getHibernateTemplate().delete(book);
	  }
	  
	  public void edit(Book book) {
		  this.getHibernateTemplate().update(book);
	  }
	  
	  public List list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException{
		  BaseDao obj = super.getClass().newInstance();
		  return (List) this.getHibernateTemplate().execute(new HibernateCallback>() {

			@Override
			public List doInHibernate(Session session) throws HibernateException {
				String hql = "from Book";
				return obj.executeQuery(session, hql, null, pageBean);
			}
			  
		});
	  }
	


}

Book

package com.zxp.book.entity;

import com.zxp.base.entity.BaseEntity;

public class Book extends BaseEntity {

	private static final long serialVersionUID = 4308893039068349840L;
	private Integer bid;
	private String bname;
	private Float price;

	public Integer getBid() {
		return bid;
	}

	public void setBid(Integer bid) {
		this.bid = bid;
	}

	public String getBname() {
		return bname;
	}

	public void setBname(String bname) {
		this.bname = bname;
	}

	public Float getPrice() {
		return price;
	}

	public void setPrice(Float price) {
		this.price = price;
	}

	public Book(Integer bid, String bname, Float price) {
		super();
		this.bid = bid;
		this.bname = bname;
		this.price = price;
	}

	public Book() {
		super();
	}

	@Override
	public String toString() {
		return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
	}

}

book.hbm.xml




	
		
			
		
		
		
		
	

BookAction

package com.zxp.book.web;
import java.util.List;

import com.opensymphony.xwork2.ModelDriven;
import com.zxp.base.web.BaseAction;
import com.zxp.book.biz.BookBiz;
import com.zxp.book.entity.Book;

public class BookAction extends BaseAction implements ModelDriven{

	private static final long serialVersionUID = 1703301949600905805L;
	private BookBiz bookBiz;
	private Book book = new Book();
	
	public BookBiz getBookBiz() {
		return bookBiz;
	}

	public void setBookBiz(BookBiz bookBiz) {
		this.bookBiz = bookBiz;
	}

	public String list() {
		try {
			List res = this.bookBiz.list(book, null);
			for (Book b : res) {
				System.out.println(b);
			}
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	 public String add() {
		 this.bookBiz.add(book);
		 return SUCCESS;
	 }
	 
	 public String del() {
		 this.bookBiz.del(book);
		 return SUCCESS;
	 }
	 
	 public String edit() {
		 this.bookBiz.edit(book);
		 return SUCCESS;
	 }
	@Override
	public Book getModel() {
		return book;
	}
}

配置spring-book.xml



		

  
  
  
     
  
  
  
  
		

3测试

Ssh框架1_第5张图片

Ssh框架1_第6张图片

Ssh框架1_第7张图片

Ssh框架1_第8张图片
切面切在biz与切在Dao的区别

/**
 * 为什么切面要切到Biz接口上?不能切到Dao层上面呢?
 *   以银行转账为例,假如说张三李四账户各有1000,张三给李四转账300,正常的结果是张三:700 李四:1300
 *   web层处理转账的请求:
 *    transfer(){
 *      biz.transfer(from,to.money)
 *    }
 *    
 *    biz层
 *      transfer(from,to.money){
 *      1.获取from账号的现在账户信息(现在有多少钱)
 *      2.获取to账号的现在账户信息(现在有多少钱)
 *      3.第一步获取的金额-money
 *      4.第二步获取的金额+money
 *      5.dao.edit(from)
 *      6.dao.edit(to)
 *    }
 *    
 *    dao层:
 *     get(user){
 *     ...
 *     }
 *     
 *     edit(user){
 *     ...
 *     }
 *     
 *  如果切面切在Dao层上:
 *   transfer(from,to.money){
 *      1.获取from账号的现在账户信息(现在有多少钱)
 *      2.获取to账号的现在账户信息(现在有多少钱)
 *      3.第一步获取的金额-money
 *      4.第二步获取的金额+money
 *      
 *      Transation transation1 = session.beginTransation();
 *      5.dao.edit(from)
 *      transation1.commit();
 *      
 *      system.out.print(1/0);
 *      
 *      Transation transation2 = session.beginTransation();
 *      6.dao.edit(to)
 *       transation2.commit();
 *    }
 *  
 *  如果切面切在Biz层上:
 *  
 *   transfer(from,to.money){
 *      1.获取from账号的现在账户信息(现在有多少钱)
 *      2.获取to账号的现在账户信息(现在有多少钱)
 *      3.第一步获取的金额-money
 *      4.第二步获取的金额+money
 *      5.dao.edit(from)
 *      6.dao.edit(to)
 *    }
 *    
 * web层处理转账的请求:
 *    tranfer(){
 *      Transation transation1 = session.beginTransation();
 *      biz.transfer(from,to,money)
 *      transation1.commit();
 *    }
 * execution(* *..*Biz.*(..))
 * @author 玉姬
 *
 */

你可能感兴趣的:(Ssh框架1)