迎着风跑  

 

 DatabasePropertiesConfig中的内容(数据库连接信息):

@PropertySource(value = {"classpath:db.properties"})
public class DataBasePropertiesConfig {
@Value("${jdbc.driverClassName}")
private String className;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;

public String getClassName() {
return className;
}

public String getUrl() {
return url;
}

public String getUsername() {
return username;
}

public String getPassword() {
return password;
}
}

SpringConfig中的内容(spring配置):

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.format.FormatterRegistry;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@ComponentScan(basePackages = {"cn.woniu.service.impl", "cn.woniu.dao"}) //扫描器
@Import(value = {DataBasePropertiesConfig.class})
@EnableTransactionManagement(proxyTargetClass = true) //开启事务支持
public class SpringConfig {

/**
* 实例化数据源对象,并保存到ioc容器中
*
* @return dataSource
*/
//给实例化连接对象规定名称 并设置实例化生成 和 销毁
@Bean(name = "dataSource", initMethod = "init", destroyMethod = "close")
public DruidDataSource druidDataSource(DataBasePropertiesConfig dataBase) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(dataBase.getClassName());
dataSource.setUrl(dataBase.getUrl());
dataSource.setUsername(dataBase.getUsername());
dataSource.setPassword(dataBase.getPassword());
return dataSource;
}

/**
* spring管理mybaits的SqlSessionFactoryBean会话工厂
*
* @param dataSource
* @return
*/
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);

//设置分页拦截器
PageInterceptor pageInterceptor=new PageInterceptor();
//创建PageHelper插件需要的参数集合
Properties properties=new Properties();
//配置数据库方言为 mysql
properties.setProperty("helperDialect","mysql");
//配置分页的合理化数据
properties.setProperty("reasonable","true");
pageInterceptor.setProperties(properties);
//将分页拦截器添加到SqlSessionFactoryBean
sqlSessionFactory.setPlugins(new Interceptor[]{pageInterceptor});

return sqlSessionFactory;

/*对mybaits的额外配置*/
//读取mybaits配置文件
// factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
//配置实体类别名
//factoryBean.setTypeAliasesPackage("cn.woniu.domain");
//让dao接口和mapper.xml不在同一个包下
//factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
// .getResources("cn/woniu/mapper/*.xml"));
}

/**
* 配置dao映射文件用来扫描dao
*
* @return
*/
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("cn.woniu.dao");
return mapperScannerConfigurer;
}

/**
* 配置事务管理
*
* @param dataSource
* @return
*/
@Bean
public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
/**
* 注册自定义类型转换器
* @param registry
*/
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DataConverter());
}

}

SpringMvcConfig中的内容(springmvc配置):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
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.InternalResourceViewResolver;

@Configuration
@EnableWebMvc //开启springMvc注解支持
@ComponentScan(basePackages = {"cn.woniu.controller","cn.woniu.exception"})
public class SpringMvcConfig implements WebMvcConfigurer {
/**
* 配置视图解析器
* @return
*/
@Bean
public InternalResourceViewResolver resourceViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
/**
* 配置静态资源过滤(解决springmvc拦截静态资源)
* @param configurer
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable(); //开启静态资源忽略
}

/*
//第二种静态资源忽略配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**") // 过滤静态资源路径
.addResourceLocations("/static/");// 定位资源
}*/
/**
* 配置springmvc文件解析器 文件上传需要
* @return
*/
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
//设置上传文件的大小
resolver.setMaxUploadSize(10485760);
return resolver;
}

/**
* 添加拦截器注册
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptor = registry.addInterceptor(new LoginInterceptor());
interceptor.addPathPatterns("/**");
interceptor.excludePathPatterns("/","/loginUser");
}
}

WebInitializer中的内容(tomcat启动时自动加载spring和springmvc的配置环境,相当于web.xml Initializer初始化器):

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;


/**
* tomcat启动时自动加载spring和springmvc的配置环境,相当于web.xml Initializer初始化器
*/
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

/**
* 读取spring配置类
* @return
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{
SpringConfig.class
};
}
/**
* 读取Springmvc的配置类
* @return
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{
SpringMvcConfig.class
};
}
/**
* 配置springmvc的拦截规则
* @return
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}


/**
* 配置springmvc的中文编码过滤器
* @return
*/
@Override
protected Filter[] getServletFilters() {
Filter encodingFilter = new CharacterEncodingFilter("UTF-8", true);
return new Filter[]{ encodingFilter };
}

}

GlodalException中的内容(异常处理器):

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* 全局异常处理器,所有的异常都由我进行捕获,并显示提示
* 对controller进行增强
* 将这个类设为controller层的切面类
*/
@ControllerAdvice //controller的增强器
public class GlobalException {

/**
* 当controler中发生了ArithmeticException时执行该方法
* @return
*/
@ExceptionHandler(ArithmeticException.class)//只捕获ArithmeticException异常,如果小括号中不指定异常类型则捕获所有异常
@ResponseBody
public ResponseResult<Void> arithmeticException(ArithmeticException e){
return new ResponseResult<>(500,"除数不能为0");
}
}

LoginInterceptor中的内容(拦截器):

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
/**
* 在进入controller之前执行
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(request.getSession().getAttribute("users")!=null){
return true;
}
response.sendRedirect("/");
return false;
}
}

 

 DataConverter(日期格式转换类):

import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DataConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
/**
* 将字符串转为日期
* @param source
* @return
*/
Date date = null;
/**
* yyyy-MM-dd
* yyyy/MM/dd
* yyyy年MM月dd日
*/
String str = null;
if (source != null) {

if (source.contains("-")) {
str = "yyyy-MM-dd";
}
if (source.contains("/")) {
str = "yyyy/MM/dd";
}
if (source.contains("年")) {
str = "yyyy年MM月dd日";
}
try {
SimpleDateFormat sdf = new SimpleDateFormat(str);
date = sdf.parse(source);
} catch (Exception e) {
throw new RuntimeException("日期转换失败,请联系管理员。");
}

} else {
throw new RuntimeException("参数不能为空,请输入一个参数。");
}
return date;
}
}
---------------------------------------------------------------------------------------

ResponseResult(返回json格式的工具类):
public class ResponseResult<T> {
private int code; // 状态码 200,成功,500:失败,403:无权
private String msg; // 消息
private T data; // 数据

public ResponseResult() {
}

public ResponseResult(T data, int code) {
this(code, "OK");
this.data = data;
}

public ResponseResult(int code, String msg) {
this.code = code;
this.msg = msg;
}

public ResponseResult(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}

public static final ResponseResult<Void> SUCCESS = new ResponseResult<>(200, "OK");
public static final ResponseResult<Void> NOTLOGINED = new ResponseResult<>(401, "未登录");
public static final ResponseResult<Void> FORBIDDEN = new ResponseResult<>(403, "无权限");
public static final ResponseResult<Void> Unauthenticated = new ResponseResult<>(402, "认证失败");
public static final ResponseResult<Void> FAIL = new ResponseResult<>(500, "操作失败");

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}
}
UploadFileUtils(图片上传工具类):
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
* 文件上传工具类
*/
public class UploadFileUtils {

/**
* 上传文件
* @param request request对象
* @param filePath 文件保存路径
* @param uploadFile 要上传的文件对象
* @return
*/
public static String sendFile(HttpServletRequest request, String filePath, MultipartFile uploadFile){
String str=null;//保存文件上传成功后的路径

// 指定上传文件保存位置
String path = request.getSession().getServletContext().getRealPath("/"+filePath+"/");
// 判断,该路径是否存在
File file = new File(path);
if(!file.exists()){
// 创建该文件夹
file.mkdirs();
}

// 获取上传文件的名称
String filename = uploadFile.getOriginalFilename();
//获得后缀
String suffix=filename.substring(filename.lastIndexOf("."));

// 把文件的名称设置唯一值,uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid+""+suffix;

try {
// 完成文件上传
uploadFile.transferTo(new File(path,filename));
str=filePath+"/"+filename;
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}

 

 db.properties(数据库连接信息):

 

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/数据库名称?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai(本地数据库)
jdbc.username=root
jdbc.password=123456

 

generatorConfig(自动生成dao mapper entity插件配置):
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="VenueGenerator" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>

<commentGenerator>
<!--关闭时间注释 -->
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/woniu_jdbc_data3?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai"
userId="root" password="123456">
<!--只生成当前库下的表-->
<property name="nullCatalogMeansCurrent" value="true"/>
<property name="remarksReporting" value="true"/>
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成model的包名和位置-->
<javaModelGenerator targetPackage="cn.woniu.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射XML文件的包名和位置-->
<sqlMapGenerator targetPackage="cn.woniu.dao" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成dao文件包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.woniu.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成哪些表-->
<table tableName="users" domainObjectName="Users" enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<generatedKey column="id" sqlStatement="Mysql" type="post" identity="true"/>
</table>
<table tableName="book" domainObjectName="Book" enableCountByExample="true" enableUpdateByExample="true"
enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<generatedKey column="id" sqlStatement="Mysql" type="post" identity="true"/>
</table>
</context>
</generatorConfiguration>
logback(日志文件配置类):
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%5p | %-40.40logger{39} : %m%n</pattern>
<charset>utf8</charset>
</encoder>
</appender>

<logger name="cn.woniu" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
</logger>

<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>

 
 
posted on 2021-10-15 17:54  迎着风跑  阅读(103)  评论(0编辑  收藏  举报