ssh(struts2.3.8+spring3.2+heibernate4.1+annotation零配置

阅读更多

公司一直不是ssh零配置的框架,每次写action都要在applicationcontext和struts里面配置,好麻烦,最近有空,写了一个ssh零配置的框架

这里写了一个小的项目,以用户权限管理为例

先做准备工作:

1.struts2去官网下载最新版struts开发包http://struts.apache.org/download.cgi#struts216

2.hibernate4去官网下载最新版hibernate4开发包http://sourceforge.net/projects/hibernate/files/hibernate4/

3.spring3去官网下载最新版spring3开发包http://www.springsource.org/download/community

一、先建立一个空的web的项目sshFrame,加载必须的包

1.添加struts2必备的包。我下载的是最近的struts2.3.8

asm-3.3.jar  --ASM字节码库 ,使用“cglib”则必要

aopalliance-1.0.jar  --这个包为AOP提供了最普通和通用的接口

commons-fileupload-1.2.2.jar   --Struts2上传下载的jar

commons-io-2.0.1.jar  --Struts2上传下载的jar

commons-logging-1.1.1.jar   --Jakarta的通用日志记录包

freemarker-2.3.19.jar

ognl-3.0.6.jar    --支持ognl表达式

struts2-core-2.3.8.jar  --struts2的核心包

struts2-spring-plugin-2.3.8.jar     --struts2与spring整合所需

struts2-convention-plugin-2.3.8.jar  --struts2零配置注释用

xwork-core-2.3.8.jar 

可以不加 struts2-config-browser-plugin-2.3.1.1.jar为struts协助开发需要的包:可以输入http://127.0.0.1:8686/config-browser/actionNames.action查看系统所有已经存在的action,配置不正确就可以在这里看出来;

 

2.添加Hibernate 所需要的包。hibernate-4.1.9.Final

把下载下来的hibernate\lib\required下的包全部拷贝进去,分别是

antlr-2.7.7.jar  --语言转换工具,hibernate用他将hql语句转换为sql语句

dom4j-1.6.1.jar  --解析xml文档的工具

hibernate-commons-annotations-4.0.1.Final.jar

hibernate-core-4.1.9.Final.jar  --核心包

hibernate-jpa-2.0-api-1.0.1.Final.jar

javassist-3.17.1-GA.jar

jboss-logging-3.1.0.GA.jar

jboss-transaction-api_1.1_spec-1.0.0.Final.jar

还有加入hibernate\lib\optional\c3p0\c3p0-0.9.1.jar

hibernate-ehcache-4.1.9.Final.jar

ehcache-core-2.4.3.jar

slf4j-api-1.6.4.jar

slf4j-log4j12-1.6.4.jar

3添加spring3 所需要的包 spring-framework-3.2.0.RELEASE

spring-aop-3.2.0.RELEASE.jar

spring-aspects-3.2.0.RELEASE.jar

spring-beans-3.2.0.RELEASE.jar

spring-context-3.2.0.RELEASE.jar

spring-core-3.2.0.RELEASE.jar

spring-expression-3.2.0.RELEASE.jar

spring-instrument-3.2.0.RELEASE.jar

spring-jdbc-3.2.0.RELEASE.jar

spring-jms-3.2.0.RELEASE.jar

spring-orm-3.2.0.RELEASE.jar

spring-oxm-3.2.0.RELEASE.jar

spring-test-3.2.0.RELEASE.jar --测试时用

spring-tx-3.2.0.RELEASE.jar  --事务处理所用

spring-web-3.2.0.RELEASE.jar

aspectjweaver-1.5.3.jar  --spring所依赖的包

 

其他

asm-commons-3.3.jar

Commons—pool.jar ,commons-dbcp.jar  ----------DBCP数据库连接池,Apache的jakarta组织开发 的,tomcat连接池也是dbcp(可选)

cglib.jar----------------------------高效的代码生成工具, Hibernate用它在运行时扩展 Java类和实现 Java 接

jta.jar  --标准的JTA API(JTA即java事物API,JTA事务比JDBC事务更强大。一个JTA事务可以有多个参与者,而一个JDBC事务则被限定在一个单一的数据库连接),我暂时还没加,先备着

mysql-connector-java-5.1.18-bin.jar

log4j-1.2.16.jar

二、添加配置文件

在struts包下struts\src\apps\blank\src\main\resources提供了空白的struts.xml文件,把它复制到项目的src下

web.xml中


  
    org.springframework.web.context.ContextLoaderListener
  
  
    Spring上下文
    contextConfigLocation
    classpath:applicationContext*.xml
  


  
    hibernate Session 过滤器
    openSessionInViewFilter
    org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
  
  
    openSessionInViewFilter
    /*
  
   
 
    struts2
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  
  
    struts2
    /*
  

 

struts.xml配置




 
 
 
 
 
  
   
   
   
   
   
   
    
    
       
     .*\\u0023.*   
    
    
   
  
  
  
  
   /index.jsp
   /error.jsp
  
 

 applicationcontext.xml配置:




	
		
		
		
		
	
	
		
		
			
				org.hibernate.dialect.MySQLDialect
				thread
				org.hibernate.cache.EhCacheRegionFactory
				true
				true
				update
			
		
		
			
				com.sshFrame.zero.pojo
				com.sshFrame.test.pojo
				
		
	
 	
	
 	
  		
 	
 	
	
	
        
            
            
            
            
            
            
            
            
            
            

            
            
            

            
            

            
        
    
    
        
        
        
    
 	
	
 	

配置都写好了,

改写基本的框架类了

Basedao

package com.sshFrame.zero.dao;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.Id;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 基于hibernate的BaseDao
 * Spring3对Hibernate4已经没有了HibernateDaoSupport和HibernateTemplate的支持,使用了原生态的API
 * @author 雪精灵
 *
 * @param 
 */
public class BaseDao {
	@Autowired
	private SessionFactory sessionFactory;
	//当前泛型类
	@SuppressWarnings("rawtypes")
	private Class entityClass;
	//当前主键名称
	private String pkname;
	private final String HQL_LIST_ALL;
	private final String HQL_COUNT_ALL;
	@SuppressWarnings("rawtypes")
	public Class getEntityClass() {
		return entityClass;
	}
	@SuppressWarnings("rawtypes")
	public void setEntityClass(Class entityClass) {
		this.entityClass = entityClass;
	}
	
	@SuppressWarnings("rawtypes")
	public BaseDao() {
		//获取当前泛型类
		Type type = this.getClass().getGenericSuperclass();
		if (type.toString().indexOf("BaseDao") != -1) {
			ParameterizedType type1 = (ParameterizedType) type;
			Type[] types = type1.getActualTypeArguments();
			setEntityClass((Class) types[0]);
		}else{
			type = ((Class)type).getGenericSuperclass();
			ParameterizedType type1 = (ParameterizedType) type;
			Type[] types = type1.getActualTypeArguments();
			setEntityClass((Class) types[0]);
		}
		getPkname();
		HQL_LIST_ALL="from "+this.entityClass.getSimpleName()+" order by "+pkname+" desc";
		HQL_COUNT_ALL="select count(*) from "+this.entityClass.getSimpleName();
	}
	/**
	 * 获取主键名称
	 * @return
	 */
	public String getPkname() {
		Field[] fields = this.entityClass.getDeclaredFields();//反射类字段
		for (Field field : fields) {
			field.isAnnotationPresent(Id.class);
			this.pkname=field.getName();
			break;
		}
		return pkname;
	}
	/**
	 * 保存实例
	 * 
	 * @param t
	 * @throws HibernateException
	 */
	public void save(T t) throws HibernateException{
		Session session=null;
		try {
			session=sessionFactory.openSession();
			session.beginTransaction();
			session.save(t);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}finally{
			session.close();
		}
	}
	/**
	 * 修改实例
	 * 
	 * @param t
	 * @throws HibernateException
	 */
	public void update(T t) throws HibernateException{
		Session session=null;
		try {
			session=sessionFactory.openSession();
			session.beginTransaction();
			session.update(t);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}finally{
			session.close();
		}
	}
	
	/**
	 * 删除实例
	 * 
	 * @param t
	 * @throws HibernateException
	 */
	public void delete(T t) throws HibernateException{
		Session session=null;
		try {
			session=sessionFactory.openSession();
			session.beginTransaction();
			session.delete(t);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}finally{
			session.close();
		}
	}
	/**
	 * 获取实例
	 * 
	 * @param id
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public T get(Serializable id) throws Exception{
		Session session=null;
		T t=null;
		try {
			session=sessionFactory.openSession();
			session.beginTransaction();
			t=(T) session.get(getEntityClass(), id);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new HibernateException(e);
		}finally{
			session.close();
		}
		return t;
	}
	/**
	 * 查询全部
	 * 
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public List findAll() throws Exception {
		List list=null;
		Session session=null;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Query query = session.createQuery(HQL_LIST_ALL);
			list = query.list();
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
	/**
	 * 查询总数
	 * 
	 * @throws HibernateException
	 */
	public Integer findAllCount() throws Exception {
		Session session=null;
		Integer count=0;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Query query = session.createQuery(HQL_COUNT_ALL);
			List list = query.list();
			session.getTransaction().commit();
			if(list!=null&&!list.isEmpty()){
				count=((Integer) list.get(0)).intValue();
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return count;
	}
	/**
	 * QBC查询
	 * 
	 * @param criteria
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public List findByCriteria(Criteria criteria) throws Exception {
		List list=null;
		Session session=null;
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Criteria criteria1 = session.createCriteria(getEntityClass());
			criteria1=criteria;
			list = criteria1.list();
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
	
	/**
	 * QBE查询
	 * 
	 * @param t
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public List findByExample(T t) throws Exception {
		List list=null;
		Session session=null;
		Example example = Example.create(t);
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			Criteria criteria = session.createCriteria(getEntityClass());
			criteria.add(example);
			list = criteria.list();
			session.getTransaction().commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
	/**
	 * HQL查询
	 * 
	 * @param hql
	 * @param objects
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public List findByHql(String hql,final Object...objects) throws Exception{
		List list=null;
		Session session=null;
		try {
			session=sessionFactory.openSession();
			session.beginTransaction();
			Query query = session.createQuery(hql);
			for (int i = 0; i < objects.length; i++) {
				query.setParameter(i, objects[i]);
			}
			list = query.list();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
	/**
	 * SQL查询
	 * 
	 * @param hql
	 * @param objects
	 * @throws HibernateException
	 */
	@SuppressWarnings("unchecked")
	public List findBySql(String sql,final Object...objects){
		List list=null;
		Session session=null;
		try {
			session=sessionFactory.openSession();
			session.beginTransaction();
			Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
			for (int i = 0; i < objects.length; i++) {
				query.setParameter(i, objects[i]);
			}
			list = query.list();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
}


BaseService

package com.sshFrame.zero.service;

import java.io.Serializable;
import java.util.List;

import com.sshFrame.zero.dao.BaseDao;
/**
 * @author 雪精灵
 *
 * @param 
 */

public class BaseService {
	
	protected BaseDao baseDao;
	
	public void save(T t) throws Exception{
		baseDao.save(t);
	}
	public void update(T t) throws Exception{
		baseDao.update(t);
	}
	public void delete(T t) throws Exception{
		baseDao.delete(t);
	}
	public T get(Serializable id) throws Exception{
		return baseDao.get(id);
	}
	public List findAll() throws Exception{
		return baseDao.findAll();
	}
	public List findByExample(T t) throws Exception{
		return baseDao.findByExample(t);
	}
	public BaseDao getBaseDao() {
		return baseDao;
	}
	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}
}

 

先上7个pojo

package com.sshFrame.zero.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="userinfo")
public class Userinfo implements Serializable{
	private static final long serialVersionUID = 1L;
	private String userid;
	private String username;
	private String password;
	private String depid;
	private String dutyid;
	private Set userroles=new HashSet();
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "userid", unique = true, nullable = false, length = 50)
	public String getUserid() {
		return userid;
	}
	public void setUserid(String userid) {
		this.userid = userid;
	}
	@Column(name = "username", nullable = false, length = 50)
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	@Column(name = "password", nullable = false, length = 50)
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Column(name = "depid", nullable = false, length = 50)
	public String getDepid() {
		return depid;
	}
	public void setDepid(String depid) {
		this.depid = depid;
	}
	@Column(name = "dutyid", nullable = false, length = 50)
	public String getDutyid() {
		return dutyid;
	}
	public void setDutyid(String dutyid) {
		this.dutyid = dutyid;
	}
	@OneToMany(cascade=CascadeType.REMOVE,mappedBy="userinfo",fetch=FetchType.LAZY)
	public Set getUserroles() {
		return userroles;
	}
	public void setUserroles(Set userroles) {
		this.userroles = userroles;
	}
}
package com.sshFrame.zero.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;


@Entity
@Table(name="role")
public class Role implements Serializable{
	private static final long serialVersionUID = 1L;
	private String id;
	private String name;
	private Set userroles=new HashSet();
	private Set rolerights=new HashSet();
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "name", nullable = false, length = 50)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="role")
	public Set getUserroles() {
		return userroles;
	}
	public void setUserroles(Set userroles) {
		this.userroles = userroles;
	}
	@OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="role")
	public Set getRolerights() {
		return rolerights;
	}
	public void setRolerights(Set rolerights) {
		this.rolerights = rolerights;
	}
}

 

package com.sshFrame.zero.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="rights")
public class Rights implements Serializable{

	private static final long serialVersionUID = 1L;
	private String id;
	private String name;
	private Set rolerights=new HashSet();
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	@Column(name = "name", nullable = false, length = 50)
	public void setName(String name) {
		this.name = name;
	}
	@OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="rights")
	public Set getRolerights() {
		return rolerights;
	}
	public void setRolerights(Set rolerights) {
		this.rolerights = rolerights;
	}
}

 

package com.sshFrame.zero.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="resources")
public class Resources implements Serializable{

	private static final long serialVersionUID = 1L;
	private String id;
	private String name;
	private String url;
	private Set rightsresourcs=new HashSet();
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "name", nullable = false, length = 50)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name = "url", nullable = false, length = 100)
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	@OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="resources")
	public Set getRightsresourcs() {
		return rightsresourcs;
	}
	public void setRightsresourcs(Set rightsresourcs) {
		this.rightsresourcs = rightsresourcs;
	}
	
}

 

package com.sshFrame.zero.pojo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="userrole")
public class Userrole implements Serializable{
	private static final long serialVersionUID = 1L;
	private String id;
	private Userinfo userinfo;
	private Role role;
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="userid")
	public Userinfo getUserinfo() {
		return userinfo;
	}
	public void setUserinfo(Userinfo userinfo) {
		this.userinfo = userinfo;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="roleid")
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
}

 

package com.sshFrame.zero.pojo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="rolerights")
public class Rolerights implements Serializable{
	private static final long serialVersionUID = 1L;
	private String id;
	private Role role;
	private Rights rights;
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="roleid")
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="rightsid")
	public Rights getRights() {
		return rights;
	}
	public void setRights(Rights rights) {
		this.rights = rights;
	}
}

 

package com.sshFrame.zero.pojo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="rightsresources")
public class Rightsresources implements Serializable{

	private static final long serialVersionUID = 1L;
	private String id;
	private Rights rights;
	private Resources resources;
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="rightsid")
	public Rights getRights() {
		return rights;
	}
	public void setRights(Rights rights) {
		this.rights = rights;
	}
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="resourcesid")
	public Resources getResources() {
		return resources;
	}
	public void setResources(Resources resources) {
		this.resources = resources;
	}
	
}

UserinfoService 这个一定要注意,要在setUserinfoDao方法里把当前的dao给basedao,否则,basedao会报空指针

package com.sshFrame.zero.service.users;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.sshFrame.zero.dao.users.UserinfoDao;
import com.sshFrame.zero.pojo.Userinfo;
import com.sshFrame.zero.service.BaseService;
/**
 * 用户管理
 * @author 雪精灵
 *
 * @param 
 */

@Service
@Component("userinfoService")
public class UserinfoService extends BaseService{
	private UserinfoDao userinfoDao;
	public UserinfoService() {
		super();
	}
	public Userinfo findlogin(String username,String password) throws Exception{
		Userinfo userinfo=new Userinfo();
		userinfo.setUsername(username);
		userinfo.setPassword(password);
		List userinfos = findByExample(userinfo);
		if(userinfos!=null&&!userinfos.isEmpty()){
			userinfo=userinfos.get(0);
		}else{
			userinfo=null;
		}
		return userinfo;
	}
	public List used(String userid,String url) throws Exception {
		String hql="select ur.userinfo.userid,re.name,re.url from Userrole ur,Role r,Rolerights rr,Rights ri,Rightsresources rs,Resources re "+
			"where ur.role.id=r.id and r.id=rr.role.id and rr.rights.id=ri.id and ri.id=rs.rights.id and rs.resources.id=re.id and "+
			"ur.userinfo.userid=? and re.url=?";
		List userResource = userinfoDao.findByHql(hql,userid,url);
		return userResource;
	}
	public UserinfoDao getUserinfoDao() {
		return userinfoDao;
	}
	/**
	 * 一定要用set方法注入,并赋值给baseDao,否则baseDao为null;
	 * 只适用于注入一个Dao
	 * @param userinfoDao
	 */
	@Autowired
	public void setUserinfoDao(UserinfoDao userinfoDao) {
		super.setBaseDao(userinfoDao);
		this.userinfoDao = userinfoDao;
	}
}
 
package com.sshFrame.zero.action.users;

import java.util.List;

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

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.sshFrame.zero.pojo.Userinfo;
import com.sshFrame.zero.service.users.UserinfoService;
/**
 * @author 雪精灵
 *
 * 
 */
@Namespace("/")
@Scope("prototype")
@Component("userinfoAction")
public class UserinfoAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
	private static final long serialVersionUID = 1L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	@Autowired
	private UserinfoService userinfoService;
	@Action(value="login",results={
			@Result(name="success",location="init.jsp"),
			@Result(name="failure",location="/index.jsp")
	})
	public String login(){
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		Userinfo userinfo=null;
		try {
			userinfo = userinfoService.findlogin(username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(userinfo==null){
			request.setAttribute("msg", "用户名或密码错误");
			return "failure";
		}else{
			request.getSession().setAttribute("userid", userinfo.getUserid());
		}
		return "success";
	}
	public boolean used(String userid,String url) {
		List list=null;
		try {
			list = userinfoService.used(userid, url);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		if(list!=null&&!list.isEmpty()){
			return true;
		}
		return false;
	}
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
	}
	public UserinfoService getUserinfoService() {
		return userinfoService;
	}
	public void setUserinfoService(UserinfoService userinfoService) {
		this.userinfoService = userinfoService;
	}
}
package com.sshFrame.zero.action.users;

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

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.opensymphony.xwork2.ActionSupport;
import com.sshFrame.zero.service.users.UserinfoService;
/**
 * @author 雪精灵
 *
 * 
 */
@Namespace("/admin")
@ParentPackage("default")
@Scope("prototype")
public class AdminAction extends ActionSupport implements ServletRequestAware,ServletResponseAware{
	private static final long serialVersionUID = 1L;
	@Autowired
	private UserinfoService userinfoService;
	private HttpServletRequest request;
	private HttpServletResponse response;
	@Action(value="init",results={@Result(name="success",location="main.jsp"),
			@Result(name="failure",location="/index.jsp")})
	public String init(){
		String userid=(String) request.getSession().getAttribute("userid");
		System.out.println(userid);
		return SUCCESS;
	}
	public UserinfoService getUserinfoService() {
		return userinfoService;
	}
	public void setUserinfoService(UserinfoService userinfoService) {
		this.userinfoService = userinfoService;
	}
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request=request;
	}
}


下面加入拦截器

package com.sshFrame.zero.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.sshFrame.zero.action.users.UserinfoAction;
import com.sshFrame.zero.exception.AhCustomException;
import com.sshFrame.zero.exception.AhCustomException.ExcCode;

/**
 * 用户权限拦截器,在struts.xml中配置
 * @author 雪精灵
 */
public class AuthorityInterceptor extends AbstractInterceptor{

	private static final long serialVersionUID = 2914081148619842225L;
	private UserinfoAction userinfoAction;
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
//		String method = invocation.getProxy().getMethod();
//		String actionName=invocation.getInvocationContext().getName();
		String userid = (String) request.getSession().getAttribute("userid");
		if(userid==null||"".equals(userid)){
			request.setAttribute("msg",AhCustomException.getExcMessage(ExcCode.Unlogined));
			return Action.ERROR;
		}
		//获取项目路径
		String contextPath=request.getServletContext().getContextPath();
		//获取当前路径
		String uri = request.getRequestURI();
		//当前相对项目的路径
		String actionUrl=uri.replace(contextPath, "");
		boolean used = userinfoAction.used(userid, actionUrl);
		if(used){
			return invocation.invoke();
		}else{
			request.setAttribute("msg",AhCustomException.getExcMessage(ExcCode.InvalidRights));
			return Action.ERROR;
		}
	}
	public UserinfoAction getUserinfoAction() {
		return userinfoAction;
	}
	public void setUserinfoAction(UserinfoAction userinfoAction) {
		this.userinfoAction = userinfoAction;
	}

}

 

package com.sshFrame.zero.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.sshFrame.zero.exception.AhCustomException;
import com.sshFrame.zero.exception.AhCustomException.ExcCode;

/**
 * 错误权限拦截器,在struts.xml中配置
 * @author 雪精灵
 */
public class ExceptionInterceptor extends AbstractInterceptor{
	private Logger logger=Logger.getLogger(ExceptionInterceptor.class);
	private static final long serialVersionUID = -3490533736557683231L;
	private String excMessage="";
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String result;
		HttpServletRequest request = ServletActionContext.getRequest();
		String uri = request.getRequestURI();
		try {
			result = invocation.invoke();
		} catch (HibernateException e) {
			e.printStackTrace();
			logger.error("异常拦截器拦截到异常:"+"
"+"uri为:"+uri+"
"+e); excMessage=AhCustomException.getExcMessage(ExcCode.DataProcessing); request.setAttribute("msg", excMessage); result=Action.ERROR; }catch (NullPointerException e) { e.printStackTrace(); logger.error("异常拦截器拦截到异常:"+"
"+"action的名称为:"+uri+"
"+e); excMessage=AhCustomException.getExcMessage(ExcCode.IllegalData); request.setAttribute("msg", excMessage); result=Action.ERROR; }catch (AhCustomException e) { e.printStackTrace(); logger.error("异常拦截器拦截到异常:"+"
"+"action的名称为:"+uri+"
"+e); excMessage=e.getExcMessage(); request.setAttribute("msg", excMessage); result=Action.ERROR; }catch (Exception e) { e.printStackTrace(); logger.error("异常拦截器拦截到异常:"+"
"+"action的名称为:"+uri+"
"+e); excMessage=AhCustomException.getExcMessage(ExcCode.AppError); request.setAttribute("msg", excMessage); result=Action.ERROR; } return result; } }

自定义异常类

package com.sshFrame.zero.exception;
/**
 * 自定义异常处理
 * @author 雪精灵
 */
public class AhCustomException extends Exception{

	private static final long serialVersionUID = 1L;
   /**
     * 错误类型标识
     */
	private ExcCode excCode = null;
	public enum ExcCode{
		AppError,
		InvalidRights,
		IllegalData,
		DataProcessing, 
		Unlogined
	}
	public static final String[] excMessage = {
		"内部异常",
		"您没有执行本操作的权限",
		"提供的数据为空或不合法",
		"数据处理异常",
		"您可能还没有登录本系统,或者已经超时,您必须先登录本系统后才能使用该功能

重新登录

" }; public AhCustomException(){ super(getExcMessage(ExcCode.AppError)); excCode = ExcCode.AppError; } /** * 构造函数 * * @param arg0 * 错误类型标识 */ public AhCustomException(ExcCode excCode) { super(getExcMessage(excCode)); this.excCode = excCode; } /** * 根据错误类型标识获取错误信息 * * @param emFlag * 错误类型标识 * * @return 错误信息 */ public static String getExcMessage(ExcCode excCode) { return excMessage[excCode.ordinal()]; } public String getExcMessage() { return excMessage[excCode.ordinal()]; } /** * 构造函数 * * @param arg0 * 错误类型标识 * * @param arg1 * 被包含的异常对象 */ public AhCustomException(ExcCode excCode, Throwable throwable) { super(getExcMessage(excCode), throwable); setStackTrace(throwable.getStackTrace()); this.excCode = excCode; } /** * 构造函数 * * @param arg0 * 被包含的异常对象 */ public AhCustomException(Throwable throwable) { super(getExcMessage(throwable.getClass() == AhCustomException.class ? ((AhCustomException) throwable).excCode : ExcCode.AppError), throwable); setStackTrace(throwable.getStackTrace()); if (throwable.getClass() == AhCustomException.class) excCode = ((AhCustomException) throwable).excCode; else excCode = excCode.AppError; } }

下面加入页面,index.jsp,在webContent下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
	
	
	    
	
	
	
  
  
  
  ${msg }
  
用户名:
密码:


init.jsp.在web-inf/content/下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'init.jsp' starting page
	
	
	    
	
	
	
	
  
  
 	欢迎进入
  


程序下载链接:http://download.csdn.net/detail/doublelucklysnow/5001504

你可能感兴趣的:(annotation,ssh,零配置,BaseDao,拦截器)