• Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(一)


    相关的maven的 pom.xml

      1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      3   <modelVersion>4.0.0</modelVersion>
      4   <groupId>cn.com.cisec.vcs</groupId>
      5   <artifactId>VCS</artifactId>
      6   <packaging>war</packaging>
      7   <version>0.0.1-SNAPSHOT</version>
      8   <name>VCS Maven Webapp</name>
      9   <url>http://maven.apache.org</url>
     10   <dependencies>
     11     <dependency>  
     12         <groupId>org.apache.maven.plugins</groupId>  
     13         <artifactId>maven-resources-plugin</artifactId>  
     14         <version>2.6</version>  
     15     </dependency> 
     16     <dependency>
     17       <groupId>junit</groupId>
     18       <artifactId>junit</artifactId>
     19       <version>3.8.1</version>
     20       <scope>test</scope>
     21     </dependency>
     22       <!-- SpringMVC核心jar -->
     23      <dependency>
     24             <groupId>org.springframework</groupId>
     25             <artifactId>spring-context</artifactId>
     26             <version>4.0.2.RELEASE</version>
     27         </dependency>
     28         <dependency>
     29             <groupId>org.springframework</groupId>
     30             <artifactId>spring-tx</artifactId>
     31             <version>4.0.2.RELEASE</version>
     32         </dependency>
     33         <dependency>
     34             <groupId>org.springframework</groupId>
     35             <artifactId>spring-webmvc</artifactId>
     36             <version>4.0.2.RELEASE</version>
     37         </dependency>
     38         <dependency>
     39             <groupId>org.springframework</groupId>
     40             <artifactId>spring-core</artifactId>
     41             <version>4.0.2.RELEASE</version>
     42         </dependency>
     43         <dependency>
     44             <groupId>org.springframework</groupId>
     45             <artifactId>spring-web</artifactId>
     46             <version>4.0.2.RELEASE</version>
     47         </dependency>
     48         <dependency>
     49             <groupId>org.springframework</groupId>
     50             <artifactId>spring-orm</artifactId>
     51             <version>4.0.2.RELEASE</version>
     52         </dependency>
     53         <dependency>
     54             <groupId>org.springframework.security</groupId>
     55             <artifactId>spring-security-core</artifactId>
     56             <version>3.2.1.RELEASE</version>
     57         </dependency>
     58         <dependency>
     59             <groupId>org.springframework.security</groupId>
     60             <artifactId>spring-security-web</artifactId>
     61             <version>3.2.1.RELEASE</version>
     62         </dependency>
     63         <dependency>
     64             <groupId>org.springframework.security</groupId>
     65             <artifactId>spring-security-config</artifactId>
     66             <version>3.2.1.RELEASE</version>
     67         </dependency>
     68         <dependency>
     69             <groupId>org.springframework.security</groupId>
     70             <artifactId>spring-security-taglibs</artifactId>
     71             <version>3.2.1.RELEASE</version>
     72         </dependency>
     73         <dependency>
     74             <groupId>org.springframework</groupId>
     75             <artifactId>spring-aspects</artifactId>
     76             <version>4.0.2.RELEASE</version>
     77       </dependency>
     78       <dependency>
     79             <groupId>org.springframework</groupId>
     80             <artifactId>spring-beans</artifactId>
     81             <version>4.0.2.RELEASE</version>
     82         </dependency>
     83          <dependency>
     84             <groupId>org.springframework</groupId>
     85             <artifactId>spring-context-support</artifactId>
     86             <version>4.0.2.RELEASE</version>
     87         </dependency>
     88         <dependency>
     89             <groupId>org.springframework</groupId>
     90             <artifactId>spring-expression</artifactId>
     91             <version>4.0.2.RELEASE</version>
     92         </dependency>
     93         <dependency>
     94             <groupId>org.springframework</groupId>
     95             <artifactId>spring-jdbc</artifactId>
     96             <version>4.0.2.RELEASE</version>
     97         </dependency>
     98         <dependency>
     99             <groupId>org.springframework</groupId>
    100             <artifactId>spring-test</artifactId>
    101             <version>4.0.2.RELEASE</version>
    102             <scope>test</scope>
    103         </dependency>
    104         <!-- ************************************ -->
    105         <dependency>
    106             <groupId>org.codehaus.jackson</groupId>
    107             <artifactId>jackson-mapper-asl</artifactId>
    108             <version>1.9.13</version>
    109         </dependency>
    110         <dependency>
    111             <groupId>org.aspectj</groupId>
    112             <artifactId>aspectjrt</artifactId>
    113             <version>1.7.4</version>
    114         </dependency>
    115         <dependency>
    116             <groupId>org.aspectj</groupId>
    117             <artifactId>aspectjtools</artifactId>
    118             <version>1.7.4</version>
    119         </dependency>
    120         <!-- Hibernate相关jar -->
    121         <dependency>
    122             <groupId>fr.inria.powerapi.sensor</groupId>
    123             <artifactId>sensor-sigar</artifactId>
    124             <version>1.5</version>
    125         </dependency>
    126         <dependency>
    127             <groupId>net.sf.ehcache</groupId>
    128             <artifactId>ehcache</artifactId>
    129             <version>2.7.2</version>
    130         </dependency>
    131         <dependency>
    132             <groupId>commons-dbcp</groupId>
    133             <artifactId>commons-dbcp</artifactId>
    134             <version>1.4</version>
    135         </dependency>
    136         <dependency>
    137             <groupId>mysql</groupId>
    138             <artifactId>mysql-connector-java</artifactId>
    139             <version>5.1.26</version>
    140         </dependency>
    141         <!-- javax提供的annotation -->
    142         <dependency>
    143             <groupId>javax.inject</groupId>
    144             <artifactId>javax.inject</artifactId>
    145             <version>1</version>
    146         </dependency>
    147         <!-- **************************** -->
    148     
    149         <!-- hibernate验证 -->
    150         <dependency>
    151             <groupId>org.hibernate</groupId>
    152             <artifactId>hibernate-core</artifactId>
    153             <version>4.3.6.Final</version>
    154         </dependency>
    155         <dependency>
    156             <groupId>org.hibernate.common</groupId>
    157             <artifactId>hibernate-commons-annotations</artifactId>
    158             <version>4.0.5.Final</version>
    159         </dependency>
    160         <dependency>
    161             <groupId>org.hibernate</groupId>
    162             <artifactId>hibernate-entitymanager</artifactId>
    163             <version>4.3.6.Final</version>
    164         </dependency>
    165         <dependency>
    166             <groupId>org.hibernate.javax.persistence</groupId>
    167             <artifactId>hibernate-jpa-2.1-api</artifactId>
    168             <version>1.0.0.Final</version>
    169         </dependency>
    170         <dependency>
    171             <groupId>org.hibernate</groupId>
    172             <artifactId>hibernate-ehcache</artifactId>
    173             <version>4.3.6.Final</version>
    174         </dependency>
    175         <dependency>
    176             <groupId>org.hibernate</groupId>
    177             <artifactId>hibernate-validator</artifactId>
    178             <version>5.1.2.Final</version>
    179         </dependency>
    180         <dependency>
    181             <groupId>com.mchange</groupId>
    182             <artifactId>c3p0</artifactId>
    183             <version>0.9.5-pre8</version>
    184         </dependency>
    185         <!-- 提供对c标签的支持 -->
    186         <dependency>
    187             <groupId>javax.servlet</groupId>
    188             <artifactId>jstl</artifactId>
    189             <version>1.2</version>
    190         </dependency>
    191         <!-- servlet api -->
    192         <dependency>
    193             <groupId>javax.servlet</groupId>
    194             <artifactId>servlet-api</artifactId>
    195             <version>2.5</version>
    196             <scope>provided</scope>
    197         </dependency>
    198         <dependency>
    199             <groupId>org.apache.httpcomponents</groupId>
    200             <artifactId>httpclient</artifactId>
    201             <version>4.3.6</version>
    202         </dependency>
    203         <dependency>
    204             <groupId>javax.servlet.jsp</groupId>
    205             <artifactId>jsp-api</artifactId>
    206             <version>2.1</version>
    207             <scope>provided</scope>
    208         </dependency>
    209         <!-- json字符串的包 -->
    210         <dependency>
    211             <groupId>commons-collections</groupId>
    212             <artifactId>commons-collections</artifactId>
    213             <version>3.2.1</version>
    214         </dependency>
    215         <dependency>
    216             <groupId>net.sf.ezmorph</groupId>
    217             <artifactId>ezmorph</artifactId>
    218             <version>1.0.6</version>
    219         </dependency>
    220         <dependency>
    221             <groupId>net.sf.json-lib</groupId>
    222             <artifactId>json-lib</artifactId>
    223             <version>2.4</version>
    224         </dependency>        
    225         <!--Apache Shiro所需的jar包-->
    226         <dependency>
    227             <groupId>org.apache.shiro</groupId>
    228             <artifactId>shiro-core</artifactId>
    229             <version>1.2.3</version>
    230         </dependency>
    231         <dependency>
    232             <groupId>org.apache.shiro</groupId>
    233             <artifactId>shiro-web</artifactId>
    234             <version>1.2.3</version>
    235         </dependency>
    236         <dependency>
    237             <groupId>org.apache.shiro</groupId>
    238             <artifactId>shiro-spring</artifactId>
    239             <version>1.2.3</version>
    240         </dependency>
    241         <dependency>
    242             <groupId>org.apache.shiro</groupId>
    243             <artifactId>shiro-ehcache</artifactId>
    244             <version>1.2.3</version>
    245         </dependency>
    246         <dependency>
    247             <groupId>commons-io</groupId>
    248             <artifactId>commons-io</artifactId>
    249             <version>2.4</version>
    250         </dependency>
    251         <dependency>
    252             <groupId>commons-beanutils</groupId>
    253             <artifactId>commons-beanutils</artifactId>
    254             <version>1.8.3</version>
    255         </dependency>
    256         <dependency>
    257             <groupId>commons-fileupload</groupId>
    258             <artifactId>commons-fileupload</artifactId>
    259             <version>1.3.1</version>
    260         </dependency>
    261         <dependency>
    262             <groupId>commons-lang</groupId>
    263             <artifactId>commons-lang</artifactId>
    264             <version>2.6</version>
    265         </dependency>
    266         <dependency>
    267             <groupId>commons-logging</groupId>
    268             <artifactId>commons-logging</artifactId>
    269             <version>1.1.2</version>
    270         </dependency>
    271         <dependency>
    272             <groupId>org.slf4j</groupId>
    273             <artifactId>slf4j-log4j12</artifactId>
    274             <version>1.7.5</version>
    275         </dependency>
    276         <dependency>
    277             <groupId>asm</groupId>
    278             <artifactId>asm</artifactId>
    279             <version>3.3.1</version>
    280         </dependency>
    281         <dependency>
    282             <groupId>org.aspectj</groupId >
    283             <artifactId>aspectjweaver</artifactId >
    284             <version> 1.6.11</version >
    285         </dependency>
    286         <dependency>
    287             <groupId>com.google.code.gson</groupId>
    288             <artifactId>gson</artifactId>
    289             <version>2.2.4</version>
    290         </dependency>
    291   </dependencies>
    292   <build>
    293     <finalName>VCS</finalName>
    294     <plugins>
    295             <plugin>
    296                 <groupId>org.apache.maven.plugins</groupId>
    297                 <artifactId>maven-compiler-plugin</artifactId>
    298                 <version>2.3</version>
    299                 <configuration>
    300                     <source>1.6</source>
    301                     <target>1.6</target>
    302                 </configuration>
    303             </plugin>
    304             <plugin>
    305                 <artifactId>maven-war-plugin</artifactId>
    306                 <configuration>
    307                     <version>2.2</version>
    308                 </configuration>
    309             </plugin>
    310             <plugin>
    311                 <groupId>org.eclipse.jetty</groupId>
    312                 <artifactId>jetty-maven-plugin</artifactId>
    313                 <version>9.3.0.M1</version>
    314                 <configuration>
    315                     <scanIntervalSeconds>10</scanIntervalSeconds>
    316                     <webApp>
    317                         <contextPath>/VCS</contextPath>
    318                     </webApp>
    319                 </configuration>
    320             </plugin>
    321             <!-- <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> 
    322                 <version>2.0-SNAPSHOT</version> <configuration> <url>http://localhost:8080/controlserver</url> 
    323                 <server>Tomcat 7.x</server> </configuration> </plugin> -->
    324         </plugins>
    325   </build>
    326 </project>

    基础的java代码:

      1 package com.etop.basic.controller;
      2 
      3 import com.etop.utils.DateUtils;
      4 
      5 import org.apache.log4j.Logger;
      6 import org.springframework.stereotype.Controller;
      7 import org.springframework.ui.Model;
      8 import org.springframework.web.bind.WebDataBinder;
      9 import org.springframework.web.bind.annotation.ExceptionHandler;
     10 import org.springframework.web.bind.annotation.InitBinder;
     11 import org.springframework.web.servlet.mvc.support.RedirectAttributes;
     12 
     13 import javax.servlet.http.HttpServletRequest;
     14 
     15 import java.beans.PropertyEditorSupport;
     16 import java.util.Date;
     17 
     18 /**
     19  * @类名: BaseController
     20  * @描述: TODO(这里用一句话描述这个类的作用)
     21  * @作者 liuren-mail@163.com
     22  * @日期 2015年5月20日 下午3:11:32
     23  */
     24 @Controller
     25 public abstract class BaseController {
     26 
     27     public final static String ERROR = "error";
     28     public final static String SUCCESS = "success";
     29 
     30     protected Logger log = Logger.getLogger(this.getClass());
     31 
     32     /**
     33      * 添加Model消息
     34      * 
     35      * @param messages
     36      */
     37     protected void addMessage(Model model, String messages) {
     38         model.addAttribute("message", messages);
     39     }
     40 
     41     /**
     42      * 添加Model消息
     43      * 
     44      * @param type
     45      *            消息类型
     46      * @param messages
     47      */
     48     protected void addMessage(Model model, String type, String messages) {
     49         model.addAttribute("message", messages);
     50         model.addAttribute("type", type);
     51     }
     52 
     53     /**
     54      * 添加Flash消息
     55      * 
     56      * @param messages
     57      */
     58     protected void addMessage(RedirectAttributes redirectAttributes,
     59             String messages) {
     60         redirectAttributes.addFlashAttribute("message", messages);
     61     }
     62 
     63     /**
     64      * 添加Flash消息
     65      * 
     66      * @param type
     67      *            消息类型
     68      * @param messages
     69      */
     70     protected void addMessage(RedirectAttributes redirectAttributes,
     71             String type, String messages) {
     72         redirectAttributes.addFlashAttribute("message", messages);
     73         redirectAttributes.addFlashAttribute("type", type);
     74     }
     75 
     76     /**
     77      * 初始化数据绑定 1. 将所有传递进来的String进行HTML编码,防止XSS攻击 2. 将字段中Date类型转换为String类型
     78      */
     79     @InitBinder
     80     protected void initBinder(WebDataBinder binder) {
     81         // String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
     82         binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
     83             @Override
     84             public void setAsText(String text) {
     85                 // setValue(text == null ? null :
     86                 // StringEscapeUtils.escapeHtml(text.trim()));
     87                 setValue(text == null ? null : text.trim());
     88             }
     89 
     90             @Override
     91             public String getAsText() {
     92                 Object value = getValue();
     93                 return value != null ? value.toString() : "";
     94             }
     95         });
     96         // Date 类型转换
     97         binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
     98             @Override
     99             public void setAsText(String text) {
    100                 setValue(DateUtils.parseDate(text));
    101             }
    102         });
    103     }
    104 
    105     @ExceptionHandler(Exception.class)
    106     public String handleException(Exception ex, HttpServletRequest request) {
    107         log.error("系统发生异常", ex);
    108         ex.printStackTrace();
    109         request.setAttribute("exMsg", ex.getMessage());
    110         return "errors/exception";
    111     }
    112 }
      1 package com.etop.basic.dao;
      2 
      3 import org.apache.log4j.Logger;
      4 import org.hibernate.Query;
      5 import org.hibernate.SQLQuery;
      6 import org.hibernate.Session;
      7 import org.hibernate.SessionFactory;
      8 import org.hibernate.StatelessSession;
      9 import org.hibernate.transform.Transformers;
     10 import org.springframework.beans.factory.annotation.Autowired;
     11 import org.springframework.dao.DataAccessException;
     12 import com.etop.utils.PageUtil;
     13 import com.etop.utils.ThreadLocalUtils;
     14 
     15 import java.io.Serializable;
     16 import java.lang.reflect.ParameterizedType;
     17 import java.math.BigInteger;
     18 import java.util.Collection;
     19 import java.util.List;
     20 import java.util.Map;
     21 import java.util.Set;
     22 
     23 /**
     24  * @类名: BaseDAO
     25  * @描述: TODO(这里用一句话描述这个类的作用)
     26  * @作者 liuren-mail@163.com
     27  * @日期 2015年5月20日 下午3:12:00
     28  * @param <T>
     29  */
     30 public class BaseDAO<T> implements Serializable {
     31 
     32     protected transient Logger log = Logger.getLogger(this.getClass());
     33     @Autowired
     34     private SessionFactory sessionFactory;
     35     private Class<T> persistentClass;
     36 
     37     protected Class<T> getCurClass() {
     38         if (persistentClass == null) {
     39             this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
     40                     .getGenericSuperclass()).getActualTypeArguments()[0];
     41         }
     42         return persistentClass;
     43     }
     44 
     45     protected Session getSession() {
     46         return sessionFactory.getCurrentSession();
     47     }
     48 
     49     protected StatelessSession getStatelessSession() {
     50         return sessionFactory.openStatelessSession();
     51     }
     52 
     53     public void flush() {
     54         getSession().flush();
     55     }
     56 
     57     public void evict(T entity) {
     58         getSession().evict(entity);
     59     }
     60 
     61     public T get(long id) throws DataAccessException {
     62         log.debug("DAO:Get entity " + getCurClass().getSimpleName() + ":Id="
     63                 + id);
     64         return (T) getSession().get(getCurClass(), id);
     65     }
     66 
     67     public void save(T entity) throws DataAccessException {
     68         log.debug("DAO:Save entity " + entity.getClass().getSimpleName());
     69         getSession().save(entity);
     70     }
     71 
     72     public void update(T entity) throws DataAccessException {
     73         log.debug("DAO:Update entity " + entity.getClass().getSimpleName());
     74         getSession().clear();
     75         getSession().update(entity);
     76     }
     77 
     78     public void saveOrUpdate(T entity) throws DataAccessException {
     79         log.debug("DAO:Sava or Update entity "
     80                 + entity.getClass().getSimpleName());
     81         getSession().clear();
     82         getSession().saveOrUpdate(entity);
     83     }
     84 
     85     public void delete(T entity) throws DataAccessException {
     86         log.debug("DAO:delete entity " + getCurClass().getSimpleName());
     87         getSession().delete(entity);
     88     }
     89 
     90     public void deleteById(long id) throws DataAccessException {
     91         log.debug("DAO:delete entity " + getCurClass().getSimpleName() + ":Id="
     92                 + id);
     93         String queryString = "delete from " + getCurClass().getSimpleName()
     94                 + " where id=" + id;
     95         this.excute(queryString);
     96     }
     97 
     98     public int excute(String queryString) throws DataAccessException {
     99         log.debug("DAO:Excute HQL update :" + queryString);
    100         Query query = getSession().createQuery(queryString);
    101         return query.executeUpdate();
    102     }
    103 
    104     public List<T> find(String queryString) throws DataAccessException {
    105         log.debug("DAO:Running HQL query :" + queryString);
    106         Query query = getSession().createQuery(queryString);
    107         query.setCacheable(true);
    108         return query.list();
    109     }
    110 
    111     private Query createQuery(String queryString, Map<String, Object> params,
    112             int startRow, int pageSize) {
    113         Query query = getSession().createQuery(queryString);
    114         if (params != null) {
    115             for (Map.Entry<String, Object> entry : params.entrySet()) {
    116                 String paramName = entry.getKey();
    117                 Object obj = entry.getValue();
    118                 log.info("DAO:set param:" + paramName + " with value:" + obj);
    119                 if (obj instanceof List) {
    120                     query.setParameterList(paramName, (Collection) obj);
    121                 } else if (obj instanceof Object[]) {
    122                     query.setParameterList(paramName, (Object[]) obj);
    123                 } else {
    124                     query.setParameter(paramName, obj);
    125                 }
    126             }
    127         }
    128         query.setCacheable(true);
    129         if (pageSize != -1) {
    130             query.setFirstResult(startRow).setMaxResults(pageSize);
    131         }
    132         return query;
    133     }
    134 
    135     private Query createQuery(String queryString) {
    136         return createQuery(queryString, null, 0, -1);
    137     }
    138 
    139     private Query createQuery(String queryString, Map<String, Object> params) {
    140         return createQuery(queryString, params, 0, -1);
    141     }
    142 
    143     public List<T> find(String queryString, int startRow, int pageSize)
    144             throws DataAccessException {
    145         log.debug("DAO:Running HQL query by page:" + queryString);
    146         Query query = createQuery(queryString, null, startRow, pageSize);
    147         return query.list();
    148     }
    149 
    150     public int getTotalCount(String queryString) throws DataAccessException {
    151         return getTotalCount(queryString, null);
    152     }
    153 
    154     public int getTotalCount(String queryString, Map<String, Object> params)
    155             throws DataAccessException {
    156         log.debug("DAO:Running HQL query for total count of records :"
    157                 + queryString);
    158         queryString = "select count(t.id) " + queryString;
    159         Query query;
    160         if (params != null) {
    161             query = createQuery(queryString, params);
    162         } else {
    163             query = createQuery(queryString);
    164         }
    165         return ((Long) query.uniqueResult()).intValue();
    166     }
    167 
    168     public List findWithSelect(String queryString) throws DataAccessException {
    169         log.debug("DAO:Running HQL query with selections :" + queryString);
    170         Query query = createQuery(queryString);
    171         return query.list();
    172     }
    173 
    174     public List findWithSelect(String queryString, Map<String, Object> params)
    175             throws DataAccessException {
    176         log.debug("DAO:Running HQL query with parameters:" + queryString);
    177         Query query = createQuery(queryString, params);
    178         return query.list();
    179     }
    180 
    181     public List findWithSelect(String queryString, Map<String, Object> params,
    182             int startRow, int pageSize) throws DataAccessException {
    183         log.debug("DAO:Running HQL query by page :" + queryString);
    184         Query query = createQuery(queryString, params, startRow, pageSize);
    185         return query.list();
    186     }
    187 
    188     public List<T> find(String queryString, Map<String, Object> params)
    189             throws DataAccessException {
    190         log.debug("DAO:Running HQL query with parameters: " + queryString);
    191         Query query = createQuery(queryString, params);
    192         return query.list();
    193     }
    194 
    195     public List<T> find(String queryString, Map<String, Object> params,
    196             int startRow, int pageSize) throws DataAccessException {
    197         log.debug("DAO:Running HQL query with params by page :" + queryString);
    198         Query query = createQuery(queryString, params, startRow, pageSize);
    199         return query.list();
    200     }
    201 
    202     public T findUniqueResult(String queryString, Map<String, Object> params)
    203             throws DataAccessException {
    204         log.debug("DAO:Running HQL query with parameters:" + queryString);
    205         Query query = createQuery(queryString, params);
    206         return (T) query.uniqueResult();
    207     }
    208 
    209     public int excute(String queryString, Map<String, Object> params)
    210             throws DataAccessException {
    211         log.debug("DAO:Excute HQL update :" + queryString);
    212         Query query = createQuery(queryString, params);
    213         return query.executeUpdate();
    214     }
    215 
    216     /**
    217      * pagefind
    218      */
    219     private String initSort(String hql) {
    220         log.debug("DAO:Excute HQL update :" + hql);
    221         String order = ThreadLocalUtils.getOrder();
    222         String sort = ThreadLocalUtils.getSort();
    223         if (sort != null && !"".equals(sort.trim())) {
    224             hql += " order by " + sort;
    225             if (!"desc".equals(order))
    226                 hql += " asc";
    227             else
    228                 hql += " desc";
    229         }
    230         return hql;
    231     }
    232 
    233     @SuppressWarnings("rawtypes")
    234     private void setAliasParameter(Query query, Map<String, Object> alias) {
    235         if (alias != null) {
    236             Set<String> keys = alias.keySet();
    237             for (String key : keys) {
    238                 Object val = alias.get(key);
    239                 if (val instanceof Collection) {
    240                     // 查询条件是列表
    241                     query.setParameterList(key, (Collection) val);
    242                 } else {
    243                     query.setParameter(key, val);
    244                 }
    245             }
    246         }
    247     }
    248 
    249     private void setParameter(Query query, Object[] args) {
    250         if (args != null && args.length > 0) {
    251             int index = 0;
    252             for (Object arg : args) {
    253                 query.setParameter(index++, arg);
    254             }
    255         }
    256     }
    257 
    258     private String getCountHql(String hql, boolean isHql) {
    259         log.debug("DAO:Excute HQL update :" + hql);
    260         String e = hql.substring(hql.indexOf("from"));
    261         String c = "select count(*) " + e;
    262         if (isHql)
    263             c = c.replaceAll("fetch", "");
    264         return c;
    265     }
    266 
    267     public PageUtil<T> pagefind(String hql, Object[] args,
    268             Map<String, Object> alias) {
    269         log.debug("DAO:Excute HQL update :" + hql);
    270         hql = initSort(hql);
    271         String cq = getCountHql(hql, true);
    272         Query cquery = getSession().createQuery(cq);
    273         Query query = getSession().createQuery(hql);
    274         // 设置别名参数
    275         setAliasParameter(query, alias);
    276         setAliasParameter(cquery, alias);
    277         // 设置参数
    278         setParameter(query, args);
    279         setParameter(cquery, args);
    280         PageUtil<T> pages = new PageUtil<T>();
    281         setPagers(query, pages);
    282         List<T> datas = query.list();
    283         pages.setRows(datas);
    284         long total = (Long) cquery.uniqueResult();
    285         pages.setTotal(total);
    286         return pages;
    287     }
    288 
    289     public PageUtil<T> pagefind(String hql, Object[] args) {
    290         log.debug("DAO:Excute HQL update :" + hql);
    291         return this.pagefind(hql, args, null);
    292     }
    293 
    294     public PageUtil<T> pagefind(String hql, Object arg) {
    295         log.debug("DAO:Excute HQL update :" + hql);
    296         return this.pagefind(hql, new Object[] { arg });
    297     }
    298 
    299     public PageUtil<T> pagefind(String hql) {
    300         log.debug("DAO:Excute HQL update :" + hql);
    301         return this.pagefind(hql, null);
    302     }
    303 
    304     @SuppressWarnings("rawtypes")
    305     private void setPagers(Query query, PageUtil pages) {
    306         Integer pageSize = ThreadLocalUtils.getPageSize();
    307         Integer pageOffset = ThreadLocalUtils.getPageOffset();
    308         if (pageOffset == null || pageOffset < 0)
    309             pageOffset = 0;
    310         if (pageSize == null || pageSize < 0)
    311             pageSize = 15;
    312         // pages.setOffset(pageOffset);
    313         // pages.setSize(pageSize);
    314         query.setFirstResult(pageOffset).setMaxResults(pageSize);
    315     }
    316 
    317     public <N extends Object> PageUtil<N> findBySql(String sql, Object[] args,
    318             Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
    319         sql = initSort(sql);
    320         String cq = getCountHql(sql, false);
    321         SQLQuery sq = getSession().createSQLQuery(sql);
    322         SQLQuery cquery = getSession().createSQLQuery(cq);
    323         setAliasParameter(sq, alias);
    324         setAliasParameter(cquery, alias);
    325         setParameter(sq, args);
    326         setParameter(cquery, args);
    327         PageUtil<N> pages = new PageUtil<N>();
    328         // setPagers(sq, pages);
    329         if (hasEntity) {
    330             sq.addEntity(clz);
    331         } else {
    332             sq.setResultTransformer(Transformers.aliasToBean(clz));
    333         }
    334         List<N> datas = sq.list();
    335         pages.setRows(datas);
    336         long total = ((BigInteger) cquery.uniqueResult()).longValue();
    337         pages.setTotal(total);
    338         return pages;
    339     }
    340 
    341     public <N extends Object> PageUtil<N> findBySql(String sql, Object[] args,
    342             Class<?> clz, boolean hasEntity) {
    343         return this.findBySql(sql, args, null, clz, hasEntity);
    344     }
    345 
    346     public <N extends Object> PageUtil<N> findBySql(String sql, Object arg,
    347             Class<?> clz, boolean hasEntity) {
    348         return this.findBySql(sql, new Object[] { arg }, clz, hasEntity);
    349     }
    350 
    351     public <N extends Object> PageUtil<N> findBySql(String sql, Class<?> clz,
    352             boolean hasEntity) {
    353         return this.findBySql(sql, null, clz, hasEntity);
    354     }
    355 }
      1 package com.etop.controller;
      2 
      3 import java.util.HashMap;
      4 import java.util.Map;
      5 import java.util.Set;
      6 
      7 import org.apache.log4j.Logger;
      8 import org.springframework.beans.factory.annotation.Autowired;
      9 import org.springframework.stereotype.Controller;
     10 import org.springframework.web.bind.annotation.RequestMapping;
     11 import org.springframework.web.bind.annotation.ResponseBody;
     12 
     13 import com.etop.basic.controller.BaseController;
     14 import com.etop.dto.FunctionDto;
     15 import com.etop.pojo.Function;
     16 import com.etop.pojo.Permission;
     17 import com.etop.pojo.Role;
     18 import com.etop.service.FunctionService;
     19 import com.etop.service.PermissionService;
     20 import com.etop.service.RoleService;
     21 import com.etop.utils.PageUtil;
     22 
     23 /**
     24  * @类名: FunctionController
     25  * @描述: 处理过滤网址出的控制器
     26  * @作者 liuren-mail@163.com
     27  * @日期 2015年5月27日 下午3:31:54
     28  */
     29 @Controller
     30 @RequestMapping("/function")
     31 public class FunctionController extends BaseController {
     32     Map<String,Object> map = new HashMap<String,Object>();
     33     private final static Logger log = Logger
     34             .getLogger(FunctionController.class);
     35     @Autowired
     36     private FunctionService functionService;
     37     @Autowired
     38     private PermissionService permissionService;
     39     @Autowired
     40     private RoleService roleService;
     41     @RequestMapping("/functionList.html")
     42     public String getFunctions() {
     43         log.info("/functionList.html");
     44         return "/functionList.jsp";
     45     }
     46 
     47     /**
     48      * @标题: getFunctionList
     49      * @描述: 返回分页的json数据
     50      * @参数 @return 设定文件
     51      * @返回 Object 返回类型
     52      * @throws
     53      * @作者 liuren-mail@163.com
     54      * @日期 2015年5月27日 下午3:55:12
     55      */
     56     @RequestMapping("/get_functions.html")
     57     @ResponseBody
     58     public Object getFunctionList() {
     59         log.info("/get_functions.html");
     60         PageUtil<FunctionDto> functionList = functionService.findAllFunction();
     61         return functionList;
     62     }
     63 
     64     @RequestMapping("/add.html")
     65     @ResponseBody
     66     public Object addFunction(String value,int permission_id,int role_id,String type) {
     67         log.info("/add.html");
     68         Function function = new Function();
     69         function.setPermission_id(permission_id);
     70         function.setRole_id(role_id);
     71         function.setValue(value);
     72         function.setType(type);
     73         functionService.saveFunction(function);
     74         map.put(SUCCESS, true);
     75         return map;
     76     }
     77 
     78     @RequestMapping("/edit.html")
     79     @ResponseBody
     80     public Object updateFunction(int id,String value,String type) {
     81         log.info("/edit.html");
     82         Function function = functionService.findFunctionById(id);
     83         if (function==null||"".equals(function)) {
     84             map.put(SUCCESS, false);
     85             return map;
     86         }
     87         function.setValue(value);
     88         function.setType(type);
     89         functionService.updateFunction(function);
     90         map.put(SUCCESS, true);
     91         return map;
     92     }
     93 
     94     @RequestMapping("/del.html")
     95     @ResponseBody
     96     public Object deleteFunction(int id) {
     97         log.info("/del.html");
     98         functionService.deleteFunction(id);
     99         map.put(SUCCESS, true);
    100         return map;
    101     }
    102 }
      1 package com.etop.controller;
      2 
      3 import javax.imageio.ImageIO;
      4 import javax.servlet.ServletOutputStream;
      5 import javax.servlet.http.HttpServletRequest;
      6 import javax.servlet.http.HttpServletResponse;
      7 import javax.servlet.http.HttpSession;
      8 import javax.validation.Valid;
      9 
     10 import com.etop.basic.controller.BaseController;
     11 import com.etop.service.UserService;
     12 import com.etop.utils.VerifyCode;
     13 
     14 import org.apache.commons.lang.StringUtils;
     15 import org.apache.log4j.Logger;
     16 import org.apache.shiro.SecurityUtils;
     17 import org.apache.shiro.authc.AuthenticationException;
     18 import org.apache.shiro.authc.UsernamePasswordToken;
     19 import org.apache.shiro.web.util.WebUtils;
     20 import org.springframework.beans.factory.annotation.Autowired;
     21 import org.springframework.stereotype.Controller;
     22 import org.springframework.ui.Model;
     23 import org.springframework.validation.BindingResult;
     24 import org.springframework.web.bind.annotation.RequestMapping;
     25 import org.springframework.web.bind.annotation.RequestMethod;
     26 
     27 import com.etop.pojo.User;
     28 
     29 import org.springframework.web.servlet.mvc.support.RedirectAttributes;
     30 
     31 import java.awt.Color;
     32 import java.awt.image.BufferedImage;
     33 import java.io.IOException;
     34 import java.util.List;
     35 
     36 /**
     37  * @类名: HomeController
     38  * @描述: 处理用户登录登出的控制器
     39  * @作者 liuren-mail@163.com
     40  * @日期 2015年5月20日 下午3:11:00
     41  */
     42 @Controller
     43 public class HomeController extends BaseController {
     44     private final static Logger log = Logger.getLogger(HomeController.class);
     45     @Autowired
     46     private UserService userService;
     47 
     48     @RequestMapping(value = "/login.html", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
     49     public String loginForm(Model model, String message) {
     50         if (!StringUtils.isEmpty(message))
     51             model.addAttribute(message);
     52         model.addAttribute("user", new User());
     53         System.out.println("login_1");
     54         System.out.println("model:" + model);
     55         System.out.println("message:" + message);
     56         log.info("login.html");
     57         return "/login.jsp";
     58     }
     59 
     60     @RequestMapping(value = "/login.html", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
     61     public String login(@Valid User user, BindingResult bindingResult,
     62             Model model, RedirectAttributes attr, HttpServletRequest request) {
     63         HttpSession session = request.getSession();
     64         // session为空时跳转到登录界面
     65         if (session.getAttribute(VerifyCode.VERIFY_TYPE_COMMENT) == null
     66                 || session.getAttribute(VerifyCode.VERIFY_TYPE_COMMENT) == "") {
     67             addMessage(attr, "session为空");
     68             log.info("session为空");
     69             return "redirect:/";
     70         }
     71         String code = ((String) request.getSession().getAttribute(
     72                 VerifyCode.VERIFY_TYPE_COMMENT)).toLowerCase();
     73         String submitCode = WebUtils.getCleanParam(request, "checkcode");
     74         if (StringUtils.isEmpty(code) || StringUtils.isEmpty(submitCode)
     75                 || !StringUtils.equals(code, submitCode.toLowerCase())) {
     76             addMessage(attr, "验证码错误");
     77             log.info("验证码错误");
     78             return "redirect:/";
     79         }
     80         try {
     81             if (bindingResult.hasErrors() || user.getUsername().isEmpty()
     82                     || user.getPassword().isEmpty()) {
     83                 addMessage(attr, "用户名或密码错误");
     84                 log.info("用户名或密码错误");
     85                 return "redirect:/login.html";
     86             }
     87             System.out.println("管理用户登录");
     88             // 使用shiro管理登录
     89             SecurityUtils.getSubject().login(
     90                     new UsernamePasswordToken(user.getUsername(), user
     91                             .getPassword()));
     92             // 获取所有用户信息,权限由前端shiro标签控制
     93             List<User> userList = userService.getAllUser();
     94             System.out.println(userList);
     95             model.addAttribute("userList", userList);
     96             System.out.println("管理用户登录success");
     97             log.info("成功登录");
     98             System.out.println("密码:======================"+user.getPassword());
     99             return "/user.jsp";
    100         } catch (AuthenticationException e) {
    101             addMessage(attr, "用户名或密码错误");
    102             log.info("用户名或密码错误");
    103             return "redirect:/login.html";
    104         }
    105     }
    106 
    107     @RequestMapping(value = "/logout.html", method = RequestMethod.GET)
    108     public String logout(RedirectAttributes attr) {
    109         // 使用权限管理工具进行用户的退出,注销登录
    110         SecurityUtils.getSubject().logout();
    111         addMessage(attr, "您已安全退出");
    112         log.info("安全退出");
    113         return "redirect:/login.html";
    114     }
    115 
    116     @RequestMapping("/403.html")
    117     public String unauthorizedRole() {
    118         log.info("跳转到403页面");
    119         return "/403.jsp";
    120     }
    121 
    122     @RequestMapping("/verifyCode.html")
    123     public void verifyCode(HttpServletRequest request,
    124             HttpServletResponse response) throws IOException {
    125         response.setHeader("Pragma", "no-cache");
    126         response.setHeader("Cache-Control", "no-cache");
    127         response.setDateHeader("Expires", 0);
    128         // 生成验证码,写入用户session
    129         String verifyCode = VerifyCode.generateTextCode(
    130                 VerifyCode.TYPE_NUM_UPPER, 4, "null");
    131         request.getSession().setAttribute(VerifyCode.VERIFY_TYPE_COMMENT,
    132                 verifyCode);
    133         System.out.println("verifyCode=" + verifyCode);
    134         // 输出验证码给客户端
    135         response.setContentType("image/jpeg");
    136         /*
    137          * textCode 文本验证码 width 图片宽度 height 图片高度 interLine 图片中干扰线的条数
    138          * randomLocation 每个字符的高低位置是否随机 backColor 图片颜色,若为null,则采用随机颜色 f
    139          * oreColor字体颜色,若为null,则采用随机颜色 lineColor 干扰线颜色,若为null,则采用随机颜色
    140          */
    141         BufferedImage bim = VerifyCode.generateImageCode(verifyCode, 65, 22, 8,
    142                 true, Color.WHITE, Color.BLACK, null);
    143         ServletOutputStream out = response.getOutputStream();
    144         ImageIO.write(bim, "JPEG", out);
    145         log.info("验证码已经生成并存入session中");
    146         try {
    147             out.flush();
    148             log.info("刷新验证码图片");
    149         } finally {
    150             out.close();
    151             log.info("关闭验证码流");
    152         }
    153     }
    154 }
      1 package com.etop.controller;
      2 
      3 import java.util.HashMap;
      4 import java.util.Map;
      5 
      6 import org.apache.log4j.Logger;
      7 import org.springframework.beans.factory.annotation.Autowired;
      8 import org.springframework.stereotype.Controller;
      9 import org.springframework.web.bind.annotation.RequestMapping;
     10 import org.springframework.web.bind.annotation.ResponseBody;
     11 
     12 
     13 
     14 import com.etop.basic.controller.BaseController;
     15 import com.etop.dto.PermissionDto;
     16 import com.etop.pojo.Permission;
     17 import com.etop.service.PermissionService;
     18 import com.etop.utils.PageUtil;
     19 
     20 /**
     21  * @类名: PermissionController
     22  * @描述: 处理用户权限的控制器
     23  * @作者 liuren-mail@163.com
     24  * @日期 2015年5月27日 下午3:28:09
     25  */
     26 @Controller
     27 @RequestMapping("/permission")
     28 public class PermissionController extends BaseController {
     29     Map<String,Object> map = new HashMap<String,Object>();
     30     private final static Logger log = Logger
     31             .getLogger(PermissionController.class);
     32     @Autowired
     33     private PermissionService permissionService;
     34 
     35     @RequestMapping("/permissonList.html")
     36     public String getPermissons() {
     37         log.info("/permissionList.html");
     38         return "/permissonList.jsp";
     39     }
     40 
     41     /**
     42      * @标题: getPermissionList
     43      * @描述: 返回分页的json数据
     44      * @参数 @return 设定文件
     45      * @返回 Object 返回类型
     46      * @throws
     47      * @作者 liuren-mail@163.com
     48      * @日期 2015年5月27日 下午3:33:27
     49      */
     50     @RequestMapping("/get_permissions.html")
     51     @ResponseBody
     52     public Object getPermissionList() {
     53         log.info("/get_permission.html");
     54         PageUtil<PermissionDto> permissionList = permissionService
     55                 .findAllPermisson();
     56         return permissionList;
     57     }
     58 
     59     @RequestMapping("/add.html")
     60     @ResponseBody
     61     public Object addPermission(String permissionname) {
     62         log.info("/add.html");
     63         if (permissionname==null||"".equals(permissionname)) {
     64             map.put("success", false);
     65             return map;
     66         }
     67         Permission permission = new Permission();
     68         permission.setPermissionname(permissionname);
     69         permissionService.savePermission(permission);
     70         map.put("success", true);
     71         return map;
     72     }
     73 
     74     @RequestMapping("/edit.html")
     75     @ResponseBody
     76     public Object updatePermission(int id,String permissionname) {
     77         log.info("/edit.html");
     78         Permission permission =permissionService.findPermissionById(id);
     79         if (permission==null||"".equals(permission)) {
     80             map.put("success", false);
     81         }
     82         permission.setPermissionname(permissionname);
     83         permissionService.updatePermission(permission);
     84         map.put("success", true);
     85         return map;
     86     }
     87 
     88     @RequestMapping("/del.html")
     89     @ResponseBody
     90     public Object deletePermission(int id) {
     91         log.info("/del.html");
     92         Permission permission = permissionService.findPermissionById(id);
     93         if (permission==null||"".equals(permission)) {
     94             map.put("success", false);
     95             return map;
     96         }
     97         permissionService.deletePermission(id);
     98         map.put("success", true);
     99         return map;
    100     }
    101 }
      1 package com.etop.controller;
      2 
      3 import java.util.HashMap;
      4 import java.util.Map;
      5 
      6 import org.apache.log4j.Logger;
      7 import org.springframework.beans.factory.annotation.Autowired;
      8 import org.springframework.stereotype.Controller;
      9 import org.springframework.web.bind.annotation.RequestMapping;
     10 import org.springframework.web.bind.annotation.ResponseBody;
     11 
     12 import com.etop.basic.controller.BaseController;
     13 import com.etop.dto.RoleDto;
     14 import com.etop.pojo.Role;
     15 import com.etop.service.RoleService;
     16 import com.etop.utils.PageUtil;
     17 
     18 /**
     19  * @类名: RoleController
     20  * @描述: 处理角色操作的控制器
     21  * @作者 liuren-mail@163.com
     22  * @日期 2015年5月26日 下午6:09:03
     23  */
     24 @Controller
     25 @RequestMapping("/role")
     26 public class RoleController extends BaseController {
     27     Map<String,Object> map = new HashMap<String,Object>();
     28     private final static Logger log = Logger.getLogger(RoleController.class);
     29     @Autowired
     30     private RoleService roleService;
     31 
     32     @RequestMapping("/roleList.html")
     33     public String getRoles() {
     34         log.info("/roleList.html");
     35         return "/roleList.jsp";
     36     }
     37 
     38     /**
     39      * @标题: getRoleList
     40      * @描述: 返回json数据
     41      * @参数 @return 设定文件
     42      * @返回 Object 返回类型
     43      * @throws
     44      * @作者 liuren-mail@163.com
     45      * @日期 2015年5月27日 下午3:56:39
     46      */
     47     @RequestMapping("/get_roles.html")
     48     @ResponseBody
     49     public Object getRoleList() {
     50         log.info("/get_roles.html");
     51         PageUtil<RoleDto> roleList = roleService.findAllRole();
     52         return roleList;
     53     }
     54 
     55     @RequestMapping("/add.html")
     56     @ResponseBody
     57     public Object addRole(String rolename,String description) {
     58         log.info("/add.html");
     59         Role role = new Role();
     60         if (rolename==null||description==null||"".equals(rolename)||"".equals(description)) {
     61             map.put("success", false);
     62             return map;
     63         }
     64         role.setRolename(rolename);
     65         role.setDescription(description);
     66         roleService.saveRole(role);
     67         map.put("success", true);
     68         return map;
     69     }
     70 
     71     @RequestMapping("/edit.html")
     72     @ResponseBody
     73     public Object updateRole(int id,String rolename,String description) {
     74         log.info("/edit.html");
     75         Role role = roleService.findById(id);
     76         if (role==null||"".equals(role)) {
     77             map.put("success", false);
     78         }
     79         role.setRolename(rolename);
     80         role.setDescription(description);
     81         roleService.updateRole(role);
     82         map.put("success", true);
     83         return map;
     84     }
     85 
     86     @RequestMapping("/del.html")
     87     @ResponseBody
     88     public Object deleteRole(int id) {
     89         log.info("/del.html");
     90         roleService.deleteRole(id);
     91         map.put("success", true);
     92         return map;
     93     }
     94 
     95     @RequestMapping("/roleTest.html")
     96     public String testRole() {
     97         log.info("roleTest.html");
     98         return "/success.jsp";
     99     }
    100 }
      1 package com.etop.controller;
      2 
      3 import java.util.HashMap;
      4 import java.util.Map;
      5 
      6 import org.apache.log4j.Logger;
      7 import org.springframework.beans.factory.annotation.Autowired;
      8 import org.springframework.stereotype.Controller;
      9 import org.springframework.web.bind.annotation.RequestMapping;
     10 import org.springframework.web.bind.annotation.ResponseBody;
     11 
     12 import com.etop.basic.controller.BaseController;
     13 import com.etop.dto.UserDto;
     14 import com.etop.pojo.User;
     15 import com.etop.service.UserService;
     16 import com.etop.utils.MD5Utils;
     17 import com.etop.utils.PageUtil;
     18 
     19 /**
     20  * @类名: UserController
     21  * @描述: 处理用户操作的控制器
     22  * @作者 liuren-mail@163.com
     23  * @日期 2015年5月20日 下午3:10:19
     24  */
     25 @Controller
     26 @RequestMapping("/user")
     27 public class UserController extends BaseController {
     28     Map<String, Object> map = new HashMap<String, Object>();
     29     private final static Logger log = Logger.getLogger(UserController.class);
     30     private UserService userService;
     31 
     32     @Autowired
     33     public void setUserService(UserService userService) {
     34         this.userService = userService;
     35     }
     36 
     37     // add,edit,del页面并没有写具体逻辑,要验证是否成功,需要观察控制台输出。
     38     @RequestMapping(value = "/get_users.html")
     39     @ResponseBody
     40     public Object getUsers() {
     41         log.info("/get_users.html");
     42         PageUtil<UserDto> pageList = userService.findAllUser();
     43         return pageList;
     44     }
     45 
     46     @RequestMapping("/userList.html")
     47     public String userList() {
     48         log.info("/userList.html");
     49         return "/userList.jsp";
     50     }
     51 
     52     @RequestMapping("/add.html")
     53     @ResponseBody
     54     public Object addUser(String username, String password) {
     55         log.info("/add.html");
     56         MD5Utils MD5 = new MD5Utils();
     57         User user = new User();
     58         if (username == null || password == null || "".equals(username)
     59                 || "".equals(password)) {
     60             map.put("success", false);
     61         }
     62         String md5_password = MD5.GetMD5Code(password);
     63         user.setUsername(username);
     64         user.setPassword(md5_password);
     65         userService.saveUser(user);
     66         map.put("success", true);
     67         return map;
     68     }
     69 
     70     @RequestMapping("/edit.html")
     71     @ResponseBody
     72     public Object updateUser(int id, String username, String password) {
     73         log.info("/edit.html");
     74         MD5Utils MD5 = new MD5Utils();
     75         User user = userService.findById(id);
     76         if (user == null || "".equals(user)) {
     77             map.put("success", false);
     78             return map;
     79         }
     80         String md5_password = MD5.GetMD5Code(password);
     81         user.setUsername(username);
     82         user.setPassword(md5_password);
     83         userService.updateUser(user);
     84         map.put("success", true);
     85         System.out.println("=========================================>要修改的id为:"
     86                 + id);
     87         return map;
     88     }
     89 
     90     @ResponseBody
     91     @RequestMapping(value = "/del.html")
     92     public Object deleteUser(int id) {
     93         log.info("/del.html");
     94         userService.deleteUser(id);
     95         map.put("success", true);
     96         System.out.println("=========================================>要删除的id为:"
     97                 + id);
     98         return map;
     99     }
    100 }

    项目的dao层:

     1 package com.etop.dao;
     2 
     3 import com.etop.basic.dao.BaseDAO;
     4 import com.etop.pojo.Function;
     5 
     6 import org.springframework.stereotype.Repository;
     7 
     8 /**
     9  * @类名: FunctionDAO
    10  * @描述: TODO(这里用一句话描述这个类的作用)
    11  * @作者 liuren-mail@163.com
    12  * @日期 2015年5月20日 下午3:01:38
    13  */
    14 @SuppressWarnings("serial")
    15 @Repository("FunctionDAO")
    16 public class FunctionDAO extends BaseDAO<Function> {
    17 }
     1 package com.etop.dao;
     2 
     3 import com.etop.basic.dao.BaseDAO;
     4 import com.etop.pojo.Permission;
     5 
     6 import org.springframework.stereotype.Repository;
     7 
     8 /**
     9  * @类名: PermissionDAO 
    10  * @描述: TODO(这里用一句话描述这个类的作用) 
    11  * @作者 liuren-mail@163.com
    12  * @日期 2015年5月20日 下午3:04:50
    13  */
    14 @SuppressWarnings("serial")
    15 @Repository("PermissionDAO")
    16 public class PermissionDAO extends BaseDAO<Permission> {
    17 }
     1 package com.etop.dao;
     2 
     3 import com.etop.basic.dao.BaseDAO;
     4 import com.etop.pojo.Role;
     5 
     6 import org.springframework.stereotype.Repository;
     7 
     8 /**
     9  * @类名: RoleDAO
    10  * @描述: TODO(这里用一句话描述这个类的作用)
    11  * @作者 liuren-mail@163.com
    12  * @日期 2015年5月20日 下午3:05:28
    13  */
    14 @SuppressWarnings("serial")
    15 @Repository("RoleDAO")
    16 public class RoleDAO extends BaseDAO<Role> {
    17 }
     1 package com.etop.dao;
     2 
     3 import com.etop.basic.dao.BaseDAO;
     4 import com.etop.pojo.User;
     5 
     6 import org.springframework.stereotype.Repository;
     7 
     8 /**
     9  * @类名: UserDAO
    10  * @描述: TODO(这里用一句话描述这个类的作用)
    11  * @作者 liuren-mail@163.com
    12  * @日期 2015年5月20日 下午3:05:41
    13  */
    14 @SuppressWarnings("serial")
    15 @Repository("UserDAO")
    16 public class UserDAO extends BaseDAO<User> {
    17 }

    项目的DTO层:

     1 package com.etop.dto;
     2 
     3 public class FunctionDto {
     4 
     5     private Integer id;
     6     private String value;
     7     private Integer permission_id;
     8     private Integer role_id;
     9     private String type;
    10 
    11     public Integer getId() {
    12         return id;
    13     }
    14 
    15     public void setId(Integer id) {
    16         this.id = id;
    17     }
    18 
    19     public String getValue() {
    20         return value;
    21     }
    22 
    23     public void setValue(String value) {
    24         this.value = value;
    25     }
    26 
    27     public Integer getPermission_id() {
    28         return permission_id;
    29     }
    30 
    31     public void setPermission_id(Integer permission_id) {
    32         this.permission_id = permission_id;
    33     }
    34 
    35     public Integer getRole_id() {
    36         return role_id;
    37     }
    38 
    39     public void setRole_id(Integer role_id) {
    40         this.role_id = role_id;
    41     }
    42 
    43     public String getType() {
    44         return type;
    45     }
    46 
    47     public void setType(String type) {
    48         this.type = type;
    49     }
    50 
    51 }
     1 package com.etop.dto;
     2 
     3 public class PermissionDto {
     4 
     5     private Integer id;
     6     private String permissionname;
     7     private String role;
     8     public Integer getId() {
     9         return id;
    10     }
    11     public void setId(Integer id) {
    12         this.id = id;
    13     }
    14     public String getPermissionname() {
    15         return permissionname;
    16     }
    17     public void setPermissionname(String permissionname) {
    18         this.permissionname = permissionname;
    19     }
    20     public String getRole() {
    21         return role;
    22     }
    23     public void setRole(String role) {
    24         this.role = role;
    25     }
    26     
    27     
    28 }
     1 package com.etop.dto;
     2 
     3 public class RoleDto {
     4 
     5     private Integer id;
     6     private String rolename;
     7     private String description;
     8     private String permissionList;
     9     private String userList;
    10 
    11     public Integer getId() {
    12         return id;
    13     }
    14 
    15     public void setId(Integer id) {
    16         this.id = id;
    17     }
    18 
    19     public String getRolename() {
    20         return rolename;
    21     }
    22 
    23     public void setRolename(String rolename) {
    24         this.rolename = rolename;
    25     }
    26 
    27     public String getDescription() {
    28         return description;
    29     }
    30 
    31     public void setDescription(String description) {
    32         this.description = description;
    33     }
    34 
    35     public String getPermissionList() {
    36         return permissionList;
    37     }
    38 
    39     public void setPermissionList(String permissionList) {
    40         this.permissionList = permissionList;
    41     }
    42 
    43     public String getUserList() {
    44         return userList;
    45     }
    46 
    47     public void setUserList(String userList) {
    48         this.userList = userList;
    49     }
    50 
    51 }
     1 package com.etop.dto;
     2 
     3 public class UserDto {
     4 
     5     private Integer id;
     6     private String username;
     7     private String password;
     8     private String roleList;
     9 
    10     public Integer getId() {
    11         return id;
    12     }
    13 
    14     public void setId(Integer id) {
    15         this.id = id;
    16     }
    17 
    18     public String getUsername() {
    19         return username;
    20     }
    21 
    22     public void setUsername(String username) {
    23         this.username = username;
    24     }
    25 
    26     public String getPassword() {
    27         return password;
    28     }
    29 
    30     public void setPassword(String password) {
    31         this.password = password;
    32     }
    33 
    34     public String getRoleList() {
    35         return roleList;
    36     }
    37 
    38     public void setRoleList(String roleList) {
    39         this.roleList = roleList;
    40     }
    41 
    42 }

    项目的model层

      1 package com.etop.pojo;
      2 
      3 import javax.persistence.*;
      4 
      5 import java.io.Serializable;
      6 
      7 /**
      8  * @类名: Function
      9  * @描述: 网页过滤信息类,保存网页过滤信息,以及对应的权限(一对一)或角色(一对一)
     10  * @作者 liuren-mail@163.com
     11  * @日期 2015年5月20日 下午3:07:03
     12  */
     13 @SuppressWarnings("serial")
     14 @Entity
     15 @Table(name = "t_function")
     16 public class Function implements Serializable {
     17     /**
     18      * 这个是id
     19      */
     20     private Integer id;
     21     /**
     22      * 这个是过滤的url
     23      */
     24     private String value;
     25 //    private Permission permission;
     26 //    private Role role;
     27     private int permission_id;
     28     private int role_id;
     29     private String type;
     30 
     31     public Function() {
     32         super();
     33     }
     34 
     35 //    public Function(Integer id, String value, Permission permission, Role role,
     36 //            String type) {
     37 //        super();
     38 //        this.id = id;
     39 //        this.value = value;
     40 //        this.permission = permission;
     41 //        this.role = role;
     42 //        this.type = type;
     43 //    }
     44     public Function(Integer id, String value, int permission_id, int role_id,
     45             String type) {
     46         super();
     47         this.id = id;
     48         this.value = value;
     49         this.permission_id = permission_id;
     50         this.role_id = role_id;
     51         this.type = type;
     52     }
     53     
     54     @Id
     55     @GeneratedValue(strategy = GenerationType.IDENTITY)
     56     public Integer getId() {
     57         return id;
     58     }
     59 
     60     public void setId(Integer id) {
     61         this.id = id;
     62     }
     63 
     64     public String getValue() {
     65         return value;
     66     }
     67 
     68     public void setValue(String value) {
     69         this.value = value;
     70     }
     71 
     72 //    @OneToOne 
     73 //    @JoinColumn(name = "permission_id")
     74 //    public Permission getPermission() {
     75 //        return permission;
     76 //    }
     77 //
     78 //    public void setPermission(Permission permission) {
     79 //        this.permission = permission;
     80 //    }
     81 //
     82 //    @OneToOne
     83 //    @JoinColumn(name = "role_id")
     84 //    public Role getRole() {
     85 //        return role;
     86 //    }
     87 //
     88 //    public void setRole(Role role) {
     89 //        this.role = role;
     90 //    }
     91     public int getPermission_id() {
     92         return permission_id;
     93     }
     94 
     95     public void setPermission_id(int permission_id) {
     96         this.permission_id = permission_id;
     97     }
     98 
     99     public int getRole_id() {
    100         return role_id;
    101     }
    102 
    103     public void setRole_id(int role_id) {
    104         this.role_id = role_id;
    105     }
    106 
    107     
    108     public String getType() {
    109         return type;
    110     }
    111 
    112     public void setType(String type) {
    113         this.type = type;
    114     }
    115 }
     1 package com.etop.pojo;
     2 
     3 import java.io.Serializable;
     4 
     5 import javax.persistence.Entity;
     6 import javax.persistence.GeneratedValue;
     7 import javax.persistence.GenerationType;
     8 import javax.persistence.Id;
     9 import javax.persistence.JoinColumn;
    10 import javax.persistence.JoinTable;
    11 import javax.persistence.ManyToOne;
    12 import javax.persistence.Table;
    13 
    14 /**
    15  * @类名: Permission
    16  * @描述: 权限类,保存权限信息与对应的角色(多对一)
    17  * @作者 liuren-mail@163.com
    18  * @日期 2015年5月20日 上午11:26:31
    19  */
    20 @SuppressWarnings("serial")
    21 @Entity
    22 @Table(name = "t_permission")
    23 public class Permission implements Serializable {
    24 
    25     private Integer id;
    26     private String permissionname;
    27     private Role role;
    28     public Permission() {
    29         super();
    30     }
    31 
    32     public Permission(Integer id, String permissionname, Role role) {
    33         super();
    34         this.id = id;
    35         this.permissionname = permissionname;
    36         this.role = role;
    37     }
    38 
    39     @Id
    40     @GeneratedValue(strategy = GenerationType.IDENTITY)
    41     public Integer getId() {
    42         return id;
    43     }
    44 
    45     public void setId(Integer id) {
    46         this.id = id;
    47     }
    48 
    49     public String getPermissionname() {
    50         return permissionname;
    51     }
    52 
    53     public void setPermissionname(String permissionname) {
    54         this.permissionname = permissionname;
    55     }
    56 
    57     @ManyToOne(targetEntity = Role.class)
    58     @JoinTable(name = "t_role_permission", joinColumns = { @JoinColumn(name = "permission_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
    59     public Role getRole() {
    60         return role;
    61     }
    62 
    63     public void setRole(Role role) {
    64         this.role = role;
    65     }
    66 }
      1 package com.etop.pojo;
      2 
      3 import javax.persistence.*;
      4 
      5 import org.codehaus.jackson.annotate.JsonIgnore;
      6 
      7 import java.io.Serializable;
      8 import java.util.HashSet;
      9 import java.util.Set;
     10 
     11 /**
     12  * @类名: Role
     13  * @描述: 角色类,用于保存角色信息、用户列表(多对多)与角色(一对多)对应的权限
     14  * @作者 liuren-mail@163.com
     15  * @日期 2015年5月20日 下午3:07:42
     16  */
     17 @SuppressWarnings("serial")
     18 @Entity
     19 @Table(name = "t_role")
     20 public class Role implements Serializable {
     21 
     22     private Integer id;
     23     private String rolename;
     24     private String description;
     25     private Set<Permission> permissionList;
     26     private Set<User> userList;
     27 
     28     public Role() {
     29         super();
     30     }
     31 
     32     public Role(Integer id, String rolename, Set<Permission> permissionList,
     33             Set<User> userList) {
     34         super();
     35         this.id = id;
     36         this.rolename = rolename;
     37         this.permissionList = permissionList;
     38         this.userList = userList;
     39     }
     40 
     41     @Id
     42     @GeneratedValue(strategy = GenerationType.IDENTITY)
     43     public Integer getId() {
     44         return id;
     45     }
     46 
     47     public void setId(Integer id) {
     48         this.id = id;
     49     }
     50 
     51     public String getRolename() {
     52         return rolename;
     53     }
     54 
     55     public void setRolename(String rolename) {
     56         this.rolename = rolename;
     57     }
     58 
     59     public String getDescription() {
     60         return description;
     61     }
     62 
     63     public void setDescription(String description) {
     64         this.description = description;
     65     }
     66 
     67     @OneToMany(targetEntity = Permission.class, cascade = {
     68             CascadeType.PERSIST, CascadeType.MERGE })
     69     @JsonIgnore
     70     // 防止无限循环
     71     @JoinTable(name = "t_role_permission", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "permission_id") })
     72     public Set<Permission> getPermissionList() {
     73         return permissionList;
     74     }
     75 
     76     public void setPermissionList(Set<Permission> permissionList) {
     77         this.permissionList = permissionList;
     78     }
     79 
     80     @ManyToMany(targetEntity = com.etop.pojo.User.class, cascade = {
     81             CascadeType.PERSIST, CascadeType.MERGE })
     82     @JsonIgnore
     83     // 防止无限循环
     84     @JoinTable(name = "t_user_role", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "user_id") })
     85     public Set<User> getUserList() {
     86         return userList;
     87     }
     88 
     89     public void setUserList(Set<User> userList) {
     90         this.userList = userList;
     91     }
     92 
     93     @Transient
     94     public Set<String> getPermissionsName() {
     95         Set<String> list = new HashSet<>();
     96         Set<Permission> perlist = getPermissionList();
     97         for (Permission per : perlist) {
     98             list.add(per.getPermissionname());
     99         }
    100         return list;
    101     }
    102 
    103     private class User {
    104     }
    105     
    106 }
     1 package com.etop.pojo;
     2 
     3 import org.codehaus.jackson.annotate.JsonIgnore;
     4 import org.hibernate.validator.constraints.NotEmpty;
     5 
     6 import javax.persistence.*;
     7 
     8 import java.io.Serializable;
     9 import java.util.HashSet;
    10 import java.util.Set;
    11 
    12 /**
    13  * @类名: User
    14  * @描述: 用户类,保存用户信息与角色(多对多)
    15  * @作者 liuren-mail@163.com
    16  * @日期 2015年5月20日 下午3:08:11
    17  */
    18 @SuppressWarnings("serial")
    19 @Entity
    20 @Table(name = "t_user")
    21 public class User implements Serializable {
    22 
    23     private Integer id;
    24     @NotEmpty(message = "用户名不能为空")
    25     private String username;
    26     @NotEmpty(message = "密码不能为空")
    27     private String password;
    28     private Set<Role> roleList;
    29 
    30     @Id
    31     @GeneratedValue(strategy = GenerationType.IDENTITY)
    32     public Integer getId() {
    33         return id;
    34     }
    35 
    36     public void setId(Integer id) {
    37         this.id = id;
    38     }
    39 
    40     public String getUsername() {
    41         return username;
    42     }
    43 
    44     public void setUsername(String username) {
    45         this.username = username;
    46     }
    47 
    48     public String getPassword() {
    49         return password;
    50     }
    51 
    52     public void setPassword(String password) {
    53         this.password = password;
    54     }
    55 
    56     @ManyToMany(fetch = FetchType.EAGER)
    57     @JsonIgnore
    58     // 防止无限循环
    59     @JoinTable(name = "t_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
    60     public Set<Role> getRoleList() {
    61         return roleList;
    62     }
    63 
    64     public void setRoleList(Set<Role> roleList) {
    65         this.roleList = roleList;
    66     }
    67 
    68     @Transient
    69     public Set<String> getRolesName() {
    70         Set<Role> roles = getRoleList();
    71         Set<String> set = new HashSet<String>();
    72         for (Role role : roles) {
    73             set.add(role.getRolename());
    74         }
    75         return set;
    76     }
    77 
    78     public User() {
    79         super();
    80     }
    81 
    82     public User(Integer id, String username, String password, Set<Role> roleList) {
    83         super();
    84         this.id = id;
    85         this.username = username;
    86         this.password = password;
    87         this.roleList = roleList;
    88     }
    89 }

    项目的service层:

     1 package com.etop.service;
     2 
     3 import com.etop.dao.FunctionDAO;
     4 import com.etop.dto.FunctionDto;
     5 import com.etop.pojo.Function;
     6 import com.etop.utils.PageUtil;
     7 
     8 import org.springframework.beans.factory.annotation.Autowired;
     9 import org.springframework.stereotype.Service;
    10 import org.springframework.transaction.annotation.Transactional;
    11 
    12 import java.io.Serializable;
    13 import java.util.HashMap;
    14 import java.util.List;
    15 import java.util.Map;
    16 
    17 /**
    18  * @类名: FunctionService
    19  * @描述: 网页过滤服务,与dao进行对接
    20  * @作者 liuren-mail@163.com
    21  * @日期 2015年5月20日 上午11:46:22
    22  */
    23 @SuppressWarnings("serial")
    24 @Service("FunctionService")
    25 public class FunctionService implements Serializable {
    26 
    27     @Autowired
    28     private FunctionDAO functionDAO;
    29 
    30     /**
    31      * 查找所有权限过滤信息
    32      * 
    33      * @return
    34      */
    35     public List<Function> findAll() {
    36         return functionDAO.find("from Function f");
    37     }
    38 
    39     @Transactional
    40     public PageUtil<FunctionDto> findAllFunction() {
    41         return functionDAO.findBySql("select * from t_function",
    42                 FunctionDto.class, false);
    43     }
    44 
    45     public void saveFunction(Function function) {
    46         functionDAO.save(function);
    47     }
    48 
    49     public Function findFunctionById(int id) {
    50         Map<String,Object> params = new HashMap<String,Object>();
    51         params.put("id", id);
    52         return functionDAO.findUniqueResult("from Function f where f.id= :id", params);
    53     }
    54 
    55     public void updateFunction(Function function) {
    56         functionDAO.saveOrUpdate(function);
    57     }
    58 
    59     public void deleteFunction(int id) {
    60         functionDAO.deleteById(id);
    61     }
    62 }
     1 package com.etop.service;
     2 
     3 import java.io.Serializable;
     4 import java.util.HashMap;
     5 import java.util.List;
     6 import java.util.Map;
     7 
     8 import org.springframework.beans.factory.annotation.Autowired;
     9 import org.springframework.stereotype.Service;
    10 import org.springframework.transaction.annotation.Transactional;
    11 
    12 import com.etop.dao.PermissionDAO;
    13 import com.etop.dto.PermissionDto;
    14 import com.etop.pojo.Permission;
    15 import com.etop.utils.PageUtil;
    16 
    17 /**
    18  * @类名: PermissionService
    19  * @描述: 权限服务和DAO对接
    20  * @作者 liuren-mail@163.com
    21  * @日期 2015年5月27日 下午3:58:27
    22  */
    23 @SuppressWarnings("serial")
    24 @Service
    25 public class PermissionService implements Serializable {
    26 
    27     @Autowired
    28     private PermissionDAO permissionDAO;
    29 
    30     public List<Permission> findAll(){
    31         return permissionDAO.find("from Permission p");
    32     }
    33     @Transactional
    34     public PageUtil<PermissionDto> findAllPermisson() {
    35         return permissionDAO.findBySql("select * from t_permission",
    36                 PermissionDto.class, false);
    37     }
    38     
    39     public void savePermission(Permission permission) {
    40         permissionDAO.save(permission);
    41     }
    42 
    43     public Permission findPermissionById(int id) {
    44         Map<String,Object> params = new HashMap<String,Object>();
    45         params.put("id", id);
    46         return permissionDAO.findUniqueResult("from Permission p where p.id= :id", params);
    47     }
    48 
    49     public void updatePermission(Permission permission) {
    50         permissionDAO.saveOrUpdate(permission);
    51     }
    52 
    53     public void deletePermission(int id) {
    54         permissionDAO.deleteById(id);
    55     }
    56     public String getNameById(int permission_id) {
    57         Map<String,Object> params = new HashMap<String,Object>();
    58         params.put("id", permission_id);
    59         Permission permission = permissionDAO.findUniqueResult("from Permission p where p.id= :id", params);
    60         String name =permission.getPermissionname();
    61         return name;
    62     }
    63 
    64 }
     1 package com.etop.service;
     2 
     3 import java.io.Serializable;
     4 import java.util.HashMap;
     5 import java.util.List;
     6 import java.util.Map;
     7 
     8 import org.springframework.beans.factory.annotation.Autowired;
     9 import org.springframework.stereotype.Service;
    10 import org.springframework.transaction.annotation.Transactional;
    11 
    12 import com.etop.dao.RoleDAO;
    13 import com.etop.dto.RoleDto;
    14 import com.etop.pojo.Role;
    15 import com.etop.utils.PageUtil;
    16 /**
    17  * @类名: RoleService 
    18  * @描述: 角色服务和DAO对接
    19  * @作者 liuren-mail@163.com
    20  * @日期 2015年5月26日 下午5:20:03
    21  */
    22 @SuppressWarnings("serial")
    23 @Service
    24 public class RoleService implements Serializable{
    25     
    26     @Autowired
    27     private RoleDAO roleDAO;
    28     
    29     @Transactional
    30     public List<Role> getAllRole() {
    31         return roleDAO.find("from Role r");
    32     }
    33     
    34     @Transactional
    35     public PageUtil<RoleDto> findAllRole() {
    36         return roleDAO.findBySql("select * from t_role", RoleDto.class, false);
    37     }
    38 
    39     public Role findById(int id) {
    40         Map<String,Object> params = new HashMap<String,Object>();
    41         params.put("id", id);
    42         return roleDAO.findUniqueResult("from Role r where r.id= :id", params);
    43     }
    44 
    45     public void updateRole(Role role) {
    46         roleDAO.saveOrUpdate(role);
    47     }
    48 
    49     public void saveRole(Role role) {
    50         roleDAO.save(role);
    51     }
    52 
    53     public void deleteRole(int id) {
    54         roleDAO.deleteById(id);
    55     }
    56 
    57     public String getNameById(int role_id) {
    58         Map<String,Object> params = new HashMap<String,Object>();
    59         params.put("id", role_id);
    60         Role role =roleDAO.findUniqueResult("from Role r where r.id= :id", params);
    61         String rolename = role.getRolename();
    62         return rolename;
    63     }
    64 }
     1 package com.etop.service;
     2 
     3 import com.etop.dao.UserDAO;
     4 import com.etop.dto.UserDto;
     5 import com.etop.pojo.User;
     6 import com.etop.utils.PageUtil;
     7 
     8 import org.springframework.beans.factory.annotation.Autowired;
     9 import org.springframework.stereotype.Service;
    10 
    11 import java.io.Serializable;
    12 import java.util.HashMap;
    13 import java.util.List;
    14 import java.util.Map;
    15 
    16 /**
    17  * @类名: UserService
    18  * @描述: 用户服务,与dao进行对接
    19  * @作者 liuren-mail@163.com
    20  * @日期 2015年5月20日 下午3:03:20
    21  */
    22 @SuppressWarnings("serial")
    23 @Service("UserService")
    24 public class UserService implements Serializable {
    25 
    26     @Autowired
    27     private UserDAO userDAO;
    28 
    29     /**
    30      * 通过用户名查找用户信息
    31      * 
    32      * @param username
    33      * @return
    34      */
    35     public User findByName(String username) {
    36         Map<String, Object> params = new HashMap<>();
    37         params.put("name", username);
    38         return userDAO.findUniqueResult("from User u where u.username = :name",
    39                 params);
    40     }
    41 
    42     public List<User> getAllUser() {
    43         return userDAO.find("from User u");
    44     }
    45 
    46     public PageUtil<UserDto> findAllUser() {
    47         return userDAO.findBySql("select * from t_user", UserDto.class, false);
    48     }
    49 
    50     public void saveUser(User user) {
    51         userDAO.save(user);
    52     }
    53 
    54     public User findById(int id) {
    55         Map<String, Object> params = new HashMap<String, Object>();
    56         params.put("id", id);
    57         return userDAO.findUniqueResult("from User u where u.id = :id", params);
    58     }
    59 
    60     public void updateUser(User user) {
    61         userDAO.saveOrUpdate(user);
    62     }
    63 
    64     public void deleteUser(int id) {
    65         userDAO.deleteById(id);
    66     }
    67 }

    项目的shiro层代码:

     1 package com.etop.shiro;
     2 
     3 import com.etop.pojo.Function;
     4 import com.etop.service.FunctionService;
     5 import com.etop.service.PermissionService;
     6 import com.etop.service.RoleService;
     7 
     8 import org.apache.commons.lang.StringUtils;
     9 import org.apache.shiro.config.Ini;
    10 import org.springframework.beans.factory.FactoryBean;
    11 import org.springframework.beans.factory.annotation.Autowired;
    12 
    13 import java.util.Iterator;
    14 import java.util.List;
    15 
    16 /**
    17  * @类名: ChainDefinitionSectionMetaSource
    18  * @描述: 产生责任链,确定每个url的访问权限
    19  * @作者 liuren-mail@163.com
    20  * @日期 2015年5月20日 下午3:12:53
    21  */
    22 public class ChainDefinitionSectionMetaSource implements
    23         FactoryBean<Ini.Section> {
    24 
    25     @Autowired
    26     private FunctionService functionService;
    27     @Autowired
    28     private RoleService roleService;
    29     @Autowired
    30     private PermissionService permissionService;
    31     // 静态资源访问权限
    32     private String filterChainDefinitions = "/static/**=anon";
    33 
    34     @Override
    35     public Ini.Section getObject() throws Exception {
    36         List<Function> list = functionService.findAll();
    37         Ini ini = new Ini();
    38         // 加载默认的url
    39         ini.load(filterChainDefinitions);
    40         Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
    41         // 循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
    42         // 里面的键就是链接URL,值就是存在什么条件才能访问该链接
    43         for (Iterator<Function> it = list.iterator(); it.hasNext();) {
    44             Function function = it.next();
    45             int permission_id = function.getPermission_id();
    46             int role_id = function.getRole_id();
    47             // 构成permission字符串
    48             if (StringUtils.isNotEmpty(function.getValue())
    49                     && StringUtils.isNotEmpty(function.getType())) {
    50                 String permission = "";
    51                 switch (function.getType()) {
    52                 case "anon":
    53                     permission = "anon";
    54                     break;
    55                 case "perms":
    56                     permission = "perms["
    57                             + permissionService.getNameById(permission_id)//function.getPermission().getPermissionname()
    58                             + "]";
    59                     break;
    60                 case "roles":
    61                     permission = "roles[" 
    62                             + roleService.getNameById(role_id)//function.getRole().getRolename()
    63                             + "]";
    64                     break;
    65                 default:
    66                     break;
    67                 }
    68                 section.put(function.getValue(), permission);
    69             }
    70 
    71         }
    72         // 所有资源的访问权限,必须放在最后
    73         section.put("/**", "authc");
    74         return section;
    75     }
    76 
    77     @Override
    78     public Class<?> getObjectType() {
    79         return this.getClass();
    80     }
    81 
    82     @Override
    83     public boolean isSingleton() {
    84         return false;
    85     }
    86 }
     1 package com.etop.shiro;
     2 
     3 import java.util.Collection;
     4 
     5 import javax.inject.Inject;
     6 
     7 import org.apache.shiro.authc.AuthenticationException;
     8 import org.apache.shiro.authc.AuthenticationInfo;
     9 import org.apache.shiro.authc.AuthenticationToken;
    10 import org.apache.shiro.authc.SimpleAuthenticationInfo;
    11 import org.apache.shiro.authc.UsernamePasswordToken;
    12 import org.apache.shiro.authz.AuthorizationInfo;
    13 import org.apache.shiro.authz.SimpleAuthorizationInfo;
    14 import org.apache.shiro.realm.AuthorizingRealm;
    15 import org.apache.shiro.subject.PrincipalCollection;
    16 import org.springframework.stereotype.Service;
    17 import org.springframework.transaction.annotation.Transactional;
    18 
    19 import com.etop.pojo.Role;
    20 import com.etop.pojo.User;
    21 import com.etop.service.UserService;
    22 
    23 /**
    24  * @类名: MyRealm
    25  * @描述: 自定义Realm,进行数据源配置
    26  * @作者 liuren-mail@163.com
    27  * @日期 2015年5月20日 上午11:50:21
    28  */
    29 
    30 @Service
    31 @Transactional
    32 public class MyRealm extends AuthorizingRealm {
    33 
    34     @Inject
    35     private UserService userService;
    36 
    37     /**
    38      * 获取授权信息
    39      */
    40     @Override
    41     protected AuthorizationInfo doGetAuthorizationInfo(
    42             PrincipalCollection principalCollection) {
    43         // 获取登录时输入的用户名
    44         String loginName = (String) principalCollection.fromRealm(getName())
    45                 .iterator().next();
    46         // 到数据库获取此用户
    47         User user = userService.findByName(loginName);
    48         if (user != null) {
    49             // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
    50             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    51             // 用户的角色集合
    52             info.setRoles(user.getRolesName());
    53             // 用户的角色对应的所有权限,如果只使用角色定义访问权限
    54             Collection<Role> roleList = user.getRoleList();
    55             for (Role role : roleList) {
    56                 info.addStringPermissions(role.getPermissionsName());
    57             }
    58             return info;
    59         }
    60         return null;
    61     }
    62 
    63     /**
    64      * 获取身份验证相关信息
    65      */
    66     @Override
    67     protected AuthenticationInfo doGetAuthenticationInfo(
    68             AuthenticationToken authenticationToken)
    69             throws AuthenticationException {
    70         // UsernamePasswordToken对象用来存放提交的登录信息
    71         UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    72         // 查出是否有此用户
    73         User user = userService.findByName(token.getUsername());
    74         if (user != null) {
    75             // 若存在,将此用户存放到登录认证info中
    76             return new SimpleAuthenticationInfo(user.getUsername(),
    77                     user.getPassword(), getName());
    78         }
    79         return null;
    80     }
    81 
    82 }

    项目的工具类:

      1 package com.etop.utils;
      2 
      3 import org.apache.commons.lang.time.DateFormatUtils;
      4 
      5 import java.sql.Timestamp;
      6 import java.text.ParseException;
      7 import java.text.SimpleDateFormat;
      8 import java.util.Calendar;
      9 import java.util.Date;
     10 
     11 /**
     12  * @类名: DateUtils
     13  * @描述: 比较两个日期相差的月份数
     14  * @作者 liuren-mail@163.com
     15  * @日期 2015年5月20日 下午2:47:06
     16  */
     17 public class DateUtils extends org.apache.commons.lang.time.DateUtils {
     18 
     19     public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     20     private static String[] parsePatterns = { "yyyy-MM-dd",
     21             "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
     22             "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };
     23 
     24     /**
     25      * 得到当前日期字符串 格式(yyyy-MM-dd)
     26      */
     27     public static String getDate() {
     28         return getDate("yyyy-MM-dd");
     29     }
     30 
     31     /**
     32      * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
     33      */
     34     public static String getDate(String pattern) {
     35         return DateFormatUtils.format(new Date(), pattern);
     36     }
     37 
     38     /**
     39      * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
     40      */
     41     public static String formatDate(Date date, Object... pattern) {
     42         String formatDate = null;
     43         if (pattern != null && pattern.length > 0) {
     44             formatDate = DateFormatUtils.format(date, pattern[0].toString());
     45         } else {
     46             formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
     47         }
     48         return formatDate;
     49     }
     50 
     51     /**
     52      * 得到当前时间字符串 格式(HH:mm:ss)
     53      */
     54     public static String getTime() {
     55         return formatDate(new Date(), "HH:mm:ss");
     56     }
     57 
     58     /**
     59      * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
     60      */
     61     public static String getDateTime() {
     62         return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
     63     }
     64 
     65     /**
     66      * 得到当前年份字符串 格式(yyyy)
     67      */
     68     public static String getYear() {
     69         return formatDate(new Date(), "yyyy");
     70     }
     71 
     72     /**
     73      * 得到当前月份字符串 格式(MM)
     74      */
     75     public static String getMonth() {
     76         return formatDate(new Date(), "MM");
     77     }
     78 
     79     /**
     80      * 得到当天字符串 格式(dd)
     81      */
     82     public static String getDay() {
     83         return formatDate(new Date(), "dd");
     84     }
     85 
     86     /**
     87      * 得到当前星期字符串 格式(E)星期几
     88      */
     89     public static String getWeek() {
     90         return formatDate(new Date(), "E");
     91     }
     92 
     93     /**
     94      * 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
     95      * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
     96      */
     97     public static Date parseDate(Object str) {
     98         if (str == null) {
     99             return null;
    100         }
    101         try {
    102             return parseDate(str.toString(), parsePatterns);
    103         } catch (ParseException e) {
    104             return null;
    105         }
    106     }
    107 
    108     /**
    109      * 获取过去的天数
    110      * 
    111      * @param date
    112      * @return
    113      */
    114     public static long pastDays(Date date) {
    115         long t = new Date().getTime() - date.getTime();
    116         return t / (24 * 60 * 60 * 1000);
    117     }
    118 
    119     public static int getMonthSpace(Timestamp source, Timestamp target) {
    120         int result = 0;
    121 
    122         Calendar c1 = Calendar.getInstance();
    123         Calendar c2 = Calendar.getInstance();
    124 
    125         c1.setTime(new Date(source.getTime()));
    126         c2.setTime(new Date(target.getTime()));
    127 
    128         result = c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH);
    129 
    130         return result == 0 ? 0 : result;
    131     }
    132 
    133     public static Timestamp addDay(Timestamp source, int amount) {
    134         Calendar c = Calendar.getInstance();
    135         c.setTimeInMillis(source.getTime());
    136         c.add(Calendar.DAY_OF_MONTH, amount);
    137         return new Timestamp(c.getTimeInMillis());
    138     }
    139 }
     1 package com.etop.utils;
     2 
     3 import net.sf.json.JSONObject;
     4 
     5 public class JsonTools {
     6     /**
     7      * 得到一个json类型的字符串对象
     8      * 
     9      * @param key
    10      * @param value
    11      * @return
    12      */
    13     public static String getJsonString(String key, Object value) {
    14         JSONObject jsonObject = new JSONObject();
    15         // put和element都是往JSONObject对象中放入 key/value 对
    16         // jsonObject.put(key, value);
    17         jsonObject.element(key, value);
    18         return jsonObject.toString();
    19     }
    20 
    21     /**
    22      * 得到一个json对象
    23      * 
    24      * @param key
    25      * @param value
    26      * @return
    27      */
    28     public static JSONObject getJsonObject(String key, Object value) {
    29         JSONObject jsonObject = new JSONObject();
    30         jsonObject.put(key, value);
    31         return jsonObject;
    32     }
    33 
    34 }
    package com.etop.utils;
    
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    /**
     * @类名: MD5Utils 
     * @描述: 32位的md5加密方法
     * @作者 liuren-mail@163.com
     * @日期 2015年5月30日 上午10:29:57
     */
    public class MD5Utils {
        // 全局数组
        private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    
        public MD5Utils() {
        }
    
        // 返回形式为数字跟字符串
        private static String byteToArrayString(byte bByte) {
            int iRet = bByte;
            // System.out.println("iRet="+iRet);
            if (iRet < 0) {
                iRet += 256;
            }
            int iD1 = iRet / 16;
            int iD2 = iRet % 16;
            return strDigits[iD1] + strDigits[iD2];
        }
    
        // 返回形式只为数字
        @SuppressWarnings("unused")
        private static String byteToNum(byte bByte) {
            int iRet = bByte;
            System.out.println("iRet1=" + iRet);
            if (iRet < 0) {
                iRet += 256;
            }
            return String.valueOf(iRet);
        }
    
        // 转换字节数组为16进制字串
        private static String byteToString(byte[] bByte) {
            StringBuffer sBuffer = new StringBuffer();
            for (int i = 0; i < bByte.length; i++) {
                sBuffer.append(byteToArrayString(bByte[i]));
            }
            return sBuffer.toString();
        }
    
        public String GetMD5Code(String strObj) {
            String resultString = null;
            try {
                resultString = new String(strObj);
                MessageDigest md = MessageDigest.getInstance("MD5");
                // md.digest() 该函数返回值为存放哈希值结果的byte数组
                resultString = byteToString(md.digest(strObj.getBytes()));
            } catch (NoSuchAlgorithmException ex) {
                ex.printStackTrace();
            }
            return resultString;
        }
    
        public static void main(String[] args) {
            MD5Utils getMD5 = new MD5Utils();
            System.out.println(getMD5.GetMD5Code("000000"));
        }
    }
     1 package com.etop.utils;
     2 
     3 import java.util.List;
     4 
     5 public class PageUtil<T> {
     6 
     7     // /**
     8     // * 分页的大小
     9     // */
    10     // private int size;//page*limit
    11     // /**
    12     // * 分页的起始页
    13     // */
    14     // private int offset;//start
    15     // /**
    16     // * 总记录数
    17     // */
    18     private long total;
    19     /**
    20      * 分页的数据
    21      */
    22     private List<T> rows;
    23 
    24     // public int getSize() {
    25     // return size;
    26     // }
    27     // public void setSize(int size) {
    28     // this.size = size;
    29     // }
    30     // public int getOffset() {
    31     // return offset;
    32     // }
    33     // public void setOffset(int offset) {
    34     // this.offset = offset;
    35     // }
    36     public long getTotal() {
    37         return total;
    38     }
    39 
    40     public void setTotal(long total) {
    41         this.total = total;
    42     }
    43 
    44     public List<T> getRows() {
    45         return rows;
    46     }
    47 
    48     public void setRows(List<T> rows) {
    49         this.rows = rows;
    50     }
    51 
    52 }
     1 package com.etop.utils;
     2 
     3 import org.apache.commons.lang.Validate;
     4 import org.apache.log4j.Logger;
     5 import org.springframework.beans.factory.DisposableBean;
     6 import org.springframework.context.ApplicationContext;
     7 import org.springframework.context.ApplicationContextAware;
     8 
     9 /**
    10  * @类名: SpringContextHolder
    11  * @描述: 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
    12  * @作者 liuren-mail@163.com
    13  * @日期 2015年5月20日 上午11:49:42
    14  */
    15 public class SpringContextHolder implements ApplicationContextAware,
    16         DisposableBean {
    17 
    18     private static ApplicationContext applicationContext = null;
    19     private static Logger logger = Logger.getLogger(SpringContextHolder.class);
    20 
    21     /**
    22      * 取得存储在静态变量中的ApplicationContext.
    23      */
    24     public static ApplicationContext getApplicationContext() {
    25         assertContextInjected();
    26         return applicationContext;
    27     }
    28 
    29     /**
    30      * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
    31      */
    32     @SuppressWarnings("unchecked")
    33     public static <T> T getBean(String name) {
    34         assertContextInjected();
    35         return (T) applicationContext.getBean(name);
    36     }
    37 
    38     /**
    39      * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
    40      */
    41     public static <T> T getBean(Class<T> requiredType) {
    42         assertContextInjected();
    43         return applicationContext.getBean(requiredType);
    44     }
    45 
    46     /**
    47      * 清除SpringContextHolder中的ApplicationContext为Null.
    48      */
    49     public static void clearHolder() {
    50         logger.debug("清除SpringContextHolder中的ApplicationContext:"
    51                 + applicationContext);
    52         applicationContext = null;
    53     }
    54 
    55     /**
    56      * 实现ApplicationContextAware接口, 注入Context到静态变量中.
    57      */
    58     @Override
    59     public void setApplicationContext(ApplicationContext applicationContext) {
    60         if (SpringContextHolder.applicationContext != null) {
    61             logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
    62                     + SpringContextHolder.applicationContext);
    63         }
    64         SpringContextHolder.applicationContext = applicationContext; // NOSONAR
    65     }
    66 
    67     /**
    68      * 实现DisposableBean接口, 在Context关闭时清理静态变量.
    69      */
    70     @Override
    71     public void destroy() throws Exception {
    72         SpringContextHolder.clearHolder();
    73     }
    74 
    75     /**
    76      * 检查ApplicationContext不为空.
    77      */
    78     private static void assertContextInjected() {
    79         Validate.isTrue(applicationContext != null,
    80                 "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    81     }
    82 }
     1 package com.etop.utils;
     2 /**
     3  * 用来传递列表对象的ThreadLocal数据
     4  * @author Administrator
     5  *
     6  */
     7 public class ThreadLocalUtils {
     8     /**
     9      * 分页大小
    10      */
    11     private static ThreadLocal<Integer> pageSize = new ThreadLocal<Integer>();
    12     /**
    13      * 分页的起始页
    14      */
    15     private static ThreadLocal<Integer> pageOffset = new ThreadLocal<Integer>();
    16     /**
    17      * 列表的排序字段
    18      */
    19     private static ThreadLocal<String> sort = new ThreadLocal<String>();
    20     /**
    21      * 列表的排序方式
    22      */
    23     private static ThreadLocal<String> order = new ThreadLocal<String>();
    24     
    25     private static ThreadLocal<String> realPath = new ThreadLocal<String>();
    26 /*    
    27     private static ThreadLocal<String> query = new ThreadLocal<String>();
    28     
    29     public static String getQuery() {
    30         return query.get();
    31     }
    32     public static void setQuery(String _query) {
    33         SystemContext.query.set(_query);
    34     }*/
    35     public static String getRealPath() {
    36         return realPath.get();
    37     }
    38     public static void setRealPath(String _realPath) {
    39         ThreadLocalUtils.realPath.set(_realPath);
    40     }
    41     public static Integer getPageSize() {
    42         return pageSize.get();
    43     }
    44     public static void setPageSize(Integer _pageSize) {
    45         pageSize.set(_pageSize);
    46     }
    47     public static Integer getPageOffset() {
    48         return pageOffset.get();
    49     }
    50     public static void setPageOffset(Integer _pageOffset) {
    51         pageOffset.set(_pageOffset);
    52     }
    53     public static String getSort() {
    54         return sort.get();
    55     }
    56     public static void setSort(String _sort) {
    57         ThreadLocalUtils.sort.set(_sort);
    58     }
    59     public static String getOrder() {
    60         return order.get();
    61     }
    62     public static void setOrder(String _order) {
    63         ThreadLocalUtils.order.set(_order);
    64     }
    65     
    66     public static void removePageSize() {
    67         pageSize.remove();
    68     }
    69     
    70     public static void removePageOffset() {
    71         pageOffset.remove();
    72     }
    73     
    74     public static void removeSort() {
    75         sort.remove();
    76     }
    77     
    78     public static void removeOrder() {
    79         order.remove();
    80     }
    81     
    82     public static void removeRealPath() {
    83         realPath.remove();
    84     }
    85     
    86     /*public static void removeQuery(){
    87         query.remove();
    88     }*/
    89 }
      1 package com.etop.utils;
      2 
      3 import java.io.*;
      4 import java.text.SimpleDateFormat;
      5 import java.util.*;
      6 
      7 import org.apache.commons.fileupload.*;
      8 import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
      9 import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
     10 import org.apache.commons.fileupload.util.*;
     11 import org.apache.commons.fileupload.servlet.*;
     12 import org.apache.commons.fileupload.FileItemIterator;
     13 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     14 
     15 import sun.misc.BASE64Decoder;
     16 
     17 import javax.servlet.http.HttpServletRequest;
     18 
     19 /**
     20  * UEditor文件上传辅助类
     21  * 
     22  */
     23 @SuppressWarnings("restriction")
     24 public class Uploader {
     25     // 输出文件地址
     26     private String url = "";
     27     // 上传文件名
     28     private String fileName = "";
     29     // 状态
     30     private String state = "";
     31     // 文件类型
     32     private String type = "";
     33     // 原始文件名
     34     private String originalName = "";
     35     // 文件大小
     36     private String size = "";
     37 
     38     private HttpServletRequest request = null;
     39     private String title = "";
     40 
     41     // 保存路径
     42     private String savePath = "upload";
     43     // 文件允许格式
     44     private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",
     45             ".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
     46     // 文件大小限制,单位KB
     47     private int maxSize = 10000;
     48 
     49     private HashMap<String, String> errorInfo = new HashMap<String, String>();
     50 
     51     public Uploader(HttpServletRequest request) {
     52         this.request = request;
     53         HashMap<String, String> tmp = this.errorInfo;
     54         tmp.put("SUCCESS", "SUCCESS"); // 默认成功
     55         tmp.put("NOFILE", "未包含文件上传域");
     56         tmp.put("TYPE", "不允许的文件格式");
     57         tmp.put("SIZE", "文件大小超出限制");
     58         tmp.put("ENTYPE", "请求类型ENTYPE错误");
     59         tmp.put("REQUEST", "上传请求异常");
     60         tmp.put("IO", "IO异常");
     61         tmp.put("DIR", "目录创建失败");
     62         tmp.put("UNKNOWN", "未知错误");
     63 
     64     }
     65 
     66     public void upload() throws Exception {
     67         boolean isMultipart = ServletFileUpload
     68                 .isMultipartContent(this.request);
     69         if (!isMultipart) {
     70             this.state = this.errorInfo.get("NOFILE");
     71             return;
     72         }
     73         DiskFileItemFactory dff = new DiskFileItemFactory();
     74         String savePath = this.getFolder(this.savePath);
     75         dff.setRepository(new File(savePath));
     76         try {
     77             ServletFileUpload sfu = new ServletFileUpload(dff);
     78             sfu.setSizeMax(this.maxSize * 1024);
     79             sfu.setHeaderEncoding("utf-8");
     80             FileItemIterator fii = sfu.getItemIterator(this.request);
     81             while (fii.hasNext()) {
     82                 FileItemStream fis = fii.next();
     83                 if (!fis.isFormField()) {
     84                     this.originalName = fis.getName().substring(
     85                             fis.getName().lastIndexOf(
     86                                     System.getProperty("file.separator")) + 1);
     87                     if (!this.checkFileType(this.originalName)) {
     88                         this.state = this.errorInfo.get("TYPE");
     89                         continue;
     90                     }
     91                     this.fileName = this.getName(this.originalName);
     92                     this.type = this.getFileExt(this.fileName);
     93                     this.url = savePath + "/" + this.fileName;
     94                     BufferedInputStream in = new BufferedInputStream(
     95                             fis.openStream());
     96                     FileOutputStream out = new FileOutputStream(new File(
     97                             this.getPhysicalPath(this.url)));
     98                     BufferedOutputStream output = new BufferedOutputStream(out);
     99                     Streams.copy(in, output, true);
    100                     this.state = this.errorInfo.get("SUCCESS");
    101                     // UE中只会处理单张上传,完成后即退出
    102                     break;
    103                 } else {
    104                     String fname = fis.getFieldName();
    105                     // 只处理title,其余表单请自行处理
    106                     if (!fname.equals("pictitle")) {
    107                         continue;
    108                     }
    109                     BufferedInputStream in = new BufferedInputStream(
    110                             fis.openStream());
    111                     BufferedReader reader = new BufferedReader(
    112                             new InputStreamReader(in));
    113                     StringBuffer result = new StringBuffer();
    114                     while (reader.ready()) {
    115                         result.append((char) reader.read());
    116                     }
    117                     this.title = new String(result.toString().getBytes(),
    118                             "utf-8");
    119                     reader.close();
    120 
    121                 }
    122             }
    123         } catch (SizeLimitExceededException e) {
    124             this.state = this.errorInfo.get("SIZE");
    125         } catch (InvalidContentTypeException e) {
    126             this.state = this.errorInfo.get("ENTYPE");
    127         } catch (FileUploadException e) {
    128             this.state = this.errorInfo.get("REQUEST");
    129         } catch (Exception e) {
    130             this.state = this.errorInfo.get("UNKNOWN");
    131         }
    132     }
    133 
    134     /**
    135      * 接受并保存以base64格式上传的文件
    136      * 
    137      * @param fieldName
    138      */
    139     public void uploadBase64(String fieldName) {
    140         String savePath = this.getFolder(this.savePath);
    141         String base64Data = this.request.getParameter(fieldName);
    142         this.fileName = this.getName("test.png");
    143         this.url = savePath + "/" + this.fileName;
    144         BASE64Decoder decoder = new BASE64Decoder();
    145         try {
    146             File outFile = new File(this.getPhysicalPath(this.url));
    147             OutputStream ro = new FileOutputStream(outFile);
    148             byte[] b = decoder.decodeBuffer(base64Data);
    149             for (int i = 0; i < b.length; ++i) {
    150                 if (b[i] < 0) {
    151                     b[i] += 256;
    152                 }
    153             }
    154             ro.write(b);
    155             ro.flush();
    156             ro.close();
    157             this.state = this.errorInfo.get("SUCCESS");
    158         } catch (Exception e) {
    159             this.state = this.errorInfo.get("IO");
    160         }
    161     }
    162 
    163     /**
    164      * 文件类型判断
    165      * 
    166      * @param fileName
    167      * @return
    168      */
    169     private boolean checkFileType(String fileName) {
    170         Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
    171         while (type.hasNext()) {
    172             String ext = type.next();
    173             if (fileName.toLowerCase().endsWith(ext)) {
    174                 return true;
    175             }
    176         }
    177         return false;
    178     }
    179 
    180     /**
    181      * 获取文件扩展名
    182      * 
    183      * @return string
    184      */
    185     private String getFileExt(String fileName) {
    186         return fileName.substring(fileName.lastIndexOf("."));
    187     }
    188 
    189     /**
    190      * 依据原始文件名生成新文件名
    191      * 
    192      * @return
    193      */
    194     private String getName(String fileName) {
    195         Random random = new Random();
    196         return this.fileName = "" + random.nextInt(10000)
    197                 + System.currentTimeMillis() + this.getFileExt(fileName);
    198     }
    199 
    200     /**
    201      * 根据字符串创建本地目录 并按照日期建立子目录返回
    202      * 
    203      * @param path
    204      * @return
    205      */
    206     private String getFolder(String path) {
    207         SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
    208         path += "/" + formater.format(new Date());
    209         File dir = new File(this.getPhysicalPath(path));
    210         if (!dir.exists()) {
    211             try {
    212                 dir.mkdirs();
    213             } catch (Exception e) {
    214                 this.state = this.errorInfo.get("DIR");
    215                 return "";
    216             }
    217         }
    218         return path;
    219     }
    220 
    221     /**
    222      * 根据传入的虚拟路径获取物理路径
    223      * 
    224      * @param path
    225      * @return
    226      */
    227     private String getPhysicalPath(String path) {
    228         String servletPath = this.request.getServletPath();
    229         String realPath = this.request.getSession().getServletContext()
    230                 .getRealPath(servletPath);
    231         return new File(realPath).getParent() + "/" + path;
    232     }
    233 
    234     public void setSavePath(String savePath) {
    235         this.savePath = savePath;
    236     }
    237 
    238     public void setAllowFiles(String[] allowFiles) {
    239         this.allowFiles = allowFiles;
    240     }
    241 
    242     public void setMaxSize(int size) {
    243         this.maxSize = size;
    244     }
    245 
    246     public String getSize() {
    247         return this.size;
    248     }
    249 
    250     public String getUrl() {
    251         return this.url;
    252     }
    253 
    254     public String getFileName() {
    255         return this.fileName;
    256     }
    257 
    258     public String getState() {
    259         return this.state;
    260     }
    261 
    262     public String getTitle() {
    263         return this.title;
    264     }
    265 
    266     public String getType() {
    267         return this.type;
    268     }
    269 
    270     public String getOriginalName() {
    271         return this.originalName;
    272     }
    273 }
      1 package com.etop.utils;
      2 
      3 import java.awt.Color;
      4 import java.awt.Font;
      5 import java.awt.Graphics;
      6 import java.awt.image.BufferedImage;
      7 import java.util.Random;
      8 
      9 /**
     10  * 验证码生成器类,可生成数字、大写、小写字母及三者混合类型的验证码。 支持自定义验证码字符数量; 支持自定义验证码图片的大小; 支持自定义需排除的特殊字符;
     11  * 支持自定义干扰线的数量; 支持自定义验证码图文颜色
     12  * 
     13  * @author org.javachina
     14  * @version 1.01
     15  */
     16 public class VerifyCode {
     17 
     18     // 验证码类型,评论
     19     public static final String VERIFY_TYPE_COMMENT = "VERIFY_TYPE_COMMENT";
     20 
     21     /**
     22      * 验证码类型为仅数字 0~9
     23      */
     24     public static final int TYPE_NUM_ONLY = 0;
     25 
     26     /**
     27      * 验证码类型为仅字母,即大写、小写字母混合
     28      */
     29     public static final int TYPE_LETTER_ONLY = 1;
     30 
     31     /**
     32      * 验证码类型为数字、大写字母、小写字母混合
     33      */
     34     public static final int TYPE_ALL_MIXED = 2;
     35 
     36     /**
     37      * 验证码类型为数字、大写字母混合
     38      */
     39     public static final int TYPE_NUM_UPPER = 3;
     40 
     41     /**
     42      * 验证码类型为数字、小写字母混合
     43      */
     44     public static final int TYPE_NUM_LOWER = 4;
     45 
     46     /**
     47      * 验证码类型为仅大写字母
     48      */
     49     public static final int TYPE_UPPER_ONLY = 5;
     50 
     51     /**
     52      * 验证码类型为仅小写字母
     53      */
     54     public static final int TYPE_LOWER_ONLY = 6;
     55 
     56     private VerifyCode() {
     57     }
     58 
     59     /**
     60      * 生成验证码字符串
     61      * 
     62      * @param type
     63      *            验证码类型,参见本类的静态属性
     64      * @param length
     65      *            验证码长度,大于0的整数
     66      * @param exChars
     67      *            需排除的特殊字符(仅对数字、字母混合型验证码有效,无需排除则为null)
     68      * @return 验证码字符串
     69      */
     70     public static String generateTextCode(int type, int length, String exChars) {
     71 
     72         if (length <= 0)
     73             return "";
     74 
     75         StringBuffer code = new StringBuffer();
     76         int i = 0;
     77         Random r = new Random();
     78 
     79         switch (type) {
     80 
     81         // 仅数字
     82         case TYPE_NUM_ONLY:
     83             while (i < length) {
     84                 int t = r.nextInt(10);
     85                 if (exChars == null || exChars.indexOf(t + "") < 0) {// 排除特殊字符
     86                     code.append(t);
     87                     i++;
     88                 }
     89             }
     90             break;
     91 
     92         // 仅字母(即大写字母、小写字母混合)
     93         case TYPE_LETTER_ONLY:
     94             while (i < length) {
     95                 int t = r.nextInt(123);
     96                 if ((t >= 97 || (t >= 65 && t <= 90))
     97                         && (exChars == null || exChars.indexOf((char) t) < 0)) {
     98                     code.append((char) t);
     99                     i++;
    100                 }
    101             }
    102             break;
    103 
    104         // 数字、大写字母、小写字母混合
    105         case TYPE_ALL_MIXED:
    106             while (i < length) {
    107                 int t = r.nextInt(123);
    108                 if ((t >= 97 || (t >= 65 && t <= 90) || (t >= 48 && t <= 57))
    109                         && (exChars == null || exChars.indexOf((char) t) < 0)) {
    110                     code.append((char) t);
    111                     i++;
    112                 }
    113             }
    114             break;
    115 
    116         // 数字、大写字母混合
    117         case TYPE_NUM_UPPER:
    118             while (i < length) {
    119                 int t = r.nextInt(91);
    120                 if ((t >= 65 || (t >= 48 && t <= 57))
    121                         && (exChars == null || exChars.indexOf((char) t) < 0)) {
    122                     code.append((char) t);
    123                     i++;
    124                 }
    125             }
    126             break;
    127 
    128         // 数字、小写字母混合
    129         case TYPE_NUM_LOWER:
    130             while (i < length) {
    131                 int t = r.nextInt(123);
    132                 if ((t >= 97 || (t >= 48 && t <= 57))
    133                         && (exChars == null || exChars.indexOf((char) t) < 0)) {
    134                     code.append((char) t);
    135                     i++;
    136                 }
    137             }
    138             break;
    139 
    140         // 仅大写字母
    141         case TYPE_UPPER_ONLY:
    142             while (i < length) {
    143                 int t = r.nextInt(91);
    144                 if ((t >= 65)
    145                         && (exChars == null || exChars.indexOf((char) t) < 0)) {
    146                     code.append((char) t);
    147                     i++;
    148                 }
    149             }
    150             break;
    151 
    152         // 仅小写字母
    153         case TYPE_LOWER_ONLY:
    154             while (i < length) {
    155                 int t = r.nextInt(123);
    156                 if ((t >= 97)
    157                         && (exChars == null || exChars.indexOf((char) t) < 0)) {
    158                     code.append((char) t);
    159                     i++;
    160                 }
    161             }
    162             break;
    163 
    164         }
    165 
    166         return code.toString();
    167     }
    168 
    169     /**
    170      * 已有验证码,生成验证码图片
    171      * 
    172      * @param textCode
    173      *            文本验证码
    174      * @param width
    175      *            图片宽度
    176      * @param height
    177      *            图片高度
    178      * @param interLine
    179      *            图片中干扰线的条数
    180      * @param randomLocation
    181      *            每个字符的高低位置是否随机
    182      * @param backColor
    183      *            图片颜色,若为null,则采用随机颜色
    184      * @param foreColor
    185      *            字体颜色,若为null,则采用随机颜色
    186      * @param lineColor
    187      *            干扰线颜色,若为null,则采用随机颜色
    188      * @return 图片缓存对象
    189      */
    190     public static BufferedImage generateImageCode(String textCode, int width,
    191             int height, int interLine, boolean randomLocation, Color backColor,
    192             Color foreColor, Color lineColor) {
    193 
    194         BufferedImage bim = new BufferedImage(width, height,
    195                 BufferedImage.TYPE_INT_RGB);
    196         Graphics g = bim.getGraphics();
    197         // 画背景图
    198         g.setColor(backColor == null ? getRandomColor() : backColor);
    199         g.fillRect(0, 0, width, height);
    200 
    201         // 画干扰线
    202         Random r = new Random();
    203         if (interLine > 0) {
    204 
    205             int x = 0, y = 0, x1 = width, y1 = 0;
    206             for (int i = 0; i < interLine; i++) {
    207                 g.setColor(lineColor == null ? getRandomColor() : lineColor);
    208                 y = r.nextInt(height);
    209                 y1 = r.nextInt(height);
    210 
    211                 g.drawLine(x, y, x1, y1);
    212             }
    213         }
    214 
    215         // 写验证码
    216 
    217         // g.setColor(getRandomColor());
    218         // g.setColor(isSimpleColor?Color.BLACK:Color.WHITE);
    219 
    220         // 字体大小为图片高度的80%
    221         int fsize = (int) (height * 0.8);
    222         int fx = height - fsize;
    223         int fy = fsize;
    224 
    225         g.setFont(new Font("Times New Roman", Font.BOLD, 20));
    226 
    227         // 写验证码字符
    228         for (int i = 0; i < textCode.length(); i++) {
    229             fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height)
    230                     : fy;// 每个字符高低是否随机
    231             g.setColor(foreColor == null ? getRandomColor() : foreColor);
    232             g.drawString(textCode.charAt(i) + "", fx, fy);
    233             fx += fsize * 0.9;
    234         }
    235 
    236         g.dispose();
    237 
    238         return bim;
    239     }
    240 
    241     /**
    242      * 生成图片验证码
    243      * 
    244      * @param type
    245      *            验证码类型,参见本类的静态属性
    246      * @param length
    247      *            验证码字符长度,大于0的整数
    248      * @param exChars
    249      *            需排除的特殊字符
    250      * @param width
    251      *            图片宽度
    252      * @param height
    253      *            图片高度
    254      * @param interLine
    255      *            图片中干扰线的条数
    256      * @param randomLocation
    257      *            每个字符的高低位置是否随机
    258      * @param backColor
    259      *            图片颜色,若为null,则采用随机颜色
    260      * @param foreColor
    261      *            字体颜色,若为null,则采用随机颜色
    262      * @param lineColor
    263      *            干扰线颜色,若为null,则采用随机颜色
    264      * @return 图片缓存对象
    265      */
    266     public static BufferedImage generateImageCode(int type, int length,
    267             String exChars, int width, int height, int interLine,
    268             boolean randomLocation, Color backColor, Color foreColor,
    269             Color lineColor) {
    270 
    271         String textCode = generateTextCode(type, length, exChars);
    272         BufferedImage bim = generateImageCode(textCode, width, height,
    273                 interLine, randomLocation, backColor, foreColor, lineColor);
    274 
    275         return bim;
    276     }
    277 
    278     /**
    279      * 产生随机颜色
    280      * 
    281      * @return
    282      */
    283     private static Color getRandomColor() {
    284         Random r = new Random();
    285         Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
    286         return c;
    287     }
    288 
    289     public static void main(String[] args) {
    290 
    291     }
    292 
    293 }

    下面是项目的配置文件:

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <beans xmlns="http://www.springframework.org/schema/beans"
      3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      4        xmlns:aop="http://www.springframework.org/schema/aop"
      5        xmlns:context="http://www.springframework.org/schema/context"
      6        xmlns:tx="http://www.springframework.org/schema/tx"
      7        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      8           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
      9           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
     10           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
     11 " default-lazy-init="true">
     12 
     13 
     14     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
     15         <property name="realm" ref="myRealm"/>
     16         <!-- 使用下面配置的缓存管理器 -->
     17         <property name="cacheManager" ref="cacheManager"/>
     18     </bean>
     19     <!--自定义Realm-->
     20     <bean id="myRealm" class="com.etop.shiro.MyRealm"/>
     21 
     22     <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
     23     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
     24         <!-- 调用我们配置的权限管理器 -->
     25         <property name="securityManager" ref="securityManager"/>
     26         <!-- 配置我们的登录请求地址 -->
     27         <property name="loginUrl" value="/login.html"/>
     28         <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
     29         <property name="successUrl" value="/user.html"/>
     30         <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
     31         <property name="unauthorizedUrl" value="/403.html"/>
     32         <!-- 权限配置 -->
     33        <!--  <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource"/> -->
     34        <property name="filterChainDefinitions">
     35            <value>
     36                /static/** = anon
     37                /login.html = anon
     38                /verifyCode.html = anon
     39                /role/** = roles[admin]
     40                /user/** = roles[admin]
     41                /function/** = roles[admin]
     42                /permission/** = roles[admin]
     43                /** = authc
     44            </value>
     45        </property>
     46     </bean>
     47     <!--自定义filterChainDefinitionMap-->
     48     <!-- <bean id="chainDefinitionSectionMetaSource" class="com.etop.shiro.ChainDefinitionSectionMetaSource"/> -->
     49     <!--shiro缓存管理器-->
     50     <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>
     51     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
     52 
     53 
     54     <bean id="propertyConfigurer"
     55           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     56         <property name="locations" value="classpath:jdbc.properties"/>
     57     </bean>
     58 
     59     <!--hibernate session工厂设置-->
     60     <bean id="sessionFactory"
     61           class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
     62         <property name="dataSource" ref="dataSource"/>
     63         <property name="packagesToScan">
     64             <list>
     65                 <value>com.etop.pojo</value>
     66             </list>
     67         </property>
     68         <property name="hibernateProperties">
     69             <props>
     70                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
     71                 <prop key="hibernate.generate_statistics">false</prop>
     72                 <prop key="hibernate.show_sql">true</prop>
     73                 <prop key="hibernate.format_sql">false</prop>
     74                 <prop key="hibernate.jdbc.batch_size">50</prop>
     75                 <prop key="jdbc.use_scrollable_resultset">false</prop>
     76                 <prop key="javax.persistence.validation.mode">none</prop>
     77                 <prop key="hibernate.cache.use_second_level_cache">true</prop>
     78                 <prop key="hibernate.cache.use_query_cache">true</prop>
     79                 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
     80                 <prop key="jdbc.use_scrollable_resultset">false</prop>
     81             </props>
     82         </property>
     83     </bean>
     84 
     85     <!-- c3p0 configuration -->
     86     <bean id="mainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
     87         <property name="driverClass" value="${jdbc.driverClass}"/>
     88         <property name="jdbcUrl" value="${jdbc.url}"/>
     89         <property name="user" value="${jdbc.username}"/>
     90         <property name="password" value="${jdbc.password}"/>
     91         <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
     92         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
     93         <property name="checkoutTimeout" value="${jdbc.checkoutTimeout}"/>
     94         <property name="maxStatements" value="${jdbc.maxStatements}"/>
     95         <property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}"/>
     96         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"/>
     97     </bean>
     98 
     99     <bean id="dataSource"
    100           class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
    101         <property name="targetDataSource">
    102             <ref bean="mainDataSource"/>
    103         </property>
    104     </bean>
    105     <context:annotation-config/>
    106     <context:component-scan base-package="com.etop">
    107         <context:exclude-filter type="regex" expression="com.cn.controller.*"/>
    108     </context:component-scan>
    109 
    110     <bean id="transactionManager"
    111           class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    112         <property name="sessionFactory">
    113             <ref bean="sessionFactory"/>
    114         </property>
    115     </bean>
    116 
    117     <!-- 拦截配置 -->
    118     <tx:advice id="txAdvice" transaction-manager="transactionManager">
    119         <tx:attributes>
    120             <!--说明事务类别 -->
    121             <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    122             <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    123             <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    124             <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    125             <tx:method name="batch*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    126             <tx:method name="sendOpen*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    127             <tx:method name="sendClose*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
    128             <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
    129             <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
    130             <tx:method name="load*" propagation="REQUIRED" read-only="true"/>
    131             <tx:method name="*" read-only="true"/>
    132         </tx:attributes>
    133     </tx:advice>
    134 
    135     <!-- 切入点 -->
    136     <aop:config expose-proxy="true" proxy-target-class="true">
    137         <!-- service层事务 -->
    138         <aop:advisor id="serviceTx" advice-ref="txAdvice"
    139                      pointcut="execution(public * com.etop.service.*.*(..))" order="1"/>
    140     </aop:config>
    141 
    142     <tx:annotation-driven/>
    143 
    144 </beans>
     1 <ehcache>
     2 
     3     <!-- Sets the path to the directory where cache .data files are created.
     4 
     5          If the path is a Java System Property it is replaced by
     6          its value in the running VM.
     7 
     8          The following properties are translated:
     9          account.home - Account's home directory
    10          account.dir - Account's current working directory
    11          java.io.tmpdir - Default temp file path -->
    12     <diskStore path="java.io.tmpdir"/>
    13 
    14 
    15     <!--Default Cache configuration. These will applied to caches programmatically created through
    16         the CacheManager.
    17 
    18         The following attributes are required for defaultCache:
    19 
    20         maxInMemory       - Sets the maximum number of objects that will be created in memory
    21         eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
    22                             is never expired.
    23         timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
    24                             if the element is not eternal. Idle time is now - last accessed time
    25         timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
    26                             if the element is not eternal. TTL is now - creation time
    27         overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
    28                             has reached the maxInMemory limit.
    29 
    30         -->
    31     <defaultCache
    32         maxElementsInMemory="10000"
    33         eternal="false"
    34         timeToIdleSeconds="120"
    35         timeToLiveSeconds="120"
    36         overflowToDisk="true"
    37         />
    38 
    39     <!--Predefined caches.  Add your cache configuration settings here.
    40         If you do not have a configuration for your cache a WARNING will be issued when the
    41         CacheManager starts
    42 
    43         The following attributes are required for defaultCache:
    44 
    45         name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
    46         maxInMemory       - Sets the maximum number of objects that will be created in memory
    47         eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
    48                             is never expired.
    49         timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
    50                             if the element is not eternal. Idle time is now - last accessed time
    51         timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
    52                             if the element is not eternal. TTL is now - creation time
    53         overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
    54                             has reached the maxInMemory limit.
    55 
    56         -->
    57     <!-- Place configuration for your caches following -->
    58     <cache name="org.hibernate.cache.StandardQueryCache"
    59            maxElementsInMemory="10000" eternal="false" 
    60            timeToIdleSeconds="300"
    61            timeToLiveSeconds="4200" overflowToDisk="true" />
    62     
    63     <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
    64            maxElementsInMemory="5000" 
    65            eternal="true" 
    66            overflowToDisk="true" />
    67 
    68 
    69 </ehcache>
     1 jdbc.driverClass = com.mysql.jdbc.Driver
     2 jdbc.url = jdbc:mysql://127.0.0.1:3306/shiro
     3 jdbc.username = root
     4 jdbc.password = root
     5 jdbc.minPoolSize=2
     6 jdbc.maxPoolSize=20
     7 jdbc.checkoutTimeout=3000
     8 jdbc.maxStatements=50
     9 jdbc.testConnectionOnCheckin = false
    10 jdbc.idleConnectionTestPeriod = 18000
    1 log4j.rootLogger=info,stdout
    2 
    3 log4j.appender.stdout = org.apache.log4j.ConsoleAppender
    4 log4j.appender.stdout.Target = System.out
    5 log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
    6 log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
    7 Hibernate
    8 #log4j.logger.org.hibernate=debug
    9 #log4j.logger.org.hibernate.SQL=debug

    数据库文件(数据库用的是mysql):

      1 /*
      2 SQLyog 企业版 - MySQL GUI v8.14 
      3 MySQL - 5.5.19 : Database - shiro
      4 *********************************************************************
      5 */
      6 
      7 
      8 /*!40101 SET NAMES utf8 */;
      9 
     10 /*!40101 SET SQL_MODE=''*/;
     11 
     12 /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
     13 /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
     14 /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
     15 /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
     16 CREATE DATABASE /*!32312 IF NOT EXISTS*/`shiro` /*!40100 DEFAULT CHARACTER SET utf8 */;
     17 
     18 USE `shiro`;
     19 
     20 /*Table structure for table `t_function` */
     21 
     22 DROP TABLE IF EXISTS `t_function`;
     23 
     24 CREATE TABLE `t_function` (
     25   `id` int(11) NOT NULL,
     26   `value` varchar(50) DEFAULT NULL,
     27   `permission_id` int(11) DEFAULT NULL,
     28   `role_id` int(11) DEFAULT NULL,
     29   `type` varchar(50) DEFAULT NULL,
     30   PRIMARY KEY (`id`),
     31   KEY `fk_function_role` (`role_id`),
     32   KEY `fk_function_permission` (`permission_id`),
     33   CONSTRAINT `fk_function_permission` FOREIGN KEY (`permission_id`) REFERENCES `t_permission` (`id`),
     34   CONSTRAINT `fk_function_role` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`)
     35 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     36 
     37 /*Data for the table `t_function` */
     38 
     39 insert  into `t_function`(`id`,`value`,`permission_id`,`role_id`,`type`) values (2,'/login.html',NULL,NULL,'anon'),(3,'/user.html',4,NULL,'perms'),(4,'/user/add.html',1,NULL,'perms'),(5,'/user/del.html',2,NULL,'perms'),(6,'/user/edit.html',3,NULL,'perms'),(7,'/test.html',NULL,4,'roles'),(8,'/verifyCode.html',NULL,NULL,'anon'),(9,'/user/userList.html',NULL,4,'roles');
     40 
     41 /*Table structure for table `t_permission` */
     42 
     43 DROP TABLE IF EXISTS `t_permission`;
     44 
     45 CREATE TABLE `t_permission` (
     46   `id` int(11) NOT NULL,
     47   `permissionname` varchar(45) NOT NULL,
     48   PRIMARY KEY (`id`)
     49 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     50 
     51 /*Data for the table `t_permission` */
     52 
     53 insert  into `t_permission`(`id`,`permissionname`) values (1,'user:add'),(2,'user:del'),(3,'user:update'),(4,'user:query');
     54 
     55 /*Table structure for table `t_role` */
     56 
     57 DROP TABLE IF EXISTS `t_role`;
     58 
     59 CREATE TABLE `t_role` (
     60   `id` int(11) NOT NULL,
     61   `rolename` varchar(45) DEFAULT NULL,
     62   `description` varchar(45) DEFAULT NULL,
     63   PRIMARY KEY (`id`)
     64 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     65 
     66 /*Data for the table `t_role` */
     67 
     68 insert  into `t_role`(`id`,`rolename`,`description`) values (1,'admin','超级管理员'),(2,'manager','系统管理员'),(3,'normal','普通管理员'),(4,'user','普通用户');
     69 
     70 /*Table structure for table `t_role_permission` */
     71 
     72 DROP TABLE IF EXISTS `t_role_permission`;
     73 
     74 CREATE TABLE `t_role_permission` (
     75   `role_id` int(11) DEFAULT NULL,
     76   `permission_id` int(11) DEFAULT NULL
     77 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     78 
     79 /*Data for the table `t_role_permission` */
     80 
     81 insert  into `t_role_permission`(`role_id`,`permission_id`) values (1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(3,4),(4,4),(4,3);
     82 
     83 /*Table structure for table `t_user` */
     84 
     85 DROP TABLE IF EXISTS `t_user`;
     86 
     87 CREATE TABLE `t_user` (
     88   `id` int(11) NOT NULL,
     89   `username` varchar(45) DEFAULT NULL,
     90   `password` varchar(45) DEFAULT NULL,
     91   PRIMARY KEY (`id`)
     92 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     93 
     94 /*Data for the table `t_user` */
     95 
     96 insert  into `t_user`(`id`,`username`,`password`) values (1,'admin1','670b14728ad9902aecba32e22fa4f6bd'),(2,'admin2','670b14728ad9902aecba32e22fa4f6bd'),(3,'admin3','670b14728ad9902aecba32e22fa4f6bd'),(4,'admin4','670b14728ad9902aecba32e22fa4f6bd');
     97 
     98 /*Table structure for table `t_user_role` */
     99 
    100 DROP TABLE IF EXISTS `t_user_role`;
    101 
    102 CREATE TABLE `t_user_role` (
    103   `user_id` int(11) DEFAULT NULL,
    104   `role_id` int(11) DEFAULT NULL,
    105   KEY `FK_role_user` (`role_id`),
    106   KEY `FK_user_role` (`user_id`),
    107   CONSTRAINT `FK_role_user` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`),
    108   CONSTRAINT `FK_user_role` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)
    109 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    110 
    111 /*Data for the table `t_user_role` */
    112 
    113 insert  into `t_user_role`(`user_id`,`role_id`) values (1,1),(1,3),(2,2),(2,3),(3,3),(4,4);
    114 
    115 /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
    116 /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
    117 /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
    118 /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
  • 相关阅读:
    Linux命令: ls -l显示文件和目录的详细资料
    Linux命令: ls -F
    Linux命令: pwd显示工作路径
    Linux命令: cd /home 进入'/home'目录
    Linux命令: cd ../.. 返回上两级目录
    Linux命令: cd
    boost::mpl::eval_if的使用方法
    【block第四篇】实现
    Android中pendingIntent的深入理解
    hdu 1565 方格取数(1)(状态压缩dp)
  • 原文地址:https://www.cnblogs.com/lr393993507/p/5257162.html
Copyright © 2020-2023  润新知