公司一直不是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中
<!-- spring 配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <description>Spring上下文</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <!-- hibernate 懒加载的问题过滤 ,可以不配置 --> <filter> <description>hibernate Session 过滤器</description> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <!-- struts配置 --> <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>
struts.xml配置
<struts> <!-- 使用Spring --> <constant name="struts.objectFactory" value="spring" /> <constant name="struts.devMode" value="true" /> <constant name="struts.configuration.xml.reload" value="true" /> <package name="default" extends="struts-default" namespace="/"> <interceptors> <!-- 使用权限拦截 --> <interceptor name="authority" class="com.sshFrame.zero.interceptor.AuthorityInterceptor"/> <!-- 异常拦截 --> <interceptor name="exceptionInterceptor" class="com.sshFrame.zero.interceptor.ExceptionInterceptor"/> <!-- 解决struts安全漏洞,拦截所有的带有#号的url --> <interceptor-stack name="baseStack"> <interceptor-ref name="authority"/> <interceptor-ref name="exceptionInterceptor"/> <interceptor-ref name="params"> <param name="excludeParams">.*\\u0023.*</param> </interceptor-ref> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <!-- 配置默认拦截器栈 --> <default-interceptor-ref name="baseStack"/> <global-results> <result name="login">/index.jsp</result> <result name="error">/error.jsp</result> </global-results> </package> </struts>
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" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/osdesignaid"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.sshFrame.zero.pojo</value> <value>com.sshFrame.test.pojo</value> </list> </property> </bean> <aop:aspectj-autoproxy /><!-- 代理 --> <!-- 定义事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 申明annotation 加载事务驱动 --> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED"/> <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到--> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config expose-proxy="true"> <!-- 只对业务逻辑层实施事务 --> <aop:pointcut id="txPointcut" expression="execution(* cn.javass..service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> <!-- 自动扫描包 --> <context:annotation-config /> <context:component-scan base-package="com.sshFrame.zero.*,com.sshFrame.test.*" annotation-config="true"/> </beans>
配置都写好了,
改写基本的框架类了
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 <T> */ public class BaseDao<T extends Serializable> { @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<T> findAll() throws Exception { List<T> 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<T> findByCriteria(Criteria criteria) throws Exception { List<T> 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<T> findByExample(T t) throws Exception { List<T> 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<Object[]> findByHql(String hql,final Object...objects) throws Exception{ List<Object[]> 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<Object[]> findBySql(String sql,final Object...objects){ List<Object[]> 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<T extends Serializable> { protected BaseDao<T> 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<T> findAll() throws Exception{ return baseDao.findAll(); } public List<T> findByExample(T t) throws Exception{ return baseDao.findByExample(t); } public BaseDao<T> getBaseDao() { return baseDao; } public void setBaseDao(BaseDao<T> 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<Userrole> userroles=new HashSet<Userrole>(); @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<Userrole> getUserroles() { return userroles; } public void setUserroles(Set<Userrole> 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<Userrole> userroles=new HashSet<Userrole>(); private Set<Rolerights> rolerights=new HashSet<Rolerights>(); @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<Userrole> getUserroles() { return userroles; } public void setUserroles(Set<Userrole> userroles) { this.userroles = userroles; } @OneToMany(cascade=CascadeType.REMOVE,fetch=FetchType.LAZY,mappedBy="role") public Set<Rolerights> getRolerights() { return rolerights; } public void setRolerights(Set<Rolerights> 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> rolerights=new HashSet<Rolerights>(); @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<Rolerights> getRolerights() { return rolerights; } public void setRolerights(Set<Rolerights> 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<Rightsresources> rightsresourcs=new HashSet<Rightsresources>(); @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<Rightsresources> getRightsresourcs() { return rightsresourcs; } public void setRightsresourcs(Set<Rightsresources> 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<Userinfo>{ 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<Userinfo> 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("异常拦截器拦截到异常:"+"<br/>"+"uri为:"+uri+"<br/>"+e); excMessage=AhCustomException.getExcMessage(ExcCode.DataProcessing); request.setAttribute("msg", excMessage); result=Action.ERROR; }catch (NullPointerException e) { e.printStackTrace(); logger.error("异常拦截器拦截到异常:"+"<br/>"+"action的名称为:"+uri+"<br/>"+e); excMessage=AhCustomException.getExcMessage(ExcCode.IllegalData); request.setAttribute("msg", excMessage); result=Action.ERROR; }catch (AhCustomException e) { e.printStackTrace(); logger.error("异常拦截器拦截到异常:"+"<br/>"+"action的名称为:"+uri+"<br/>"+e); excMessage=e.getExcMessage(); request.setAttribute("msg", excMessage); result=Action.ERROR; }catch (Exception e) { e.printStackTrace(); logger.error("异常拦截器拦截到异常:"+"<br/>"+"action的名称为:"+uri+"<br/>"+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 = { "内部异常", "您没有执行本操作的权限", "提供的数据为空或不合法", "数据处理异常", "您可能还没有登录本系统,或者已经超时,您必须先登录本系统后才能使用该功能<p><a href='../' target='_parent'>重新登录</a></p>" }; 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+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <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> ${msg } <form action="login" method="post"> <table> <tbody> <tr><td>用户名:</td><td><input type="text" name="username"/></td></tr> <tr><td>密码:</td><td><input type="password" name="password"/></td></tr> <tr><td colspan="2"><input type="submit" value="Login"/></td></tr> </tbody> </table> </form> </body> </html>
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+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'init.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"> --> <script type="text/javascript"> window.onload=function(){ window.location.href="admin/init"; } </script> </head> <body> 欢迎进入 </body> </html>
程序下载链接:http://download.csdn.net/detail/doublelucklysnow/5001504