相关的maven的 pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.com.cisec.vcs</groupId>
<artifactId>VCS</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>VCS Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- SpringMVC核心jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- ************************************ -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.7.4</version>
</dependency>
<!-- Hibernate相关jar -->
<dependency>
<groupId>fr.inria.powerapi.sensor</groupId>
<artifactId>sensor-sigar</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!-- javax提供的annotation -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- **************************** --> <!-- hibernate验证 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5-pre8</version>
</dependency>
<!-- 提供对c标签的支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- servlet api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- json字符串的包 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
<!--Apache Shiro所需的jar包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId >
<artifactId>aspectjweaver</artifactId >
<version> 1.6.11</version >
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>
<finalName>VCS</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<version>2.2</version>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.0.M1</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/VCS</contextPath>
</webApp>
</configuration>
</plugin>
<!-- <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId>
<version>2.0-SNAPSHOT</version> <configuration> <url>http://localhost:8080/controlserver</url>
<server>Tomcat 7.x</server> </configuration> </plugin> -->
</plugins>
</build>
</project>

基础的java代码:

 package com.etop.basic.controller;

 import com.etop.utils.DateUtils;

 import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import java.beans.PropertyEditorSupport;
import java.util.Date; /**
* @类名: BaseController
* @描述: TODO(这里用一句话描述这个类的作用)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:11:32
*/
@Controller
public abstract class BaseController { public final static String ERROR = "error";
public final static String SUCCESS = "success"; protected Logger log = Logger.getLogger(this.getClass()); /**
* 添加Model消息
*
* @param messages
*/
protected void addMessage(Model model, String messages) {
model.addAttribute("message", messages);
} /**
* 添加Model消息
*
* @param type
* 消息类型
* @param messages
*/
protected void addMessage(Model model, String type, String messages) {
model.addAttribute("message", messages);
model.addAttribute("type", type);
} /**
* 添加Flash消息
*
* @param messages
*/
protected void addMessage(RedirectAttributes redirectAttributes,
String messages) {
redirectAttributes.addFlashAttribute("message", messages);
} /**
* 添加Flash消息
*
* @param type
* 消息类型
* @param messages
*/
protected void addMessage(RedirectAttributes redirectAttributes,
String type, String messages) {
redirectAttributes.addFlashAttribute("message", messages);
redirectAttributes.addFlashAttribute("type", type);
} /**
* 初始化数据绑定 1. 将所有传递进来的String进行HTML编码,防止XSS攻击 2. 将字段中Date类型转换为String类型
*/
@InitBinder
protected void initBinder(WebDataBinder binder) {
// String类型转换,将所有传递进来的String进行HTML编码,防止XSS攻击
binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
// setValue(text == null ? null :
// StringEscapeUtils.escapeHtml(text.trim()));
setValue(text == null ? null : text.trim());
} @Override
public String getAsText() {
Object value = getValue();
return value != null ? value.toString() : "";
}
});
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.parseDate(text));
}
});
} @ExceptionHandler(Exception.class)
public String handleException(Exception ex, HttpServletRequest request) {
log.error("系统发生异常", ex);
ex.printStackTrace();
request.setAttribute("exMsg", ex.getMessage());
return "errors/exception";
}
}
 package com.etop.basic.dao;

 import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import com.etop.utils.PageUtil;
import com.etop.utils.ThreadLocalUtils; import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set; /**
* @类名: BaseDAO
* @描述: TODO(这里用一句话描述这个类的作用)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:12:00
* @param <T>
*/
public class BaseDAO<T> implements Serializable { protected transient Logger log = Logger.getLogger(this.getClass());
@Autowired
private SessionFactory sessionFactory;
private Class<T> persistentClass; protected Class<T> getCurClass() {
if (persistentClass == null) {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
return persistentClass;
} protected Session getSession() {
return sessionFactory.getCurrentSession();
} protected StatelessSession getStatelessSession() {
return sessionFactory.openStatelessSession();
} public void flush() {
getSession().flush();
} public void evict(T entity) {
getSession().evict(entity);
} public T get(long id) throws DataAccessException {
log.debug("DAO:Get entity " + getCurClass().getSimpleName() + ":Id="
+ id);
return (T) getSession().get(getCurClass(), id);
} public void save(T entity) throws DataAccessException {
log.debug("DAO:Save entity " + entity.getClass().getSimpleName());
getSession().save(entity);
} public void update(T entity) throws DataAccessException {
log.debug("DAO:Update entity " + entity.getClass().getSimpleName());
getSession().clear();
getSession().update(entity);
} public void saveOrUpdate(T entity) throws DataAccessException {
log.debug("DAO:Sava or Update entity "
+ entity.getClass().getSimpleName());
getSession().clear();
getSession().saveOrUpdate(entity);
} public void delete(T entity) throws DataAccessException {
log.debug("DAO:delete entity " + getCurClass().getSimpleName());
getSession().delete(entity);
} public void deleteById(long id) throws DataAccessException {
log.debug("DAO:delete entity " + getCurClass().getSimpleName() + ":Id="
+ id);
String queryString = "delete from " + getCurClass().getSimpleName()
+ " where id=" + id;
this.excute(queryString);
} public int excute(String queryString) throws DataAccessException {
log.debug("DAO:Excute HQL update :" + queryString);
Query query = getSession().createQuery(queryString);
return query.executeUpdate();
} public List<T> find(String queryString) throws DataAccessException {
log.debug("DAO:Running HQL query :" + queryString);
Query query = getSession().createQuery(queryString);
query.setCacheable(true);
return query.list();
} private Query createQuery(String queryString, Map<String, Object> params,
int startRow, int pageSize) {
Query query = getSession().createQuery(queryString);
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String paramName = entry.getKey();
Object obj = entry.getValue();
log.info("DAO:set param:" + paramName + " with value:" + obj);
if (obj instanceof List) {
query.setParameterList(paramName, (Collection) obj);
} else if (obj instanceof Object[]) {
query.setParameterList(paramName, (Object[]) obj);
} else {
query.setParameter(paramName, obj);
}
}
}
query.setCacheable(true);
if (pageSize != -1) {
query.setFirstResult(startRow).setMaxResults(pageSize);
}
return query;
} private Query createQuery(String queryString) {
return createQuery(queryString, null, 0, -1);
} private Query createQuery(String queryString, Map<String, Object> params) {
return createQuery(queryString, params, 0, -1);
} public List<T> find(String queryString, int startRow, int pageSize)
throws DataAccessException {
log.debug("DAO:Running HQL query by page:" + queryString);
Query query = createQuery(queryString, null, startRow, pageSize);
return query.list();
} public int getTotalCount(String queryString) throws DataAccessException {
return getTotalCount(queryString, null);
} public int getTotalCount(String queryString, Map<String, Object> params)
throws DataAccessException {
log.debug("DAO:Running HQL query for total count of records :"
+ queryString);
queryString = "select count(t.id) " + queryString;
Query query;
if (params != null) {
query = createQuery(queryString, params);
} else {
query = createQuery(queryString);
}
return ((Long) query.uniqueResult()).intValue();
} public List findWithSelect(String queryString) throws DataAccessException {
log.debug("DAO:Running HQL query with selections :" + queryString);
Query query = createQuery(queryString);
return query.list();
} public List findWithSelect(String queryString, Map<String, Object> params)
throws DataAccessException {
log.debug("DAO:Running HQL query with parameters:" + queryString);
Query query = createQuery(queryString, params);
return query.list();
} public List findWithSelect(String queryString, Map<String, Object> params,
int startRow, int pageSize) throws DataAccessException {
log.debug("DAO:Running HQL query by page :" + queryString);
Query query = createQuery(queryString, params, startRow, pageSize);
return query.list();
} public List<T> find(String queryString, Map<String, Object> params)
throws DataAccessException {
log.debug("DAO:Running HQL query with parameters: " + queryString);
Query query = createQuery(queryString, params);
return query.list();
} public List<T> find(String queryString, Map<String, Object> params,
int startRow, int pageSize) throws DataAccessException {
log.debug("DAO:Running HQL query with params by page :" + queryString);
Query query = createQuery(queryString, params, startRow, pageSize);
return query.list();
} public T findUniqueResult(String queryString, Map<String, Object> params)
throws DataAccessException {
log.debug("DAO:Running HQL query with parameters:" + queryString);
Query query = createQuery(queryString, params);
return (T) query.uniqueResult();
} public int excute(String queryString, Map<String, Object> params)
throws DataAccessException {
log.debug("DAO:Excute HQL update :" + queryString);
Query query = createQuery(queryString, params);
return query.executeUpdate();
} /**
* pagefind
*/
private String initSort(String hql) {
log.debug("DAO:Excute HQL update :" + hql);
String order = ThreadLocalUtils.getOrder();
String sort = ThreadLocalUtils.getSort();
if (sort != null && !"".equals(sort.trim())) {
hql += " order by " + sort;
if (!"desc".equals(order))
hql += " asc";
else
hql += " desc";
}
return hql;
} @SuppressWarnings("rawtypes")
private void setAliasParameter(Query query, Map<String, Object> alias) {
if (alias != null) {
Set<String> keys = alias.keySet();
for (String key : keys) {
Object val = alias.get(key);
if (val instanceof Collection) {
// 查询条件是列表
query.setParameterList(key, (Collection) val);
} else {
query.setParameter(key, val);
}
}
}
} private void setParameter(Query query, Object[] args) {
if (args != null && args.length > 0) {
int index = 0;
for (Object arg : args) {
query.setParameter(index++, arg);
}
}
} private String getCountHql(String hql, boolean isHql) {
log.debug("DAO:Excute HQL update :" + hql);
String e = hql.substring(hql.indexOf("from"));
String c = "select count(*) " + e;
if (isHql)
c = c.replaceAll("fetch", "");
return c;
} public PageUtil<T> pagefind(String hql, Object[] args,
Map<String, Object> alias) {
log.debug("DAO:Excute HQL update :" + hql);
hql = initSort(hql);
String cq = getCountHql(hql, true);
Query cquery = getSession().createQuery(cq);
Query query = getSession().createQuery(hql);
// 设置别名参数
setAliasParameter(query, alias);
setAliasParameter(cquery, alias);
// 设置参数
setParameter(query, args);
setParameter(cquery, args);
PageUtil<T> pages = new PageUtil<T>();
setPagers(query, pages);
List<T> datas = query.list();
pages.setRows(datas);
long total = (Long) cquery.uniqueResult();
pages.setTotal(total);
return pages;
} public PageUtil<T> pagefind(String hql, Object[] args) {
log.debug("DAO:Excute HQL update :" + hql);
return this.pagefind(hql, args, null);
} public PageUtil<T> pagefind(String hql, Object arg) {
log.debug("DAO:Excute HQL update :" + hql);
return this.pagefind(hql, new Object[] { arg });
} public PageUtil<T> pagefind(String hql) {
log.debug("DAO:Excute HQL update :" + hql);
return this.pagefind(hql, null);
} @SuppressWarnings("rawtypes")
private void setPagers(Query query, PageUtil pages) {
Integer pageSize = ThreadLocalUtils.getPageSize();
Integer pageOffset = ThreadLocalUtils.getPageOffset();
if (pageOffset == null || pageOffset < 0)
pageOffset = 0;
if (pageSize == null || pageSize < 0)
pageSize = 15;
// pages.setOffset(pageOffset);
// pages.setSize(pageSize);
query.setFirstResult(pageOffset).setMaxResults(pageSize);
} public <N extends Object> PageUtil<N> findBySql(String sql, Object[] args,
Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
sql = initSort(sql);
String cq = getCountHql(sql, false);
SQLQuery sq = getSession().createSQLQuery(sql);
SQLQuery cquery = getSession().createSQLQuery(cq);
setAliasParameter(sq, alias);
setAliasParameter(cquery, alias);
setParameter(sq, args);
setParameter(cquery, args);
PageUtil<N> pages = new PageUtil<N>();
// setPagers(sq, pages);
if (hasEntity) {
sq.addEntity(clz);
} else {
sq.setResultTransformer(Transformers.aliasToBean(clz));
}
List<N> datas = sq.list();
pages.setRows(datas);
long total = ((BigInteger) cquery.uniqueResult()).longValue();
pages.setTotal(total);
return pages;
} public <N extends Object> PageUtil<N> findBySql(String sql, Object[] args,
Class<?> clz, boolean hasEntity) {
return this.findBySql(sql, args, null, clz, hasEntity);
} public <N extends Object> PageUtil<N> findBySql(String sql, Object arg,
Class<?> clz, boolean hasEntity) {
return this.findBySql(sql, new Object[] { arg }, clz, hasEntity);
} public <N extends Object> PageUtil<N> findBySql(String sql, Class<?> clz,
boolean hasEntity) {
return this.findBySql(sql, null, clz, hasEntity);
}
}
 package com.etop.controller;

 import java.util.HashMap;
import java.util.Map;
import java.util.Set; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.etop.basic.controller.BaseController;
import com.etop.dto.FunctionDto;
import com.etop.pojo.Function;
import com.etop.pojo.Permission;
import com.etop.pojo.Role;
import com.etop.service.FunctionService;
import com.etop.service.PermissionService;
import com.etop.service.RoleService;
import com.etop.utils.PageUtil; /**
* @类名: FunctionController
* @描述: 处理过滤网址出的控制器
* @作者 liuren-mail@163.com
* @日期 2015年5月27日 下午3:31:54
*/
@Controller
@RequestMapping("/function")
public class FunctionController extends BaseController {
Map<String,Object> map = new HashMap<String,Object>();
private final static Logger log = Logger
.getLogger(FunctionController.class);
@Autowired
private FunctionService functionService;
@Autowired
private PermissionService permissionService;
@Autowired
private RoleService roleService;
@RequestMapping("/functionList.html")
public String getFunctions() {
log.info("/functionList.html");
return "/functionList.jsp";
} /**
* @标题: getFunctionList
* @描述: 返回分页的json数据
* @参数 @return 设定文件
* @返回 Object 返回类型
* @throws
* @作者 liuren-mail@163.com
* @日期 2015年5月27日 下午3:55:12
*/
@RequestMapping("/get_functions.html")
@ResponseBody
public Object getFunctionList() {
log.info("/get_functions.html");
PageUtil<FunctionDto> functionList = functionService.findAllFunction();
return functionList;
} @RequestMapping("/add.html")
@ResponseBody
public Object addFunction(String value,int permission_id,int role_id,String type) {
log.info("/add.html");
Function function = new Function();
function.setPermission_id(permission_id);
function.setRole_id(role_id);
function.setValue(value);
function.setType(type);
functionService.saveFunction(function);
map.put(SUCCESS, true);
return map;
} @RequestMapping("/edit.html")
@ResponseBody
public Object updateFunction(int id,String value,String type) {
log.info("/edit.html");
Function function = functionService.findFunctionById(id);
if (function==null||"".equals(function)) {
map.put(SUCCESS, false);
return map;
}
function.setValue(value);
function.setType(type);
functionService.updateFunction(function);
map.put(SUCCESS, true);
return map;
} @RequestMapping("/del.html")
@ResponseBody
public Object deleteFunction(int id) {
log.info("/del.html");
functionService.deleteFunction(id);
map.put(SUCCESS, true);
return map;
}
}
 package com.etop.controller;

 import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid; import com.etop.basic.controller.BaseController;
import com.etop.service.UserService;
import com.etop.utils.VerifyCode; import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import com.etop.pojo.User; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List; /**
* @类名: HomeController
* @描述: 处理用户登录登出的控制器
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:11:00
*/
@Controller
public class HomeController extends BaseController {
private final static Logger log = Logger.getLogger(HomeController.class);
@Autowired
private UserService userService; @RequestMapping(value = "/login.html", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
public String loginForm(Model model, String message) {
if (!StringUtils.isEmpty(message))
model.addAttribute(message);
model.addAttribute("user", new User());
System.out.println("login_1");
System.out.println("model:" + model);
System.out.println("message:" + message);
log.info("login.html");
return "/login.jsp";
} @RequestMapping(value = "/login.html", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
public String login(@Valid User user, BindingResult bindingResult,
Model model, RedirectAttributes attr, HttpServletRequest request) {
HttpSession session = request.getSession();
// session为空时跳转到登录界面
if (session.getAttribute(VerifyCode.VERIFY_TYPE_COMMENT) == null
|| session.getAttribute(VerifyCode.VERIFY_TYPE_COMMENT) == "") {
addMessage(attr, "session为空");
log.info("session为空");
return "redirect:/";
}
String code = ((String) request.getSession().getAttribute(
VerifyCode.VERIFY_TYPE_COMMENT)).toLowerCase();
String submitCode = WebUtils.getCleanParam(request, "checkcode");
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(submitCode)
|| !StringUtils.equals(code, submitCode.toLowerCase())) {
addMessage(attr, "验证码错误");
log.info("验证码错误");
return "redirect:/";
}
try {
if (bindingResult.hasErrors() || user.getUsername().isEmpty()
|| user.getPassword().isEmpty()) {
addMessage(attr, "用户名或密码错误");
log.info("用户名或密码错误");
return "redirect:/login.html";
}
System.out.println("管理用户登录");
// 使用shiro管理登录
SecurityUtils.getSubject().login(
new UsernamePasswordToken(user.getUsername(), user
.getPassword()));
// 获取所有用户信息,权限由前端shiro标签控制
List<User> userList = userService.getAllUser();
System.out.println(userList);
model.addAttribute("userList", userList);
System.out.println("管理用户登录success");
log.info("成功登录");
System.out.println("密码:======================"+user.getPassword());
return "/user.jsp";
} catch (AuthenticationException e) {
addMessage(attr, "用户名或密码错误");
log.info("用户名或密码错误");
return "redirect:/login.html";
}
} @RequestMapping(value = "/logout.html", method = RequestMethod.GET)
public String logout(RedirectAttributes attr) {
// 使用权限管理工具进行用户的退出,注销登录
SecurityUtils.getSubject().logout();
addMessage(attr, "您已安全退出");
log.info("安全退出");
return "redirect:/login.html";
} @RequestMapping("/403.html")
public String unauthorizedRole() {
log.info("跳转到403页面");
return "/403.jsp";
} @RequestMapping("/verifyCode.html")
public void verifyCode(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
// 生成验证码,写入用户session
String verifyCode = VerifyCode.generateTextCode(
VerifyCode.TYPE_NUM_UPPER, 4, "null");
request.getSession().setAttribute(VerifyCode.VERIFY_TYPE_COMMENT,
verifyCode);
System.out.println("verifyCode=" + verifyCode);
// 输出验证码给客户端
response.setContentType("image/jpeg");
/*
* textCode 文本验证码 width 图片宽度 height 图片高度 interLine 图片中干扰线的条数
* randomLocation 每个字符的高低位置是否随机 backColor 图片颜色,若为null,则采用随机颜色 f
* oreColor字体颜色,若为null,则采用随机颜色 lineColor 干扰线颜色,若为null,则采用随机颜色
*/
BufferedImage bim = VerifyCode.generateImageCode(verifyCode, 65, 22, 8,
true, Color.WHITE, Color.BLACK, null);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bim, "JPEG", out);
log.info("验证码已经生成并存入session中");
try {
out.flush();
log.info("刷新验证码图片");
} finally {
out.close();
log.info("关闭验证码流");
}
}
}
 package com.etop.controller;

 import java.util.HashMap;
import java.util.Map; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.etop.basic.controller.BaseController;
import com.etop.dto.PermissionDto;
import com.etop.pojo.Permission;
import com.etop.service.PermissionService;
import com.etop.utils.PageUtil; /**
* @类名: PermissionController
* @描述: 处理用户权限的控制器
* @作者 liuren-mail@163.com
* @日期 2015年5月27日 下午3:28:09
*/
@Controller
@RequestMapping("/permission")
public class PermissionController extends BaseController {
Map<String,Object> map = new HashMap<String,Object>();
private final static Logger log = Logger
.getLogger(PermissionController.class);
@Autowired
private PermissionService permissionService; @RequestMapping("/permissonList.html")
public String getPermissons() {
log.info("/permissionList.html");
return "/permissonList.jsp";
} /**
* @标题: getPermissionList
* @描述: 返回分页的json数据
* @参数 @return 设定文件
* @返回 Object 返回类型
* @throws
* @作者 liuren-mail@163.com
* @日期 2015年5月27日 下午3:33:27
*/
@RequestMapping("/get_permissions.html")
@ResponseBody
public Object getPermissionList() {
log.info("/get_permission.html");
PageUtil<PermissionDto> permissionList = permissionService
.findAllPermisson();
return permissionList;
} @RequestMapping("/add.html")
@ResponseBody
public Object addPermission(String permissionname) {
log.info("/add.html");
if (permissionname==null||"".equals(permissionname)) {
map.put("success", false);
return map;
}
Permission permission = new Permission();
permission.setPermissionname(permissionname);
permissionService.savePermission(permission);
map.put("success", true);
return map;
} @RequestMapping("/edit.html")
@ResponseBody
public Object updatePermission(int id,String permissionname) {
log.info("/edit.html");
Permission permission =permissionService.findPermissionById(id);
if (permission==null||"".equals(permission)) {
map.put("success", false);
}
permission.setPermissionname(permissionname);
permissionService.updatePermission(permission);
map.put("success", true);
return map;
} @RequestMapping("/del.html")
@ResponseBody
public Object deletePermission(int id) {
log.info("/del.html");
Permission permission = permissionService.findPermissionById(id);
if (permission==null||"".equals(permission)) {
map.put("success", false);
return map;
}
permissionService.deletePermission(id);
map.put("success", true);
return map;
}
}
 package com.etop.controller;

 import java.util.HashMap;
import java.util.Map; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.etop.basic.controller.BaseController;
import com.etop.dto.RoleDto;
import com.etop.pojo.Role;
import com.etop.service.RoleService;
import com.etop.utils.PageUtil; /**
* @类名: RoleController
* @描述: 处理角色操作的控制器
* @作者 liuren-mail@163.com
* @日期 2015年5月26日 下午6:09:03
*/
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {
Map<String,Object> map = new HashMap<String,Object>();
private final static Logger log = Logger.getLogger(RoleController.class);
@Autowired
private RoleService roleService; @RequestMapping("/roleList.html")
public String getRoles() {
log.info("/roleList.html");
return "/roleList.jsp";
} /**
* @标题: getRoleList
* @描述: 返回json数据
* @参数 @return 设定文件
* @返回 Object 返回类型
* @throws
* @作者 liuren-mail@163.com
* @日期 2015年5月27日 下午3:56:39
*/
@RequestMapping("/get_roles.html")
@ResponseBody
public Object getRoleList() {
log.info("/get_roles.html");
PageUtil<RoleDto> roleList = roleService.findAllRole();
return roleList;
} @RequestMapping("/add.html")
@ResponseBody
public Object addRole(String rolename,String description) {
log.info("/add.html");
Role role = new Role();
if (rolename==null||description==null||"".equals(rolename)||"".equals(description)) {
map.put("success", false);
return map;
}
role.setRolename(rolename);
role.setDescription(description);
roleService.saveRole(role);
map.put("success", true);
return map;
} @RequestMapping("/edit.html")
@ResponseBody
public Object updateRole(int id,String rolename,String description) {
log.info("/edit.html");
Role role = roleService.findById(id);
if (role==null||"".equals(role)) {
map.put("success", false);
}
role.setRolename(rolename);
role.setDescription(description);
roleService.updateRole(role);
map.put("success", true);
return map;
} @RequestMapping("/del.html")
@ResponseBody
public Object deleteRole(int id) {
log.info("/del.html");
roleService.deleteRole(id);
map.put("success", true);
return map;
} @RequestMapping("/roleTest.html")
public String testRole() {
log.info("roleTest.html");
return "/success.jsp";
}
}
 package com.etop.controller;

 import java.util.HashMap;
import java.util.Map; import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.etop.basic.controller.BaseController;
import com.etop.dto.UserDto;
import com.etop.pojo.User;
import com.etop.service.UserService;
import com.etop.utils.MD5Utils;
import com.etop.utils.PageUtil; /**
* @类名: UserController
* @描述: 处理用户操作的控制器
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:10:19
*/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
Map<String, Object> map = new HashMap<String, Object>();
private final static Logger log = Logger.getLogger(UserController.class);
private UserService userService; @Autowired
public void setUserService(UserService userService) {
this.userService = userService;
} // add,edit,del页面并没有写具体逻辑,要验证是否成功,需要观察控制台输出。
@RequestMapping(value = "/get_users.html")
@ResponseBody
public Object getUsers() {
log.info("/get_users.html");
PageUtil<UserDto> pageList = userService.findAllUser();
return pageList;
} @RequestMapping("/userList.html")
public String userList() {
log.info("/userList.html");
return "/userList.jsp";
} @RequestMapping("/add.html")
@ResponseBody
public Object addUser(String username, String password) {
log.info("/add.html");
MD5Utils MD5 = new MD5Utils();
User user = new User();
if (username == null || password == null || "".equals(username)
|| "".equals(password)) {
map.put("success", false);
}
String md5_password = MD5.GetMD5Code(password);
user.setUsername(username);
user.setPassword(md5_password);
userService.saveUser(user);
map.put("success", true);
return map;
} @RequestMapping("/edit.html")
@ResponseBody
public Object updateUser(int id, String username, String password) {
log.info("/edit.html");
MD5Utils MD5 = new MD5Utils();
User user = userService.findById(id);
if (user == null || "".equals(user)) {
map.put("success", false);
return map;
}
String md5_password = MD5.GetMD5Code(password);
user.setUsername(username);
user.setPassword(md5_password);
userService.updateUser(user);
map.put("success", true);
System.out.println("=========================================>要修改的id为:"
+ id);
return map;
} @ResponseBody
@RequestMapping(value = "/del.html")
public Object deleteUser(int id) {
log.info("/del.html");
userService.deleteUser(id);
map.put("success", true);
System.out.println("=========================================>要删除的id为:"
+ id);
return map;
}
}

项目的dao层:

 package com.etop.dao;

 import com.etop.basic.dao.BaseDAO;
import com.etop.pojo.Function; import org.springframework.stereotype.Repository; /**
* @类名: FunctionDAO
* @描述: TODO(这里用一句话描述这个类的作用)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:01:38
*/
@SuppressWarnings("serial")
@Repository("FunctionDAO")
public class FunctionDAO extends BaseDAO<Function> {
}
 package com.etop.dao;

 import com.etop.basic.dao.BaseDAO;
import com.etop.pojo.Permission; import org.springframework.stereotype.Repository; /**
* @类名: PermissionDAO
* @描述: TODO(这里用一句话描述这个类的作用)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:04:50
*/
@SuppressWarnings("serial")
@Repository("PermissionDAO")
public class PermissionDAO extends BaseDAO<Permission> {
}
 package com.etop.dao;

 import com.etop.basic.dao.BaseDAO;
import com.etop.pojo.Role; import org.springframework.stereotype.Repository; /**
* @类名: RoleDAO
* @描述: TODO(这里用一句话描述这个类的作用)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:05:28
*/
@SuppressWarnings("serial")
@Repository("RoleDAO")
public class RoleDAO extends BaseDAO<Role> {
}
 package com.etop.dao;

 import com.etop.basic.dao.BaseDAO;
import com.etop.pojo.User; import org.springframework.stereotype.Repository; /**
* @类名: UserDAO
* @描述: TODO(这里用一句话描述这个类的作用)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:05:41
*/
@SuppressWarnings("serial")
@Repository("UserDAO")
public class UserDAO extends BaseDAO<User> {
}

项目的DTO层:

 package com.etop.dto;

 public class FunctionDto {

     private Integer id;
private String value;
private Integer permission_id;
private Integer role_id;
private String type; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public Integer getPermission_id() {
return permission_id;
} public void setPermission_id(Integer permission_id) {
this.permission_id = permission_id;
} public Integer getRole_id() {
return role_id;
} public void setRole_id(Integer role_id) {
this.role_id = role_id;
} public String getType() {
return type;
} public void setType(String type) {
this.type = type;
} }
 package com.etop.dto;

 public class PermissionDto {

     private Integer id;
private String permissionname;
private String role;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPermissionname() {
return permissionname;
}
public void setPermissionname(String permissionname) {
this.permissionname = permissionname;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
} }
 package com.etop.dto;

 public class RoleDto {

     private Integer id;
private String rolename;
private String description;
private String permissionList;
private String userList; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getRolename() {
return rolename;
} public void setRolename(String rolename) {
this.rolename = rolename;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} public String getPermissionList() {
return permissionList;
} public void setPermissionList(String permissionList) {
this.permissionList = permissionList;
} public String getUserList() {
return userList;
} public void setUserList(String userList) {
this.userList = userList;
} }
 package com.etop.dto;

 public class UserDto {

     private Integer id;
private String username;
private String password;
private String roleList; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getRoleList() {
return roleList;
} public void setRoleList(String roleList) {
this.roleList = roleList;
} }

项目的model层

 package com.etop.pojo;

 import javax.persistence.*;

 import java.io.Serializable;

 /**
* @类名: Function
* @描述: 网页过滤信息类,保存网页过滤信息,以及对应的权限(一对一)或角色(一对一)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:07:03
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "t_function")
public class Function implements Serializable {
/**
* 这个是id
*/
private Integer id;
/**
* 这个是过滤的url
*/
private String value;
// private Permission permission;
// private Role role;
private int permission_id;
private int role_id;
private String type; public Function() {
super();
} // public Function(Integer id, String value, Permission permission, Role role,
// String type) {
// super();
// this.id = id;
// this.value = value;
// this.permission = permission;
// this.role = role;
// this.type = type;
// }
public Function(Integer id, String value, int permission_id, int role_id,
String type) {
super();
this.id = id;
this.value = value;
this.permission_id = permission_id;
this.role_id = role_id;
this.type = type;
} @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} // @OneToOne
// @JoinColumn(name = "permission_id")
// public Permission getPermission() {
// return permission;
// }
//
// public void setPermission(Permission permission) {
// this.permission = permission;
// }
//
// @OneToOne
// @JoinColumn(name = "role_id")
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
public int getPermission_id() {
return permission_id;
} public void setPermission_id(int permission_id) {
this.permission_id = permission_id;
} public int getRole_id() {
return role_id;
} public void setRole_id(int role_id) {
this.role_id = role_id;
} public String getType() {
return type;
} public void setType(String type) {
this.type = type;
}
}
 package com.etop.pojo;

 import java.io.Serializable;

 import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table; /**
* @类名: Permission
* @描述: 权限类,保存权限信息与对应的角色(多对一)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 上午11:26:31
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "t_permission")
public class Permission implements Serializable { private Integer id;
private String permissionname;
private Role role;
public Permission() {
super();
} public Permission(Integer id, String permissionname, Role role) {
super();
this.id = id;
this.permissionname = permissionname;
this.role = role;
} @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getPermissionname() {
return permissionname;
} public void setPermissionname(String permissionname) {
this.permissionname = permissionname;
} @ManyToOne(targetEntity = Role.class)
@JoinTable(name = "t_role_permission", joinColumns = { @JoinColumn(name = "permission_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
public Role getRole() {
return role;
} public void setRole(Role role) {
this.role = role;
}
}
 package com.etop.pojo;

 import javax.persistence.*;

 import org.codehaus.jackson.annotate.JsonIgnore;

 import java.io.Serializable;
import java.util.HashSet;
import java.util.Set; /**
* @类名: Role
* @描述: 角色类,用于保存角色信息、用户列表(多对多)与角色(一对多)对应的权限
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:07:42
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "t_role")
public class Role implements Serializable { private Integer id;
private String rolename;
private String description;
private Set<Permission> permissionList;
private Set<User> userList; public Role() {
super();
} public Role(Integer id, String rolename, Set<Permission> permissionList,
Set<User> userList) {
super();
this.id = id;
this.rolename = rolename;
this.permissionList = permissionList;
this.userList = userList;
} @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getRolename() {
return rolename;
} public void setRolename(String rolename) {
this.rolename = rolename;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} @OneToMany(targetEntity = Permission.class, cascade = {
CascadeType.PERSIST, CascadeType.MERGE })
@JsonIgnore
// 防止无限循环
@JoinTable(name = "t_role_permission", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "permission_id") })
public Set<Permission> getPermissionList() {
return permissionList;
} public void setPermissionList(Set<Permission> permissionList) {
this.permissionList = permissionList;
} @ManyToMany(targetEntity = com.etop.pojo.User.class, cascade = {
CascadeType.PERSIST, CascadeType.MERGE })
@JsonIgnore
// 防止无限循环
@JoinTable(name = "t_user_role", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "user_id") })
public Set<User> getUserList() {
return userList;
} public void setUserList(Set<User> userList) {
this.userList = userList;
} @Transient
public Set<String> getPermissionsName() {
Set<String> list = new HashSet<>();
Set<Permission> perlist = getPermissionList();
for (Permission per : perlist) {
list.add(per.getPermissionname());
}
return list;
} private class User {
} }
 package com.etop.pojo;

 import org.codehaus.jackson.annotate.JsonIgnore;
import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.*; import java.io.Serializable;
import java.util.HashSet;
import java.util.Set; /**
* @类名: User
* @描述: 用户类,保存用户信息与角色(多对多)
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:08:11
*/
@SuppressWarnings("serial")
@Entity
@Table(name = "t_user")
public class User implements Serializable { private Integer id;
@NotEmpty(message = "用户名不能为空")
private String username;
@NotEmpty(message = "密码不能为空")
private String password;
private Set<Role> roleList; @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} @ManyToMany(fetch = FetchType.EAGER)
@JsonIgnore
// 防止无限循环
@JoinTable(name = "t_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") })
public Set<Role> getRoleList() {
return roleList;
} public void setRoleList(Set<Role> roleList) {
this.roleList = roleList;
} @Transient
public Set<String> getRolesName() {
Set<Role> roles = getRoleList();
Set<String> set = new HashSet<String>();
for (Role role : roles) {
set.add(role.getRolename());
}
return set;
} public User() {
super();
} public User(Integer id, String username, String password, Set<Role> roleList) {
super();
this.id = id;
this.username = username;
this.password = password;
this.roleList = roleList;
}
}

项目的service层:

 package com.etop.service;

 import com.etop.dao.FunctionDAO;
import com.etop.dto.FunctionDto;
import com.etop.pojo.Function;
import com.etop.utils.PageUtil; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* @类名: FunctionService
* @描述: 网页过滤服务,与dao进行对接
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 上午11:46:22
*/
@SuppressWarnings("serial")
@Service("FunctionService")
public class FunctionService implements Serializable { @Autowired
private FunctionDAO functionDAO; /**
* 查找所有权限过滤信息
*
* @return
*/
public List<Function> findAll() {
return functionDAO.find("from Function f");
} @Transactional
public PageUtil<FunctionDto> findAllFunction() {
return functionDAO.findBySql("select * from t_function",
FunctionDto.class, false);
} public void saveFunction(Function function) {
functionDAO.save(function);
} public Function findFunctionById(int id) {
Map<String,Object> params = new HashMap<String,Object>();
params.put("id", id);
return functionDAO.findUniqueResult("from Function f where f.id= :id", params);
} public void updateFunction(Function function) {
functionDAO.saveOrUpdate(function);
} public void deleteFunction(int id) {
functionDAO.deleteById(id);
}
}
 package com.etop.service;

 import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.etop.dao.PermissionDAO;
import com.etop.dto.PermissionDto;
import com.etop.pojo.Permission;
import com.etop.utils.PageUtil; /**
* @类名: PermissionService
* @描述: 权限服务和DAO对接
* @作者 liuren-mail@163.com
* @日期 2015年5月27日 下午3:58:27
*/
@SuppressWarnings("serial")
@Service
public class PermissionService implements Serializable { @Autowired
private PermissionDAO permissionDAO; public List<Permission> findAll(){
return permissionDAO.find("from Permission p");
}
@Transactional
public PageUtil<PermissionDto> findAllPermisson() {
return permissionDAO.findBySql("select * from t_permission",
PermissionDto.class, false);
} public void savePermission(Permission permission) {
permissionDAO.save(permission);
} public Permission findPermissionById(int id) {
Map<String,Object> params = new HashMap<String,Object>();
params.put("id", id);
return permissionDAO.findUniqueResult("from Permission p where p.id= :id", params);
} public void updatePermission(Permission permission) {
permissionDAO.saveOrUpdate(permission);
} public void deletePermission(int id) {
permissionDAO.deleteById(id);
}
public String getNameById(int permission_id) {
Map<String,Object> params = new HashMap<String,Object>();
params.put("id", permission_id);
Permission permission = permissionDAO.findUniqueResult("from Permission p where p.id= :id", params);
String name =permission.getPermissionname();
return name;
} }
 package com.etop.service;

 import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.etop.dao.RoleDAO;
import com.etop.dto.RoleDto;
import com.etop.pojo.Role;
import com.etop.utils.PageUtil;
/**
* @类名: RoleService
* @描述: 角色服务和DAO对接
* @作者 liuren-mail@163.com
* @日期 2015年5月26日 下午5:20:03
*/
@SuppressWarnings("serial")
@Service
public class RoleService implements Serializable{ @Autowired
private RoleDAO roleDAO; @Transactional
public List<Role> getAllRole() {
return roleDAO.find("from Role r");
} @Transactional
public PageUtil<RoleDto> findAllRole() {
return roleDAO.findBySql("select * from t_role", RoleDto.class, false);
} public Role findById(int id) {
Map<String,Object> params = new HashMap<String,Object>();
params.put("id", id);
return roleDAO.findUniqueResult("from Role r where r.id= :id", params);
} public void updateRole(Role role) {
roleDAO.saveOrUpdate(role);
} public void saveRole(Role role) {
roleDAO.save(role);
} public void deleteRole(int id) {
roleDAO.deleteById(id);
} public String getNameById(int role_id) {
Map<String,Object> params = new HashMap<String,Object>();
params.put("id", role_id);
Role role =roleDAO.findUniqueResult("from Role r where r.id= :id", params);
String rolename = role.getRolename();
return rolename;
}
}
 package com.etop.service;

 import com.etop.dao.UserDAO;
import com.etop.dto.UserDto;
import com.etop.pojo.User;
import com.etop.utils.PageUtil; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* @类名: UserService
* @描述: 用户服务,与dao进行对接
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:03:20
*/
@SuppressWarnings("serial")
@Service("UserService")
public class UserService implements Serializable { @Autowired
private UserDAO userDAO; /**
* 通过用户名查找用户信息
*
* @param username
* @return
*/
public User findByName(String username) {
Map<String, Object> params = new HashMap<>();
params.put("name", username);
return userDAO.findUniqueResult("from User u where u.username = :name",
params);
} public List<User> getAllUser() {
return userDAO.find("from User u");
} public PageUtil<UserDto> findAllUser() {
return userDAO.findBySql("select * from t_user", UserDto.class, false);
} public void saveUser(User user) {
userDAO.save(user);
} public User findById(int id) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("id", id);
return userDAO.findUniqueResult("from User u where u.id = :id", params);
} public void updateUser(User user) {
userDAO.saveOrUpdate(user);
} public void deleteUser(int id) {
userDAO.deleteById(id);
}
}

项目的shiro层代码:

 package com.etop.shiro;

 import com.etop.pojo.Function;
import com.etop.service.FunctionService;
import com.etop.service.PermissionService;
import com.etop.service.RoleService; import org.apache.commons.lang.StringUtils;
import org.apache.shiro.config.Ini;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired; import java.util.Iterator;
import java.util.List; /**
* @类名: ChainDefinitionSectionMetaSource
* @描述: 产生责任链,确定每个url的访问权限
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午3:12:53
*/
public class ChainDefinitionSectionMetaSource implements
FactoryBean<Ini.Section> { @Autowired
private FunctionService functionService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService;
// 静态资源访问权限
private String filterChainDefinitions = "/static/**=anon"; @Override
public Ini.Section getObject() throws Exception {
List<Function> list = functionService.findAll();
Ini ini = new Ini();
// 加载默认的url
ini.load(filterChainDefinitions);
Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
// 循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
// 里面的键就是链接URL,值就是存在什么条件才能访问该链接
for (Iterator<Function> it = list.iterator(); it.hasNext();) {
Function function = it.next();
int permission_id = function.getPermission_id();
int role_id = function.getRole_id();
// 构成permission字符串
if (StringUtils.isNotEmpty(function.getValue())
&& StringUtils.isNotEmpty(function.getType())) {
String permission = "";
switch (function.getType()) {
case "anon":
permission = "anon";
break;
case "perms":
permission = "perms["
+ permissionService.getNameById(permission_id)//function.getPermission().getPermissionname()
+ "]";
break;
case "roles":
permission = "roles["
+ roleService.getNameById(role_id)//function.getRole().getRolename()
+ "]";
break;
default:
break;
}
section.put(function.getValue(), permission);
} }
// 所有资源的访问权限,必须放在最后
section.put("/**", "authc");
return section;
} @Override
public Class<?> getObjectType() {
return this.getClass();
} @Override
public boolean isSingleton() {
return false;
}
}
 package com.etop.shiro;

 import java.util.Collection;

 import javax.inject.Inject;

 import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.etop.pojo.Role;
import com.etop.pojo.User;
import com.etop.service.UserService; /**
* @类名: MyRealm
* @描述: 自定义Realm,进行数据源配置
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 上午11:50:21
*/ @Service
@Transactional
public class MyRealm extends AuthorizingRealm { @Inject
private UserService userService; /**
* 获取授权信息
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principalCollection) {
// 获取登录时输入的用户名
String loginName = (String) principalCollection.fromRealm(getName())
.iterator().next();
// 到数据库获取此用户
User user = userService.findByName(loginName);
if (user != null) {
// 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 用户的角色集合
info.setRoles(user.getRolesName());
// 用户的角色对应的所有权限,如果只使用角色定义访问权限
Collection<Role> roleList = user.getRoleList();
for (Role role : roleList) {
info.addStringPermissions(role.getPermissionsName());
}
return info;
}
return null;
} /**
* 获取身份验证相关信息
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authenticationToken)
throws AuthenticationException {
// UsernamePasswordToken对象用来存放提交的登录信息
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
// 查出是否有此用户
User user = userService.findByName(token.getUsername());
if (user != null) {
// 若存在,将此用户存放到登录认证info中
return new SimpleAuthenticationInfo(user.getUsername(),
user.getPassword(), getName());
}
return null;
} }

项目的工具类:

 package com.etop.utils;

 import org.apache.commons.lang.time.DateFormatUtils;

 import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; /**
* @类名: DateUtils
* @描述: 比较两个日期相差的月份数
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 下午2:47:06
*/
public class DateUtils extends org.apache.commons.lang.time.DateUtils { public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private static String[] parsePatterns = { "yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }; /**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
} /**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
} /**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
} /**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
} /**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
} /**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
} /**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
} /**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
} /**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
} /**
* 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
} /**
* 获取过去的天数
*
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime() - date.getTime();
return t / (24 * 60 * 60 * 1000);
} public static int getMonthSpace(Timestamp source, Timestamp target) {
int result = 0; Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance(); c1.setTime(new Date(source.getTime()));
c2.setTime(new Date(target.getTime())); result = c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH); return result == 0 ? 0 : result;
} public static Timestamp addDay(Timestamp source, int amount) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(source.getTime());
c.add(Calendar.DAY_OF_MONTH, amount);
return new Timestamp(c.getTimeInMillis());
}
}
 package com.etop.utils;

 import net.sf.json.JSONObject;

 public class JsonTools {
/**
* 得到一个json类型的字符串对象
*
* @param key
* @param value
* @return
*/
public static String getJsonString(String key, Object value) {
JSONObject jsonObject = new JSONObject();
// put和element都是往JSONObject对象中放入 key/value 对
// jsonObject.put(key, value);
jsonObject.element(key, value);
return jsonObject.toString();
} /**
* 得到一个json对象
*
* @param key
* @param value
* @return
*/
public static JSONObject getJsonObject(String key, Object value) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject;
} }
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"));
}
}
 package com.etop.utils;

 import java.util.List;

 public class PageUtil<T> {

     // /**
// * 分页的大小
// */
// private int size;//page*limit
// /**
// * 分页的起始页
// */
// private int offset;//start
// /**
// * 总记录数
// */
private long total;
/**
* 分页的数据
*/
private List<T> rows; // public int getSize() {
// return size;
// }
// public void setSize(int size) {
// this.size = size;
// }
// public int getOffset() {
// return offset;
// }
// public void setOffset(int offset) {
// this.offset = offset;
// }
public long getTotal() {
return total;
} public void setTotal(long total) {
this.total = total;
} public List<T> getRows() {
return rows;
} public void setRows(List<T> rows) {
this.rows = rows;
} }
 package com.etop.utils;

 import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; /**
* @类名: SpringContextHolder
* @描述: 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
* @作者 liuren-mail@163.com
* @日期 2015年5月20日 上午11:49:42
*/
public class SpringContextHolder implements ApplicationContextAware,
DisposableBean { private static ApplicationContext applicationContext = null;
private static Logger logger = Logger.getLogger(SpringContextHolder.class); /**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
} /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
} /**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
logger.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
} /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
if (SpringContextHolder.applicationContext != null) {
logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:"
+ SpringContextHolder.applicationContext);
}
SpringContextHolder.applicationContext = applicationContext; // NOSONAR
} /**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
} /**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.isTrue(applicationContext != null,
"applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}
 package com.etop.utils;
/**
* 用来传递列表对象的ThreadLocal数据
* @author Administrator
*
*/
public class ThreadLocalUtils {
/**
* 分页大小
*/
private static ThreadLocal<Integer> pageSize = new ThreadLocal<Integer>();
/**
* 分页的起始页
*/
private static ThreadLocal<Integer> pageOffset = new ThreadLocal<Integer>();
/**
* 列表的排序字段
*/
private static ThreadLocal<String> sort = new ThreadLocal<String>();
/**
* 列表的排序方式
*/
private static ThreadLocal<String> order = new ThreadLocal<String>(); private static ThreadLocal<String> realPath = new ThreadLocal<String>();
/*
private static ThreadLocal<String> query = new ThreadLocal<String>(); public static String getQuery() {
return query.get();
}
public static void setQuery(String _query) {
SystemContext.query.set(_query);
}*/
public static String getRealPath() {
return realPath.get();
}
public static void setRealPath(String _realPath) {
ThreadLocalUtils.realPath.set(_realPath);
}
public static Integer getPageSize() {
return pageSize.get();
}
public static void setPageSize(Integer _pageSize) {
pageSize.set(_pageSize);
}
public static Integer getPageOffset() {
return pageOffset.get();
}
public static void setPageOffset(Integer _pageOffset) {
pageOffset.set(_pageOffset);
}
public static String getSort() {
return sort.get();
}
public static void setSort(String _sort) {
ThreadLocalUtils.sort.set(_sort);
}
public static String getOrder() {
return order.get();
}
public static void setOrder(String _order) {
ThreadLocalUtils.order.set(_order);
} public static void removePageSize() {
pageSize.remove();
} public static void removePageOffset() {
pageOffset.remove();
} public static void removeSort() {
sort.remove();
} public static void removeOrder() {
order.remove();
} public static void removeRealPath() {
realPath.remove();
} /*public static void removeQuery(){
query.remove();
}*/
}
 package com.etop.utils;

 import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*; import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.disk.DiskFileItemFactory; import sun.misc.BASE64Decoder; import javax.servlet.http.HttpServletRequest; /**
* UEditor文件上传辅助类
*
*/
@SuppressWarnings("restriction")
public class Uploader {
// 输出文件地址
private String url = "";
// 上传文件名
private String fileName = "";
// 状态
private String state = "";
// 文件类型
private String type = "";
// 原始文件名
private String originalName = "";
// 文件大小
private String size = ""; private HttpServletRequest request = null;
private String title = ""; // 保存路径
private String savePath = "upload";
// 文件允许格式
private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",
".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
// 文件大小限制,单位KB
private int maxSize = 10000; private HashMap<String, String> errorInfo = new HashMap<String, String>(); public Uploader(HttpServletRequest request) {
this.request = request;
HashMap<String, String> tmp = this.errorInfo;
tmp.put("SUCCESS", "SUCCESS"); // 默认成功
tmp.put("NOFILE", "未包含文件上传域");
tmp.put("TYPE", "不允许的文件格式");
tmp.put("SIZE", "文件大小超出限制");
tmp.put("ENTYPE", "请求类型ENTYPE错误");
tmp.put("REQUEST", "上传请求异常");
tmp.put("IO", "IO异常");
tmp.put("DIR", "目录创建失败");
tmp.put("UNKNOWN", "未知错误"); } public void upload() throws Exception {
boolean isMultipart = ServletFileUpload
.isMultipartContent(this.request);
if (!isMultipart) {
this.state = this.errorInfo.get("NOFILE");
return;
}
DiskFileItemFactory dff = new DiskFileItemFactory();
String savePath = this.getFolder(this.savePath);
dff.setRepository(new File(savePath));
try {
ServletFileUpload sfu = new ServletFileUpload(dff);
sfu.setSizeMax(this.maxSize * 1024);
sfu.setHeaderEncoding("utf-8");
FileItemIterator fii = sfu.getItemIterator(this.request);
while (fii.hasNext()) {
FileItemStream fis = fii.next();
if (!fis.isFormField()) {
this.originalName = fis.getName().substring(
fis.getName().lastIndexOf(
System.getProperty("file.separator")) + 1);
if (!this.checkFileType(this.originalName)) {
this.state = this.errorInfo.get("TYPE");
continue;
}
this.fileName = this.getName(this.originalName);
this.type = this.getFileExt(this.fileName);
this.url = savePath + "/" + this.fileName;
BufferedInputStream in = new BufferedInputStream(
fis.openStream());
FileOutputStream out = new FileOutputStream(new File(
this.getPhysicalPath(this.url)));
BufferedOutputStream output = new BufferedOutputStream(out);
Streams.copy(in, output, true);
this.state = this.errorInfo.get("SUCCESS");
// UE中只会处理单张上传,完成后即退出
break;
} else {
String fname = fis.getFieldName();
// 只处理title,其余表单请自行处理
if (!fname.equals("pictitle")) {
continue;
}
BufferedInputStream in = new BufferedInputStream(
fis.openStream());
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuffer result = new StringBuffer();
while (reader.ready()) {
result.append((char) reader.read());
}
this.title = new String(result.toString().getBytes(),
"utf-8");
reader.close(); }
}
} catch (SizeLimitExceededException e) {
this.state = this.errorInfo.get("SIZE");
} catch (InvalidContentTypeException e) {
this.state = this.errorInfo.get("ENTYPE");
} catch (FileUploadException e) {
this.state = this.errorInfo.get("REQUEST");
} catch (Exception e) {
this.state = this.errorInfo.get("UNKNOWN");
}
} /**
* 接受并保存以base64格式上传的文件
*
* @param fieldName
*/
public void uploadBase64(String fieldName) {
String savePath = this.getFolder(this.savePath);
String base64Data = this.request.getParameter(fieldName);
this.fileName = this.getName("test.png");
this.url = savePath + "/" + this.fileName;
BASE64Decoder decoder = new BASE64Decoder();
try {
File outFile = new File(this.getPhysicalPath(this.url));
OutputStream ro = new FileOutputStream(outFile);
byte[] b = decoder.decodeBuffer(base64Data);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
ro.write(b);
ro.flush();
ro.close();
this.state = this.errorInfo.get("SUCCESS");
} catch (Exception e) {
this.state = this.errorInfo.get("IO");
}
} /**
* 文件类型判断
*
* @param fileName
* @return
*/
private boolean checkFileType(String fileName) {
Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
} /**
* 获取文件扩展名
*
* @return string
*/
private String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
} /**
* 依据原始文件名生成新文件名
*
* @return
*/
private String getName(String fileName) {
Random random = new Random();
return this.fileName = "" + random.nextInt(10000)
+ System.currentTimeMillis() + this.getFileExt(fileName);
} /**
* 根据字符串创建本地目录 并按照日期建立子目录返回
*
* @param path
* @return
*/
private String getFolder(String path) {
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
path += "/" + formater.format(new Date());
File dir = new File(this.getPhysicalPath(path));
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
this.state = this.errorInfo.get("DIR");
return "";
}
}
return path;
} /**
* 根据传入的虚拟路径获取物理路径
*
* @param path
* @return
*/
private String getPhysicalPath(String path) {
String servletPath = this.request.getServletPath();
String realPath = this.request.getSession().getServletContext()
.getRealPath(servletPath);
return new File(realPath).getParent() + "/" + path;
} public void setSavePath(String savePath) {
this.savePath = savePath;
} public void setAllowFiles(String[] allowFiles) {
this.allowFiles = allowFiles;
} public void setMaxSize(int size) {
this.maxSize = size;
} public String getSize() {
return this.size;
} public String getUrl() {
return this.url;
} public String getFileName() {
return this.fileName;
} public String getState() {
return this.state;
} public String getTitle() {
return this.title;
} public String getType() {
return this.type;
} public String getOriginalName() {
return this.originalName;
}
}
 package com.etop.utils;

 import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random; /**
* 验证码生成器类,可生成数字、大写、小写字母及三者混合类型的验证码。 支持自定义验证码字符数量; 支持自定义验证码图片的大小; 支持自定义需排除的特殊字符;
* 支持自定义干扰线的数量; 支持自定义验证码图文颜色
*
* @author org.javachina
* @version 1.01
*/
public class VerifyCode { // 验证码类型,评论
public static final String VERIFY_TYPE_COMMENT = "VERIFY_TYPE_COMMENT"; /**
* 验证码类型为仅数字 0~9
*/
public static final int TYPE_NUM_ONLY = 0; /**
* 验证码类型为仅字母,即大写、小写字母混合
*/
public static final int TYPE_LETTER_ONLY = 1; /**
* 验证码类型为数字、大写字母、小写字母混合
*/
public static final int TYPE_ALL_MIXED = 2; /**
* 验证码类型为数字、大写字母混合
*/
public static final int TYPE_NUM_UPPER = 3; /**
* 验证码类型为数字、小写字母混合
*/
public static final int TYPE_NUM_LOWER = 4; /**
* 验证码类型为仅大写字母
*/
public static final int TYPE_UPPER_ONLY = 5; /**
* 验证码类型为仅小写字母
*/
public static final int TYPE_LOWER_ONLY = 6; private VerifyCode() {
} /**
* 生成验证码字符串
*
* @param type
* 验证码类型,参见本类的静态属性
* @param length
* 验证码长度,大于0的整数
* @param exChars
* 需排除的特殊字符(仅对数字、字母混合型验证码有效,无需排除则为null)
* @return 验证码字符串
*/
public static String generateTextCode(int type, int length, String exChars) { if (length <= 0)
return ""; StringBuffer code = new StringBuffer();
int i = 0;
Random r = new Random(); switch (type) { // 仅数字
case TYPE_NUM_ONLY:
while (i < length) {
int t = r.nextInt(10);
if (exChars == null || exChars.indexOf(t + "") < 0) {// 排除特殊字符
code.append(t);
i++;
}
}
break; // 仅字母(即大写字母、小写字母混合)
case TYPE_LETTER_ONLY:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97 || (t >= 65 && t <= 90))
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break; // 数字、大写字母、小写字母混合
case TYPE_ALL_MIXED:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97 || (t >= 65 && t <= 90) || (t >= 48 && t <= 57))
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break; // 数字、大写字母混合
case TYPE_NUM_UPPER:
while (i < length) {
int t = r.nextInt(91);
if ((t >= 65 || (t >= 48 && t <= 57))
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break; // 数字、小写字母混合
case TYPE_NUM_LOWER:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97 || (t >= 48 && t <= 57))
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break; // 仅大写字母
case TYPE_UPPER_ONLY:
while (i < length) {
int t = r.nextInt(91);
if ((t >= 65)
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break; // 仅小写字母
case TYPE_LOWER_ONLY:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97)
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break; } return code.toString();
} /**
* 已有验证码,生成验证码图片
*
* @param textCode
* 文本验证码
* @param width
* 图片宽度
* @param height
* 图片高度
* @param interLine
* 图片中干扰线的条数
* @param randomLocation
* 每个字符的高低位置是否随机
* @param backColor
* 图片颜色,若为null,则采用随机颜色
* @param foreColor
* 字体颜色,若为null,则采用随机颜色
* @param lineColor
* 干扰线颜色,若为null,则采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage generateImageCode(String textCode, int width,
int height, int interLine, boolean randomLocation, Color backColor,
Color foreColor, Color lineColor) { BufferedImage bim = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = bim.getGraphics();
// 画背景图
g.setColor(backColor == null ? getRandomColor() : backColor);
g.fillRect(0, 0, width, height); // 画干扰线
Random r = new Random();
if (interLine > 0) { int x = 0, y = 0, x1 = width, y1 = 0;
for (int i = 0; i < interLine; i++) {
g.setColor(lineColor == null ? getRandomColor() : lineColor);
y = r.nextInt(height);
y1 = r.nextInt(height); g.drawLine(x, y, x1, y1);
}
} // 写验证码 // g.setColor(getRandomColor());
// g.setColor(isSimpleColor?Color.BLACK:Color.WHITE); // 字体大小为图片高度的80%
int fsize = (int) (height * 0.8);
int fx = height - fsize;
int fy = fsize; g.setFont(new Font("Times New Roman", Font.BOLD, 20)); // 写验证码字符
for (int i = 0; i < textCode.length(); i++) {
fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height)
: fy;// 每个字符高低是否随机
g.setColor(foreColor == null ? getRandomColor() : foreColor);
g.drawString(textCode.charAt(i) + "", fx, fy);
fx += fsize * 0.9;
} g.dispose(); return bim;
} /**
* 生成图片验证码
*
* @param type
* 验证码类型,参见本类的静态属性
* @param length
* 验证码字符长度,大于0的整数
* @param exChars
* 需排除的特殊字符
* @param width
* 图片宽度
* @param height
* 图片高度
* @param interLine
* 图片中干扰线的条数
* @param randomLocation
* 每个字符的高低位置是否随机
* @param backColor
* 图片颜色,若为null,则采用随机颜色
* @param foreColor
* 字体颜色,若为null,则采用随机颜色
* @param lineColor
* 干扰线颜色,若为null,则采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage generateImageCode(int type, int length,
String exChars, int width, int height, int interLine,
boolean randomLocation, Color backColor, Color foreColor,
Color lineColor) { String textCode = generateTextCode(type, length, exChars);
BufferedImage bim = generateImageCode(textCode, width, height,
interLine, randomLocation, backColor, foreColor, lineColor); return bim;
} /**
* 产生随机颜色
*
* @return
*/
private static Color getRandomColor() {
Random r = new Random();
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
return c;
} public static void main(String[] args) { } }

下面是项目的配置文件:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
" default-lazy-init="true"> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
<!-- 使用下面配置的缓存管理器 -->
<property name="cacheManager" ref="cacheManager"/>
</bean>
<!--自定义Realm-->
<bean id="myRealm" class="com.etop.shiro.MyRealm"/> <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 调用我们配置的权限管理器 -->
<property name="securityManager" ref="securityManager"/>
<!-- 配置我们的登录请求地址 -->
<property name="loginUrl" value="/login.html"/>
<!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
<property name="successUrl" value="/user.html"/>
<!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
<property name="unauthorizedUrl" value="/403.html"/>
<!-- 权限配置 -->
<!-- <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource"/> -->
<property name="filterChainDefinitions">
<value>
/static/** = anon
/login.html = anon
/verifyCode.html = anon
/role/** = roles[admin]
/user/** = roles[admin]
/function/** = roles[admin]
/permission/** = roles[admin]
/** = authc
</value>
</property>
</bean>
<!--自定义filterChainDefinitionMap-->
<!-- <bean id="chainDefinitionSectionMetaSource" class="com.etop.shiro.ChainDefinitionSectionMetaSource"/> -->
<!--shiro缓存管理器-->
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties"/>
</bean> <!--hibernate session工厂设置-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com.etop.pojo</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="jdbc.use_scrollable_resultset">false</prop>
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="jdbc.use_scrollable_resultset">false</prop>
</props>
</property>
</bean> <!-- c3p0 configuration -->
<bean id="mainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="minPoolSize" value="${jdbc.minPoolSize}"/>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
<property name="checkoutTimeout" value="${jdbc.checkoutTimeout}"/>
<property name="maxStatements" value="${jdbc.maxStatements}"/>
<property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}"/>
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"/>
</bean> <bean id="dataSource"
class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<property name="targetDataSource">
<ref bean="mainDataSource"/>
</property>
</bean>
<context:annotation-config/>
<context:component-scan base-package="com.etop">
<context:exclude-filter type="regex" expression="com.cn.controller.*"/>
</context:component-scan> <bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean> <!-- 拦截配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--说明事务类别 -->
<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="batch*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="sendOpen*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="sendClose*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
<tx:method name="find*" propagation="REQUIRED" read-only="true"/>
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="load*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice> <!-- 切入点 -->
<aop:config expose-proxy="true" proxy-target-class="true">
<!-- service层事务 -->
<aop:advisor id="serviceTx" advice-ref="txAdvice"
pointcut="execution(public * com.etop.service.*.*(..))" order="1"/>
</aop:config> <tx:annotation-driven/> </beans>
 <ehcache>

     <!-- Sets the path to the directory where cache .data files are created.

          If the path is a Java System Property it is replaced by
its value in the running VM. The following properties are translated:
account.home - Account's home directory
account.dir - Account's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/> <!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager. The following attributes are required for defaultCache: maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit. -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/> <!--Predefined caches. Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts The following attributes are required for defaultCache: name - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory - Sets the maximum number of objects that will be created in memory
eternal - Sets whether elements are eternal. If eternal, timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit. -->
<!-- Place configuration for your caches following -->
<cache name="org.hibernate.cache.StandardQueryCache"
maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="4200" overflowToDisk="true" /> <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxElementsInMemory="5000"
eternal="true"
overflowToDisk="true" /> </ehcache>
 jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/shiro
jdbc.username = root
jdbc.password = root
jdbc.minPoolSize=2
jdbc.maxPoolSize=20
jdbc.checkoutTimeout=3000
jdbc.maxStatements=50
jdbc.testConnectionOnCheckin = false
jdbc.idleConnectionTestPeriod = 18000
 log4j.rootLogger=info,stdout

 log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
Hibernate
#log4j.logger.org.hibernate=debug
#log4j.logger.org.hibernate.SQL=debug

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

 /*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.5.19 : Database - shiro
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`shiro` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `shiro`; /*Table structure for table `t_function` */ DROP TABLE IF EXISTS `t_function`; CREATE TABLE `t_function` (
`id` int(11) NOT NULL,
`value` varchar(50) DEFAULT NULL,
`permission_id` int(11) DEFAULT NULL,
`role_id` int(11) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_function_role` (`role_id`),
KEY `fk_function_permission` (`permission_id`),
CONSTRAINT `fk_function_permission` FOREIGN KEY (`permission_id`) REFERENCES `t_permission` (`id`),
CONSTRAINT `fk_function_role` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_function` */ 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'); /*Table structure for table `t_permission` */ DROP TABLE IF EXISTS `t_permission`; CREATE TABLE `t_permission` (
`id` int(11) NOT NULL,
`permissionname` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_permission` */ insert into `t_permission`(`id`,`permissionname`) values (1,'user:add'),(2,'user:del'),(3,'user:update'),(4,'user:query'); /*Table structure for table `t_role` */ DROP TABLE IF EXISTS `t_role`; CREATE TABLE `t_role` (
`id` int(11) NOT NULL,
`rolename` varchar(45) DEFAULT NULL,
`description` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_role` */ insert into `t_role`(`id`,`rolename`,`description`) values (1,'admin','超级管理员'),(2,'manager','系统管理员'),(3,'normal','普通管理员'),(4,'user','普通用户'); /*Table structure for table `t_role_permission` */ DROP TABLE IF EXISTS `t_role_permission`; CREATE TABLE `t_role_permission` (
`role_id` int(11) DEFAULT NULL,
`permission_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_role_permission` */ 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); /*Table structure for table `t_user` */ DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` (
`id` int(11) NOT NULL,
`username` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_user` */ insert into `t_user`(`id`,`username`,`password`) values (1,'admin1','670b14728ad9902aecba32e22fa4f6bd'),(2,'admin2','670b14728ad9902aecba32e22fa4f6bd'),(3,'admin3','670b14728ad9902aecba32e22fa4f6bd'),(4,'admin4','670b14728ad9902aecba32e22fa4f6bd'); /*Table structure for table `t_user_role` */ DROP TABLE IF EXISTS `t_user_role`; CREATE TABLE `t_user_role` (
`user_id` int(11) DEFAULT NULL,
`role_id` int(11) DEFAULT NULL,
KEY `FK_role_user` (`role_id`),
KEY `FK_user_role` (`user_id`),
CONSTRAINT `FK_role_user` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`),
CONSTRAINT `FK_user_role` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `t_user_role` */ insert into `t_user_role`(`user_id`,`role_id`) values (1,1),(1,3),(2,2),(2,3),(3,3),(4,4); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(一)的更多相关文章

  1. Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(二)

    然后是项目下的文件:完整的项目请看  上一篇 Maven+Spring+Hibernate+Shiro+Mysql简单的demo框架(一) 项目下的springmvc-servlet.xml配置文件: ...

  2. Dubbo入门介绍---搭建一个最简单的Demo框架

    Dubbo入门---搭建一个最简单的Demo框架 置顶 2017年04月17日 19:10:44 是Guava不是瓜娃 阅读数:320947 标签: dubbozookeeper 更多 个人分类: D ...

  3. Maven配置Spring+Hibernate Shiro权限控制项目

    前言:在Eclipse中安装好Maven插件,然后创建一个Sample项目.在Eclipse中检出Shiro的官方演示样例.地址http://svn.apache.org/repos/asf/shir ...

  4. Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境【转】

    项目建设完成之后的结构: 数据库的表结构如下: 环境建设:搭建Maven环境.Tomcat环境.需要MySql 数据库支持,使用的编程工具Eclipse (这些是前期准备): 开始创建工程: 1.创建 ...

  5. Dubbo入门—搭建一个最简单的Demo框架

    一.Dubbo背景和简介 1.电商系统的演进 Dubbo开始于电商系统,因此在这里先从电商系统的演变讲起. a.单一应用框架(ORM) 当网站流量很小时,只需一个应用,将所有功能如下单支付等都部署在一 ...

  6. Dubbo入门---搭建一个最简单的Demo框架(转)

    Dubbo背景和简介 Dubbo开始于电商系统,因此在这里先从电商系统的演变讲起. 单一应用框架(ORM) 当网站流量很小时,只需一个应用,将所有功能如下单支付等都部署在一起,以减少部署节点和成本.  ...

  7. Dubbo简介---搭建一个最简单的Demo框架

    Dubbo背景和简介 Dubbo开始于电商系统,因此在这里先从电商系统的演变讲起. 单一应用框架(ORM) 当网站流量很小时,只需一个应用,将所有功能如下单支付等都部署在一起,以减少部署节点和成本.  ...

  8. Maven+Spring+Spring MVC+MyBatis+MySQL,搭建SSM框架环境

    项目建设完成之后的结构: 数据库的表结构如下: 环境建设:搭建Maven环境.Tomcat环境.需要MySql 数据库支持,使用的编程工具Eclipse (这些是前期准备): 开始创建工程: 1.创建 ...

  9. eclipse下的,maven+spring+springMVC+mabatis+mysql.创建

    环境:window系统,64位工具:eclipse:下载地址:            链接:http://pan.baidu.com/s/1hr73LE8 密码:vcsa        tomcat: ...

随机推荐

  1. 关于myeclipse代码提示的一些问题

    默认是  .xxx  输入点提示,要写注释 @xxx的时候怎么输入@后面有代码提示呢? Auto activation delay 是代码提示出现的速度  下面一行是出现代码提示的条件 我们在.后面加 ...

  2. Ext.Ajax中scope的作用

    在Ext的前台Js中使用Ajax请求,如果想让回调函数中的this作用域跟当前的类一样如何实现呢?Ajax提供了一个参数scope. 详细代码如下: layout : { type : 'accord ...

  3. C#做音乐播放器时在自动下一曲中报异常的解决办法

    ---------------------- ASP.Net+Unity开发..Net培训.期待与您交流! ---------------------- 在利用Media Player做音乐播放器的时 ...

  4. 二分图匹配(KM算法)n^4 分类: ACM TYPE 2014-10-04 11:36 88人阅读 评论(0) 收藏

    #include <iostream> #include<cstring> #include<cstdio> #include<cmath> #incl ...

  5. Segment Tree 分类: ACM TYPE 2014-08-29 13:04 97人阅读 评论(0) 收藏

    #include<iostream> #include<cstdio> using namespace std; struct node { int l, r, m; int ...

  6. ie 与 Chrome 时间格式化问题.

    ie 与 Chrome 时间格式化通用: new Date(res[i].Time.replaceAll("-", "/")).format("yyy ...

  7. POJ 2785

    4 Values whose Sum is 0 Time Limit: 15000MS   Memory Limit: 228000K Total Submissions: 14475   Accep ...

  8. POJ 2013

    #include <iostream> #include <string> #define MAXN 20 using namespace std; string _m[MAX ...

  9. Android Service学习

    Android 中的 Service 全面总结 引用别人的博客:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 好文章 1.S ...

  10. POJ 2653 Pick-up sticks(线段相交)

    题目链接 题意 : 把每根棍往地上扔,找出最后在上面的棍,也就是说找出所有的没有别的棍子压在它的上面的棍子. 思路 : 对于每根棍子,压在他上面的棍子一定是在它之后扔的棍子,所以在找的时候只要找它之后 ...