RBAC权限管理项目(一)(项目构建及相关配置)

RBAC权限管理项目(一)

前言

最近决定将以前做过的一个RBAC项目重过一遍,进行一些整理。希望能有所收获

一.RBAC搭建

1. 项目配置

RBAC权限管理项目(一)(项目构建及相关配置)
RBAC权限管理项目(一)(项目构建及相关配置)

  • pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yue</groupId>
    <artifactId>yeyu-rbac</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>yeyu-rbac Maven Webapp</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!--springMVC-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <!--jackson支持-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.1</version>
        </dependency>

        <!-- MyBatis框架包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <!--创建`SqlSessionFactory`对象的第三方实现类-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <!--数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

        <!--数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>

        <!--jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <!--aspects-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <!--文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

        <!--lang3:针对java.lang包进行一些封装,提供一些工具类-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>

        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope><!-- 提供作用范围,不会发布到webapps下 -->
        </dependency>

        <!--lombok:帮助开发人员消除 Java 的冗长-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope><!-- 提供作用范围,不会发布到webapps下 -->
        </dependency>
    </dependencies>

    <build>
        <finalName>yeyu-rbac</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <!--允许没有web.xml文件-->
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <!--发布插件-->
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>8.1.16.v20140903</version>
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds><!--每隔10秒自动扫描一次class文件,如果被修改==>自动重启-->
                    <webApp>
                        <contextPath>/rbac</contextPath>
                    </webApp><!--发布路径-->
                    <stopKey/>
                    <stopPort/>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


2. 配置Easy Code代码生成器

  • 连接数据库
    RBAC权限管理项目(一)(项目构建及相关配置)
    RBAC权限管理项目(一)(项目构建及相关配置)
    RBAC权限管理项目(一)(项目构建及相关配置)
  • 安装插件
    RBAC权限管理项目(一)(项目构建及相关配置)
  • 载入自定义模板
    RBAC权限管理项目(一)(项目构建及相关配置)

3. 相关配置类代码:

项目结构:
RBAC权限管理项目(一)(项目构建及相关配置)

  • 入口配置类:
    • Spring的配置类
      • SpringConfig配置类
      • CommonsSpringConfig配置类
    • SpringMVC的配置类
      • WebConfig配置类
      • CommonsWebConfig配置类
    • 前端控制器的映射路径

入口:

package com.framework.rbac.config;

import com.framework.commons.config.CommonsSpringConfig;
import com.framework.commons.config.CommonsWebConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class GlobalApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	/**
	 * 加载Spring的配置类
	 * @return
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[]{SpringConfig.class, CommonsSpringConfig.class};
	}

	/**
	 * 加载SpringMVC的配置类
	 * @return
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[]{WebConfig.class, CommonsWebConfig.class};
	}

	/**
	 * 前端控制器的映射路径
	 * @return
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}
}

SpringConfig配置类:
package com.framework.rbac.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.*;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Configuration
@ComponentScan(basePackages = "com.framework",excludeFilters = {
		@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, ControllerAdvice.class}),
		@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {RestController.class, RestControllerAdvice.class})
})
@EnableAspectJAutoProxy(proxyTargetClass = true)//切面编程
@EnableTransactionManagement(proxyTargetClass = true)//事务管理
public class SpringConfig {
	/**
	 * 创建了MySQL数据源
	 * @return
	 */
	@Bean
	public DataSource dataSource(){
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
		druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/yue_mybatis");
		druidDataSource.setUsername("root");
		druidDataSource.setPassword("");
		return druidDataSource;
	}
}


CommonsSpringConfig配置类:
package com.framework.commons.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.interceptor.*;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableTransactionManagement(proxyTargetClass = true)
public class CommonsSpringConfig {
	/**
	 * 创建SqlSessionFactory对象
	 * @return
	 */
	@Bean
	public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
		SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
		factory.setDataSource(dataSource);
		//读取核心配置文件
		factory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
		//读取映射文件
		ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
		//resources目录下的映射文件
		Resource[] mapperLocations = patternResolver.getResources("classpath:mapper/*Mapper.xml");
		factory.setMapperLocations(mapperLocations);

		return factory;
	}

	/**
	 * MapperScannerConfigurer对象
	 * sqlSession.getMapper(StudentMapper.class)//接口的动态实例化是由我们自己创建
	 * @return
	 */
	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer(){
		MapperScannerConfigurer configurer = new MapperScannerConfigurer();
		configurer.setBasePackage("com.framework.**.mapper");//接口
		configurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
		//可选:为了防止相同的类名,如果你没有相同的类名,那么就可以没有该配置
		configurer.setAnnotationClass(Repository.class);//必须在接口上设置该注解
		return configurer;
	}

	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource){
		//配置JDBC的事务管理器,管理数据源
		return new DataSourceTransactionManager(dataSource);
	}
	@Bean("serviceAdvice")
	public TransactionInterceptor serviceAdvice(PlatformTransactionManager transactionManager){
		//数据源
		NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
		//设置规则:只读事务,不做更新操作
		RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
		readOnlyTx.setReadOnly(true);
		readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);//默认值

		//设置规则:当事务存在就使用当前事务,如果不存在则创建新的事务
		RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
		requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
		requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);//默认值
		//设置:哪些方法使用哪些规则?
		Map<String, TransactionAttribute> txMap = new HashMap<>();
		txMap.put("get*",readOnlyTx);
		txMap.put("list*",readOnlyTx);
		txMap.put("find*",readOnlyTx);
		txMap.put("query*",readOnlyTx);
		txMap.put("check*",readOnlyTx);
		txMap.put("load*",readOnlyTx);
		txMap.put("sel*",readOnlyTx);
		txMap.put("valid*",readOnlyTx);
		txMap.put("login*",readOnlyTx);

		txMap.put("*",requiredTx);

		source.setNameMap(txMap);

		TransactionInterceptor txAdivce = new TransactionInterceptor();
		txAdivce.setTransactionManager(transactionManager);
		txAdivce.setTransactionAttributeSource(source);
		return txAdivce;
	}

	@Bean
	public Advisor serviceAdviceAdvisor(TransactionInterceptor serviceAdvice){
		AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
		pointcut.setExpression("execution(* com.framework..service.*Service.*(..))");
		return new DefaultPointcutAdvisor(pointcut,serviceAdvice);
	}
}

WebConfig配置类:
package com.framework.rbac.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.framework",includeFilters = {
		@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class, ControllerAdvice.class}),
		@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {RestController.class, RestControllerAdvice.class})
},useDefaultFilters = false)
public class WebConfig {
}

CommonsWebConfig配置类:
package com.framework.commons.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.framework.commons.formatter.String2DateFormatter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.JstlView;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Configuration//标准该类为配置类==等价核心配置文件(springmvc.xml)
@EnableWebMvc
public class CommonsWebConfig implements WebMvcConfigurer {
	/***
	 * 配置JSP请求转发的视图解析器
	 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="jspViewResolver">
		 <property name="prefix" value="/WEB-INF/jsp/"/>
		 <property name="suffix" value=".jsp"/>
	 </bean>
	 * @param registry
	 */
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		registry.jsp("/WEB-INF/jsp/",".jsp").viewClass(JstlView.class);
	}

	/**
	 * 默认方式的排除静态资源
	 * <mvc:default-servlet-handler default-servlet-name="default"/>
	 * @param configurer
	 */
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable("default");
	}

	/**
	 * 静态资源的路径映射
	 * <mvc:resources mapping="/images/**" location="/attr/"/>
	 * <mvc:resources mapping="/js/**" location="/resources/"/>
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/js/**").addResourceLocations("/static/js/");
		registry.addResourceHandler("/css/**").addResourceLocations("/static/css/");
		registry.addResourceHandler("/img/**").addResourceLocations("/static/img/");
		registry.addResourceHandler("/fonts/**").addResourceLocations("/static/fonts/");
	}

	/**
	 * 设置消息的转换
	 * 		<mvc:message-converters>
	 *             <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
	 *                 <property name="defaultCharset" value="UTF-8"/>
	 *                 <property name="prettyPrint" value="true"/>
	 *                 <property name="supportedMediaTypes">
	 *                     <list>
	 *                         <value>text/html</value>
	 *                         <value>appication/json</value>
	 *                     </list>
	 *                 </property>
	 *                 <property name="objectMapper">
	 *                     <bean class="com.fasterxml.jackson.databind.ObjectMapper">
	 *                         <property name="dateFormat">
	 *                             <bean class="java.text.SimpleDateFormat">
	 *                                 <constructor-arg value="yyyy-MM-dd HH:mm:ss"/>
	 *                             </bean>
	 *                         </property>
	 *                     </bean>
	 *                 </property>
	 *             </bean>
	 *         </mvc:message-converters>
	 * @param converters
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		/*json转换*/
		MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
		jackson2HttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
		jackson2HttpMessageConverter.setPrettyPrint(true);
		List<MediaType> mediaTypeList = new ArrayList<>();
		mediaTypeList.add(MediaType.TEXT_HTML);
		mediaTypeList.add(MediaType.TEXT_PLAIN);
		mediaTypeList.add(MediaType.APPLICATION_JSON);
		jackson2HttpMessageConverter.setSupportedMediaTypes(mediaTypeList);

		/*对日期处理*/
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		jackson2HttpMessageConverter.setObjectMapper(objectMapper);

		converters.add(jackson2HttpMessageConverter);
	}

	/**
	 * 文件上传的解析器
	 *     <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
	 *         <property name="defaultEncoding" value="UTF-8"/>
	 *         <property name="maxUploadSize" value="#{1024*1024*50}"/>
	 *         <property name="maxUploadSizePerFile" value="#{1024*1024*10}"/>
	 *         <property name="maxInMemorySize" value="2048"/>
	 *         <property name="resolveLazily" value="true"/>
	 *
	 *     </bean>
	 * @return
	 */
	@Bean
	public MultipartResolver multipartResolver(){//<bean id="multipartResolver"/>
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
		commonsMultipartResolver.setDefaultEncoding("UTF-8");
		commonsMultipartResolver.setMaxUploadSize(1024*1024*50);
		commonsMultipartResolver.setMaxUploadSizePerFile(1024*1024*5);
		commonsMultipartResolver.setMaxInMemorySize(2048);
		commonsMultipartResolver.setResolveLazily(true);
		//commonsMultipartResolver.setUploadTempDir();
		return commonsMultipartResolver;
	}

	/**
	 * String转换java.util.Date格式的工具类
	 * @param registry
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addFormatter(new String2DateFormatter());
	}
}

Controller:

BaseController:
package com.framework.commons.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class BaseController {
	/*封装servlet*/
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	@Autowired
	protected HttpSession session;
	@Autowired
	protected ServletContext application;

	//文件上传目录
	private static final String UPLOAD_PATH = "/attr/";

	//请求转发
	protected static ModelAndView forward(String url){
		ModelAndView mav =new  ModelAndView(url);
		return mav;
	}

	//重定向
	protected static ModelAndView redirect(String url){
		ModelAndView mav =new  ModelAndView("redirect:"+url);
		return mav;
	}

	/**
	 * 获取根路径:http://localhost:8080/route
	 * @param httpRequest
	 * @return String
	 */
	protected String getContext(HttpServletRequest httpRequest) {
		String url = null;
		if (null != httpRequest) {
			url = new StringBuilder().append(httpRequest.getScheme()).append("://")
					.append(httpRequest.getServerName()).append(":")
					.append(httpRequest.getServerPort()).append("/")
					.append(httpRequest.getSession().getServletContext().getServletContextName())
					.toString();
		}
		return url;
	}

	//单文件上传
	public Map<String,String> uploadFile(MultipartFile uploadFile){
		List<Map<String,String>> tempList = uploadFiles(new MultipartFile[]{uploadFile});
		return tempList.get(0);
	}

	//多文件上传
	public List<Map<String,String>> uploadFiles(MultipartFile[] fileArray){
		List<Map<String,String>> fileList = new ArrayList<>();
		String path = application.getRealPath(UPLOAD_PATH);
		File folder = new File(path);
		if(!folder.exists()){
			folder.mkdirs();
		}
		if(fileArray!=null){
			for (MultipartFile uploadFile : fileArray) {
				String fileName = uploadFile.getOriginalFilename();
				String ext = FilenameUtils.getExtension(fileName);
				String newFileName = UUID.randomUUID().toString().replaceAll("-","")+"."+ext;
				try {
					uploadFile.transferTo(new File(path+"/"+newFileName));
				} catch (IOException e) {
					e.printStackTrace();
				}
				//保存数据
				Map<String,String> map = new HashMap<>();
				//map.put("服务器端的文件名称","上传文件的名称");
				map.put(newFileName,fileName);
				fileList.add(map);
			}
		}
		return fileList;
	}
}

自定义异常

重复异常
package com.framework.commons.exception;

public class RepetitionException extends RuntimeException {
	private int code = 1001;//重复代码
	public RepetitionException(){}
	public RepetitionException(String message) {
		super(message);
	}
	public int getCode() {
		return code;
	}
}

service异常
package com.framework.commons.exception;

public class ServiceException extends RuntimeException {
	private int code = 5001;//默认为业务逻辑层错误代码
	public ServiceException(String message, int code) {
		super(message);
		this.code = code;
	}
	public ServiceException(String message) {
		super(message);
	}
	public int getCode() {
		return code;
	}
}

异常控制器返回数据
package com.framework.commons.controller;


import com.framework.commons.exception.RepetitionException;
import com.framework.commons.exception.ServiceException;
import com.framework.commons.model.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 返回的异常信息:JSON格式的数据
 */
@RestControllerAdvice//@Controller+@ResponseBody
public class ExceptionHandlerController {
	@ExceptionHandler(ServiceException.class)
	public R handlerException(ServiceException ex){
		return R.error(ex.getCode(),ex.getMessage());
	}
	@ExceptionHandler(RepetitionException.class)
	public R handlerException(RepetitionException ex){
		return R.error("数据库中已经存在该条记录");
	}
	//可以再定义其他的异常处理
	@ExceptionHandler(Exception.class)
	public Exception handlerException(Exception ex){

		//return R.error(ex.getMessage());
		return ex;
	}
}

日期转换工具类

String2DateFormatter
package com.framework.commons.formatter;

import com.framework.commons.util.DateHelper;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

public class String2DateFormatter implements Formatter<Date> {
	@Override
	public Date parse(String s, Locale locale) throws ParseException {
		return DateHelper.parseDate(s);
	}

	@Override
	public String print(Date date, Locale locale) {
		return null;
	}
}

DateHelper
package com.framework.commons.util;

import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;

public class DateHelper {
	private static final String[] parsePatterns = {
			"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss",
			"yyyy/MM/dd","yyyy/MM/dd HH:mm:ss",
			"yyyy.MM.dd","yyyy.MM.dd HH:mm:ss"
	};

	public static Date parseDate(String str) {
		try {
			return DateUtils.parseDate(str,parsePatterns);
		} catch (Exception e) {
			return null;
		}
	}
}

Model

分页设置
package com.framework.commons.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Page<T> {
	/**当前页*/
	private int pageNow = 1;
	/**每页显示条数*/
	private int pageSize = 30;
	/**总记录数*/
	private int totalCount;
	/**总页数,需要通过总记录和每页显示条数计算得到结果*/
	private int totalPages;
	/**计算索引Limit后面开始的位置,(pageNow-1)*pageSize */
	private int offset;
	/**分页的结果集*/
	private List<T> datas;
	/**保存查询条件*/
	private Map<String,String> queryMap = new HashMap<>();

	public int getPageNow() {
		return pageNow;
	}

	public void setPageNow(int pageNow) {
		this.pageNow = pageNow;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getTotalPages() {
		boolean bool = (this.totalCount%this.pageSize==0);
		int page = this.totalCount/this.pageSize;
		totalPages = bool?page:page+1;
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

	public int getOffset() {
		offset=(pageNow-1)*pageSize;
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public List<T> getDatas() {
		return datas;
	}

	public void setDatas(List<T> datas) {
		this.datas = datas;
	}

	public Map<String, String> getQueryMap() {
		return queryMap;
	}

	public void setQueryMap(Map<String, String> queryMap) {
		this.queryMap = queryMap;
	}
}

R继承hashMap返回数据
package com.framework.commons.model;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 */
public class R extends HashMap<String,Object> {

	public R(){
		put("code",0);
		put("flag","success");//也可以使用boolean
	}

	public static R error(){
		return error(500,"未知异常,请联系系统管理员");
	}

	public static R error(String message){
		return error(500,message);
	}

	public static R error(int code,String message){
		R r = new R();
		r.put("code",code);
		r.put("flag","error");
		r.put("message",message);
		return r;
	}

	public static R ok(Map<String,Object> map){
		R r = new R();
		r.putAll(map);
		return r;
	}
	public static R ok(Object obj){
		R r = new R();
		r.put("datas",obj);
		return r;
	}
	public static R ok(String message){
		R r = new R();
		r.put("message",message);
		return r;
	}

	public static  R ok(){
		return new R();
	}

	@Override
	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}
}

生成用户操作相关代码:
RBAC权限管理项目(一)(项目构建及相关配置)

上一篇:【项目开发---权限】


下一篇:elementUI el-table合并单元格