javaee編程開發教程之SSH項目解析

javaee編程開發教程之SSH項目解析。通過學習SSH的框架,便做瞭一個小項目,是一個簡單的CRM項目,包括的功能主要有用戶的crud和部門的crud在部門中又有對用戶的多對一的關聯關系,還包括瞭一個系統日志的功能,即為當哪個用戶做瞭什麼功能都能夠在系統日志中顯示出來。

這次的項目也還是分為3層架構去實現,DAO層、SERVICE層、ACTION層
大致的分包情況:

首先是SSH的配置文件:
Struts.xml:



	

	
    
    
    
	
	
		
		
			login
			
			
				
				
			
		
	
		
		
	
	
		
		
			/WEB-INF/views/main.jsp
			/WEB-INF/views/{1}.jsp
			/WEB-INF/login.jsp
		
	
		
		
			/WEB-INF/views/user/list.jsp
			/WEB-INF/views/user/input.jsp
			user_pageList
		
		
		
		
			/WEB-INF/views/dept/list.jsp
			/WEB-INF/views/dept/input.jsp
			dept_pageList
		
		
		
		
			/WEB-INF/views/sys/list.jsp
		
		
	

hibernate.cfg.xml:

	


	<!-- hibernate對數據庫的連接參數,註冊的驅動,url,用戶名和密碼 
		
		
		com.mysql.jdbc.Driver
		
		
		jdbc:mysql://localhost:3306/shopsys
		
		root
		123
		
		hibernate對不同的數據庫用不同的數據庫的方言,hibernate能夠為各個數據庫進行一個orm映射
		主要是因為擁有瞭不同的數據庫方言支持
	-->
	
		org.hibernate.dialect.MySQL5InnoDBDialect
	


	
	true
	true
	update




	
	
	
	
	







applicationContext.xml:



        
        
        
        
	
	
		
		
		
		
		
		
	
	
	
	
		
		
	


	
	
		
	
	
	
	
		
	
	
	
	
		
			
			
			
			
			
			
			
		
	
	
	
	
	
		
		
	
	
	
	
	
	
	
	
	
		
	
	
	
		aspect ref="systemlog">
			
			
		
	

然後就是實體類(USER、ADMINS、DEPT、SYSTEMLOG):
use.hbm.xml:



    
    
    	
    		
    			
    		
    		
    		
    		
    		
    		
    		
    		
    		
    	

dept.hbm.xml:



    
    
    	
    		
    			
    		
    		
    		
    		
    		
    		
    		
    		
    		
    	

dao層,dao層采用瞭一個父類來統一規范,讓所有的dao都來繼承父類即可,BASEDAO:
baseDao:

	package gz.itcast.crm.dao.base;


import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;


public abstract class BaseDaoImpl implements IBaseDao {


	private HibernateTemplate ht;
	public void setHt(HibernateTemplate ht) {
		this.ht = ht;
	}


	Class targerClass;
	public BaseDaoImpl(){
		Class clazz = this.getClass();
		Type type = clazz.getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType)type;
		targerClass = (Class) pt.getActualTypeArguments()[0];
	}
	
	
	
	public List queryAll() {
		return ht.loadAll(targerClass);
	}


	public void save(T t) {
		ht.saveOrUpdate(t);
	}


	public List queryByHQL(String hql, Object... values) {
		return (List) ht.find(hql, values);
	}


	public T get(int id) {
		return (T) ht.get(targerClass, id);
	}


	public void delete(int id) {
		T t  = get(id);
		ht.delete(t);
	}


	public List queryByPage(final String condition,final  int curPage,final int pageSize,
			final Object... values) {
		return ht.execute(new HibernateCallback<list>() {


			public List doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery("from "
						+ targerClass.getSimpleName() + " o where 1=1 "
						+ condition);
				if(values !=null){
					for(int i=0;i() {


			public Long doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery("select count(o) from "+
							targerClass.getSimpleName() + " o where 1=1 " + condition
						);
				// 賦值
				if (values != null) {
					for (int i = 0; i < values.length; i++) {
						query.setParameter(i, values[i]);
					}
				}
				return (Long) query.uniqueResult();
			}
		
		}).intValue();
	}


}


</list

采用瞭父類的好處就是全部dao層的方法,大多數都能夠交給baseDao來完成,而相對的dao層可以簡潔

service層:
UserService:

package gz.itcast.crm.service.impl;


import gz.itcast.crm.dao.IUserDao;
import gz.itcast.crm.entity.PageBean;
import gz.itcast.crm.entity.User;
import gz.itcast.crm.service.IUserService;
import gz.itcast.crm.web.query.UserQuery;


import java.util.ArrayList;
import java.util.List;


import org.springframework.util.StringUtils;


public class UserServiceImpl implements IUserService{
	//註入UserDao
	private IUserDao userDao;
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}


	public PageBean queryByPage(UserQuery userquery) {


		PageBean pb = new PageBean();
		
		//1.設置當前頁碼
		pb.setCurPage(userquery.getCurPage());
		
		//添加查詢條件
		String condition = "";
		List param = new ArrayList();
		if(userquery!=null){
			//StringUtils: 既能判斷null,也能判斷空字符串
			//關鍵詞
			if(!StringUtils.isEmpty(userquery.getKeyword())){
				condition+=" and o.name like ? or o.realName like ? or o.phone like ? or o.email like ? ";
				param.add("%"+userquery.getKeyword()+"%");
				param.add("%"+userquery.getKeyword()+"%");
				param.add("%"+userquery.getKeyword()+"%");
				param.add("%"+userquery.getKeyword()+"%");
			}
			//錄入時間
			if(!StringUtils.isEmpty(userquery.getBeginTime())){
				condition+=" and o.inputTime>=?";
				param.add(userquery.getBeginTime());
			}
			if(!StringUtils.isEmpty(userquery.getEndTime())){
				condition+=" and o.inputTime<=?";
				param.add(userquery.getEndTime());
			}
		}
		
		
		//2.設置當前頁數
		pb.setData(userDao.queryByPage( condition , pb.getCurPage(), pb.getPageSize(), param.toArray() ) );
		//3.設置總記錄數
		pb.setTotalCount(userDao.queryByCount(condition,param.toArray()));
		return pb;
	}




	public boolean checkName(String name,int id) {
		//如果是添加,則全部數據進行檢查;如果是修改,則排除當前修改的用戶
		List param = new ArrayList();
		String hql = "from User where name=?";
		param.add(name);
		//修改操作
		if(id!=0){
			hql += " and id<>?";
			param.add(id);
		}
		List list = userDao.queryByHQL(hql, param.toArray());
		return list!=null&&list.size()>0; 
	}
	
	
	public void save(User user) {
		userDao.save(user);
	}


	public void delete(int id) {
		if(id != 0){
			userDao.delete(id);
		}
	}


	public User get(int id) {
		if(id !=0){
			return userDao.get(id);
		}
		return null;
	}


	public List findAll() {
		// TODO Auto-generated method stub
		return userDao.queryAll();
	}




}



DeptService:

package gz.itcast.crm.service.impl;


import gz.itcast.crm.dao.IDeptDao;
import gz.itcast.crm.entity.Dept;
import gz.itcast.crm.entity.PageBean;
import gz.itcast.crm.entity.User;
import gz.itcast.crm.service.IDeptService;
import gz.itcast.crm.web.query.DeptQuery;


import java.util.ArrayList;
import java.util.List;


import org.springframework.util.StringUtils;


public class DeptServiceImpl implements IDeptService {


	private IDeptDao deptDao;
	public void setDeptDao(IDeptDao deptDao) {
		this.deptDao = deptDao;
	}


	public List queryAll() {
		return deptDao.queryAll();
	}


	public void save(Dept dept) {
		deptDao.save(dept);
		
	}


	public Dept get(int id) {
		return deptDao.get(id);
	}


	public void delete(int id) {
		deptDao.delete(id);
	}


	public PageBean queryByPage(DeptQuery query) {
		//封裝PageBean
		PageBean pb = new PageBean();
		
		//1.設置當前頁碼
		pb.setCurPage(query.getCurPage());
		
		String condition = "";
		List param = new ArrayList();
		if(query!=null){
			if(!StringUtils.isEmpty(query.getKeyword())){
				condition +=" and  o.deptName like ? or o.descr like ? or o.leader.realName like ?";
				param.add("%"+query.getKeyword()+"%");
				param.add("%"+query.getKeyword()+"%");
				param.add("%"+query.getKeyword()+"%");
			}
			//錄入時間
			if(!StringUtils.isEmpty(query.getBeginTime())){
				condition+=" and o.inputTime>=?";
				param.add(query.getBeginTime());
			}
			if(!StringUtils.isEmpty(query.getEndTime())){
				condition+=" and o.inputTime<=?";
				param.add(query.getEndTime());
			}
			if(query.getLeader()!=0){
				condition +=" and  o.leader.id=?";
				param.add(query.getLeader());
			}
		}
		
		//2.設置當前頁數
		pb.setData(deptDao.queryByPage( condition , pb.getCurPage(), pb.getPageSize(), param.toArray() ) );
		//3.設置總記錄數
		pb.setTotalCount(deptDao.queryByCount(condition,param.toArray()));
		
		
		return pb;
	}


	public boolean checkName(String deptName, int id) {
			//如果是添加,則全部數據進行檢查;如果是修改,則排除當前修改的用戶
				List param = new ArrayList();
				String hql = "from Dept where deptName=?";
				param.add(deptName);
				//修改操作
				if(id!=0){
					hql += " and id<>?";
					param.add(id);
				}
				List list = deptDao.queryByHQL(hql, param.toArray());
				return list!=null&&list.size()>0; 
	}


}

SystemLogService:

package gz.itcast.crm.service.impl;


import gz.itcast.crm.dao.ISystemLogDao;


import gz.itcast.crm.entity.PageBean;
import gz.itcast.crm.entity.SystemLog;
import gz.itcast.crm.service.ISystemLogService;
import gz.itcast.crm.web.query.SystemLogQuery;


import java.util.ArrayList;
import java.util.List;


import org.springframework.util.StringUtils;




public class SystemLogServiceImpl implements ISystemLogService {
	
	private ISystemLogDao systemLogDao;
	public void setSystemLogDao(ISystemLogDao systemLogDao) {
		this.systemLogDao = systemLogDao;
	}


	public List queryAll() {
		return systemLogDao.queryAll();
	}


	public void save(SystemLog SystemLog) {
		systemLogDao.save(SystemLog);
	}


	public SystemLog get(int id) {
		return systemLogDao.get(id);
	}


	public void delete(int id) {
		systemLogDao.delete(id);
	}


	public PageBean queryByPage(SystemLogQuery query) {
		//封裝PageBean
		PageBean pb = new PageBean();
		
		//1.設置當前頁碼
		pb.setCurPage(query.getCurPage());
		
		//添加查詢條件
		String condition = "";
		List param = new ArrayList();
		if(query!=null){
			if(!StringUtils.isEmpty(query.getKeyword())){
				condition +=" and  o.operator.realName like ? or o.func like ? or o.ip like ?";
				param.add("%"+query.getKeyword()+"%");
				param.add("%"+query.getKeyword()+"%");
				param.add("%"+query.getKeyword()+"%");
			}
			//錄入時間
			if(!StringUtils.isEmpty(query.getBeginTime())){
				condition+=" and o.inputTime>=?";
				param.add(query.getBeginTime());
			}
			if(!StringUtils.isEmpty(query.getEndTime())){
				condition+=" and o.inputTime<=?";
				param.add(query.getEndTime());
			}
			if(query.getLeader()!=0){
				condition +=" and  o.operator.id=?";
				param.add(query.getLeader());
			}
		}
		
		//2.設置當前頁數
		pb.setData(systemLogDao.queryByPage( condition , pb.getCurPage(), pb.getPageSize(), param.toArray() ) );
		//3.設置總記錄數
		pb.setTotalCount(systemLogDao.queryByCount(condition,param.toArray()));
		return pb;
	}
}

action層:
UserAction:

package gz.itcast.crm.web;


import gz.itcast.crm.entity.PageBean;
import gz.itcast.crm.entity.User;
import gz.itcast.crm.service.IUserService;
import gz.itcast.crm.web.query.UserQuery;


import java.util.Date;
import java.util.List;
import java.util.Map;


import com.opensymphony.xwork2.ActionContext;


public class UserAction extends BaseAction{
	//註入userService
	private IUserService userService;
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	//接收User對象
	private User user;
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	//接收UserQuery對象
	 UserQuery uquery = new UserQuery();
	public UserQuery getUquery() {
		return uquery;
	}
	public void setUquery(UserQuery uquery) {
		this.uquery = uquery;
	}
	//跳轉頁面
	public String input(){
		if(user != null &&user.getId() !=0){
			//修改操作
			user = userService.get(user.getId());
		}
		
		return "input";
	}
	
	//查詢所有用戶
	public String pageList(){
	if(uquery==null ||uquery.getCurPage()==null || uquery.getCurPage().equals("")){
		uquery.setCurPage(1);
		ActionContext.getContext().getSession().put("Uquery", uquery);
		}
		else{
			UserQuery uquery1 = (UserQuery) ActionContext.getContext().getSession().get("Uquery");
			uquery1.setCurPage(uquery.getCurPage());
			//System.out.println(uquery.getCurPage());
			uquery = uquery1;
		}
		PageBean pb = userService.queryByPage(uquery);
		putContext("pb", pb);
		return SUCCESS;
	}
	
	//校驗save
	public void validateSave() {
		boolean result = userService.checkName(user.getName(),user.getId());
		if(result){
			addFieldError("user.name", "用戶名已重復");
		}
	}
	
	//添加用戶
	public String save(){
		user.setInputTime(new Date());
		userService.save(user);
		return "save";
	}
	
	//刪除用戶
	public String del(){
		userService.delete(user.getId());
		return pageList();
	}
	
	
}


DeptAction:

package gz.itcast.crm.web;


import gz.itcast.crm.entity.Dept;
import gz.itcast.crm.entity.PageBean;
import gz.itcast.crm.entity.User;
import gz.itcast.crm.service.IDeptService;
import gz.itcast.crm.service.IUserService;
import gz.itcast.crm.web.query.DeptQuery;


import java.util.Date;
import java.util.List;


import com.opensymphony.xwork2.ActionContext;




public class DeptAction extends BaseAction {
	//註入deptService
	private IDeptService deptService;
	public void setDeptService(IDeptService deptService) {
		this.deptService = deptService;
	}
	private IUserService userService;
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	//設置對象
	private Dept dept = new Dept();
	private DeptQuery query = new DeptQuery();
	public Dept getDept() {
		return dept;
	}
	public void setDept(Dept dept) {
		this.dept = dept;
	}
	public DeptQuery getQuery() {
		return query;
	}
	public void setQuery(DeptQuery query) {
		this.query = query;
	}


	//跳轉輸入頁面
	public String input(){
		if(dept != null &&dept.getId() !=0){
			dept = deptService.get(dept.getId());
		}
		List list = userService.findAll();
		ActionContext.getContext().getSession().put("list", list);
		return "input";
	}


	//分頁查詢用戶
	public String pageList(){
		//默認第一頁
		if(query==null || query.getCurPage()==null || query.getCurPage().equals("")){
			query.setCurPage(1);
			ActionContext.getContext().getSession().put("dquery", query);
		}
		else{
			DeptQuery query1 = (DeptQuery) ActionContext.getContext().getSession().get("dquery");
			query1.setCurPage(query.getCurPage());
			query = query1;
		}
		//查詢數據
		PageBean pb = deptService.queryByPage(query);
		
		//查詢所有用戶
		List users = userService.findAll();
		putContext("users", users);
		
		putContext("pb", pb);
		return SUCCESS;
	}
	
	//校驗保存
	public void validateSave() {
		boolean result = deptService.checkName(dept.getDeptName(),dept.getId());
		if(result){
			addFieldError("dept.deptName", "用戶名已重復");
		}
	}
	
	//保存方法
	public String save(){
		//調用業務
		if(dept==null || dept.getId()==0){
			dept.setInputTime(new Date());
		}
		deptService.save(dept);
		//設置時間
		//回顯列表頁面
		return "save";
	}
	
	//刪除用戶
	public String delete(){
		deptService.delete(dept.getId());
		return pageList();
	}
	
	
}

SystemLogAction:

package gz.itcast.crm.web;


import gz.itcast.crm.entity.PageBean;
import gz.itcast.crm.entity.SystemLog;
import gz.itcast.crm.entity.User;
import gz.itcast.crm.service.ISystemLogService;
import gz.itcast.crm.service.IUserService;
import gz.itcast.crm.web.query.SystemLogQuery;


import java.util.List;


import com.opensymphony.xwork2.ActionContext;


public class SystemLogAction extends BaseAction {
	//註入IsystemLogService
	private ISystemLogService systemLogService;
	public void setSystemLogService(ISystemLogService systemLogService) {
		this.systemLogService = systemLogService;
	}
	//註入IUserService
	private IUserService userService;
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	//設置query屬性
	private SystemLogQuery query = new SystemLogQuery();
	public SystemLogQuery getQuery() {
		return query;
	}
	public void setQuery(SystemLogQuery query) {
		this.query = query;
	}
	//設置system屬性
	private SystemLog system = new SystemLog();
	public SystemLog getSystem() {
		return system;
	}
	public void setSystem(SystemLog system) {
		this.system = system;
	}
		
	
	
	//分頁查詢用戶
	public String pageList(){
		//默認第一頁
		if(query==null || query.getCurPage()==null || query.getCurPage().equals("")){
			query.setCurPage(1);
			ActionContext.getContext().getSession().put("squery", query);
		}
		else{
			SystemLogQuery squery = (SystemLogQuery) ActionContext.getContext().getSession().get("squery");
			squery.setCurPage(query.getCurPage());
			query = squery;
		}
		//查詢數據
		PageBean pb = systemLogService.queryByPage(query);
		List users = userService.findAll();
		putContext("users", users);
		
		putContext("pb", pb);
		return SUCCESS;
	}
		
	//刪除用戶
	public String delete(){
		systemLogService.delete(system.getId());
		return pageList();
	}
}

在util層中,定義瞭一個切面類,也就是系統日志類,在applicationContext.xml文件中,采用aop切面的方法對其進行配置
SystemLogUtil:

	package gz.itcast.crm.util;


import gz.itcast.crm.entity.SystemLog;


import gz.itcast.crm.entity.User;
import gz.itcast.crm.service.ISystemLogService;


import java.util.Date;


import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.JoinPoint;


import com.opensymphony.xwork2.ActionContext;


public class SystemLogUtil {


	private ISystemLogService systemLogService;
	public void setSystemLogService(ISystemLogService systemLogService) {
		this.systemLogService = systemLogService;
	}






	public void log(JoinPoint pt){
		
		
		Object target = pt.getTarget();
		if(target instanceof ISystemLogService){
			return;
		}
		
		String clazzname = target.getClass().getSimpleName();
		String method = pt.getSignature().getName();
		String func = clazzname +":"+ method + "()";
		
		SystemLog sl = new SystemLog();
		sl.setInputTime(new Date());
		
		String ip = ServletActionContext.getRequest().getRemoteHost();
		
		sl.setIp(ip);
		//sl.setIp("11111");
		//獲取登錄用戶
		User u = new User();
		u.setId(1);
		
		sl.setOperator(u);
		sl.setFunc(func);
		
		//保存日志
		systemLogService.save(sl);
		
	}
}

還有一件很重要的事,便是使用SSH的時候需要在web.xml中進行配置,除瞭配置核心配置的過濾器和攔截器外,需要解決的懶加載問題,也可以在web.xml中進行配置

web.xml:



  	
  
    /WEB-INF/login.jsp
  
  
  
  
    osiv
    org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
  	
  		sessionFactory
  		sessionFactory
  	
  
  
    osiv
    /*
  
 
 
  
  
    struts2
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  
  
    struts2
    /*
  
  
  
  
  	org.springframework.web.context.ContextLoaderListener
  
   
  	contextConfigLocation
  	classpath:applicationContext.xml
  
  
  
    ImgServlet
    gz.itcast.crm.util.ImgServlet
  


  
    ImgServlet
    /ImgServlet.img
  
  

當整個項目都開發好瞭以後,在服務器中進行部署,在瀏覽器中打開的效果則為:

發佈留言