1、删除webapp/WEB-INF下的web.xml文件。web.xml文件主要作用是配置springMVC的dispatcherservlet,dispatcherservlet是springMVC中前端控制器,负责分发请求。springboot已经帮我们自动配置好了dispatcherservlet,因此不在需要web.xml。springboot的优点就是约定大于配置,省掉了很多配置文件。
2、建立application.yml以及多环境下的各个配置文件。
application.yml配置公共的配置。内容如下:
yaml文件是springboot推荐的配置文件格式,层次分明,书写方便。
jmx: java管理扩展。通常使用JMX来监控系统的运行状态或管理系统的某些方面,比如清空缓存、重新加载配置文件等。
profiles.active: 当前激活的配置文件。这个位置用占位符代替,maven打包的时候会自动替换此处的占位符。
cache.type: 指定spring缓存的实现。
pagehelper: 分页插件配置。
mybatis: type-aliases-package: model类的位置。mapper-locations: mapper xml文件位置
mapper.identity: 指定主键自增方法,当前是MYSQL
application-dev.yml文件的配置如下:
spring:
#数据源配置开始
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://47.104.202.212:3306/tianren?serverTimezone=Asia/Shanghai&useunicode=true&characterEncoding=utf8&useSSL=false
username: root
password: tianren
hikari: #hikari连接池配置
connection-timeout: 30000
auto-commit: true
max-lifetime: 1800000
pool-name: DatebookHikariCP
minimum-idle: 5
connection-test-query: SELECT 1
maximum-pool-size: 15
idle-timeout: 30000
driver-class-name: com.mysql.cj.jdbc.Driver
#数据源配置结束
#缓存配置开始
redis:
database: 0
host: 127.0.0.1
password:
port: 6379
jedis:
pool:
max-idle: 8
min-idle: 0
max-active: 100
max-wait: -1ms
#缓存配置结束
#模板配置开始
thymeleaf:
cache: false
enabled: false
#模板配置结束
#server配置开始
server:
address: 0.0.0.0
port: 8080
servlet:
context-path: /tianren
compression: #启用gzip压缩
mime-types: application/json,application/xml,application/javascript,application/octet-stream,test/css,text/html,text/xml,text/plain,image/jpeg,image/jpg,image/svg+xml,image/png
min-response-size: 1024
enabled: true
#server配置结束
#日志配置由logback.xml控制
上面的配置中有几个需要注意的地方:
driver-class-name:这里不能是com.mysql.jdbc.Driver而应该是com.mysql.cj.jdbc.Driver。因为在mysql-connector-java 5.x版本中是com.mysql.jdbc.Driver,而在最新的mysql-connector-java 6.x版本中发生了变化,变为com.mysql.cj.jdbc.Driver。
url:由于上面的driver-class-name发生了变化,jdbcurl也发生了变化,需要指定服务器时区,增加一个参数serverTimezone=Asia/Shanghai
3、建立Application.java启动类
@SpringBootApplication
@EnableScheduling
@EnableSwagger2 //启用swagger2
@EnableTransactionManagement //启注解事务管理,等同于xml配置方式的
//@EnableAutoConfiguration(exclude = {QuartzAutoConfiguration.class}) 这个注解不再需要,最新发布的springboot2中,依赖spring-boot-starter-quartz,springboot就已经帮我们自动配置好了quartz定时任务相关的配置。
@MapperScan("com.tianren.dao") //配置DAO接口扫描包
@EnableCaching //开启缓存,可以使用@Cacheable、@CacheEvict、@CachePut注解
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
上面的代码中EnableAutoConfiguration这个注解是不需要的,最新发布的springboot2中,依赖spring-boot-starter-quartz,springboot就已经帮我们自动配置好了quartz定时任务相关的配置。注意,shiro中引用的quartz版本为1.6,与spring的quartz(版本2.3.0)冲突,需要进行如下改动:pom中不要依赖shiro-quartz,同时增加依赖
org.springframework.boot
spring-boot-starter-quartz
然后在ShiroConfig中,会话验证调度器中,如下配置
/**
* 会话验证调度器
*
* @return
*/
@Bean
public ExecutorServiceSessionValidationScheduler sessionValidationScheduler(DefaultWebSessionManager sessionManager) {
ExecutorServiceSessionValidationScheduler sessionValidationScheduler = new ExecutorServiceSessionValidationScheduler();
sessionValidationScheduler.setInterval(3600000L);
sessionValidationScheduler.setSessionManager(sessionManager);
return sessionValidationScheduler;
}
原来使用QuartzSessionValidationScheduler,现在改为ExecutorServiceSessionValidationScheduler即可。
不要使用quartz定时任务了。
4、其他配置
spring-mvc.xml对应,WebMvcConfig.java
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
private static Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);
@Resource
private CustomObjectMapper customObjectMapper;
@Resource
private MappingJackson2HttpMessageConverter converter;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("开始注册静态资源");
registry.addResourceHandler("/bower_components/**").addResourceLocations("classpath:/static/bower_components/");
registry.addResourceHandler("/c_img/**").addResourceLocations("classpath:/static/c_img/");
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
registry.addResourceHandler("/dist/**").addResourceLocations("classpath:/static/dist/");
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
registry.addResourceHandler("/lib/**").addResourceLocations("classpath:/static/lib/");
registry.addResourceHandler("/plugins/**").addResourceLocations("classpath:/static/plugins/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/", ".jsp");
}
@Override
public void configureMessageConverters(List> converters) {
converters.add(converter);
}
@Bean
public RequestContextListener requestContextListener(){
return new RequestContextListener();
}
@Bean
public CustomObjectMapper customObjectMapper() {
return new CustomObjectMapper();
}
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(customObjectMapper);
return converter;
}
}
将原来在webapp下的所有静态资源移动到resouces/static下,同时在上面的代码中用classpath:前缀开头来映射这些静态资源文件。
spring-shiro.xml、spring-mvc-shiro.xml对应ShiroConfig
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//shiro自定义过滤器
Map filters = new LinkedHashMap<>();
Map filterChainDefinitionMap = new LinkedHashMap<>();
shiroFilterFactoryBean.setFilters(filters);
//配置记住我或认证通过可以访问的地址
// 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/login","authc");
filterChainDefinitionMap.put("/app/login","anon");
//配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
filterChainDefinitionMap.put("/logout", "logout");
//未授权界面;
filterChainDefinitionMap.put("/authenticated", "authc");
//:这是一个坑呢,一不小心代码就不好使了;
filterChainDefinitionMap.put("/bower_components/**", "anon");
filterChainDefinitionMap.put("/c_img/**", "anon");
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/dist/**", "anon");
filterChainDefinitionMap.put("/images/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/lib/**", "anon");
filterChainDefinitionMap.put("/plugins/**", "anon");
filterChainDefinitionMap.put("/test", "anon");
//swagger2访问路径
filterChainDefinitionMap.put("/swagger-ui.html", "anon");
filterChainDefinitionMap.put("/swagger-resources", "anon");
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/webjars/springfox-swagger-ui/**", "anon");
//
filterChainDefinitionMap.put("/**", "anon");
// 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* 安全管理器
* @param userRealm
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager(UserRealm userRealm, DefaultWebSessionManager sessionManager, RedisCacheManager redisCacheManager){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
securityManager.setSessionManager(sessionManager);
securityManager.setCacheManager(redisCacheManager);
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
/**
* 会话ID生成器
*
* @return
*/
@Bean
public JavaUuidSessionIdGenerator sessionIdGenerator() {
return new JavaUuidSessionIdGenerator();
}
/**
* 会话Cookie模板
*
* @return
*/
@Bean
public SimpleCookie sessionIdCookie() {
SimpleCookie simpleCookie = new SimpleCookie("sid");
simpleCookie.setHttpOnly(true);
simpleCookie.setMaxAge(-1);
return simpleCookie;
}
/**
* 自动登陆自动登陆cookie
*
* @return
*/
@Bean
public SimpleCookie rememberMeCookie() {
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
simpleCookie.setHttpOnly(true);
simpleCookie.setMaxAge(2592000);
return simpleCookie;
}
/**
* rememberMe管理器
*
* @return
*/
@Bean
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
cookieRememberMeManager.setCookie(rememberMeCookie());
return cookieRememberMeManager;
}
/**
* cacheManager 缓存 redis实现
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean(name = "redisCacheManager")
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
/**
* 配置shiro redisManager
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost("localhost");
redisManager.setPort(6379);
redisManager.setExpire(1800);// 配置缓存过期时间
redisManager.setTimeout(0);
// redisManager.setPassword(password);
return redisManager;
}
/**
* Session Manager
* 使用的是shiro-redis开源插件
*/
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
/**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
* 使用的是shiro-redis开源插件
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
return redisSessionDAO;
}
/**
* 会话验证调度器
*
* @return
*/
@Bean
public ExecutorServiceSessionValidationScheduler sessionValidationScheduler(DefaultWebSessionManager sessionManager) {
ExecutorServiceSessionValidationScheduler sessionValidationScheduler = new ExecutorServiceSessionValidationScheduler();
sessionValidationScheduler.setInterval(3600000L);
sessionValidationScheduler.setSessionManager(sessionManager);
return sessionValidationScheduler;
}
/**
* 凭证匹配器
*
* @return
*/
@Bean
public RetryLimitHashedCredentialsMatcher credentialsMatcher(RedisCacheManager redisCacheManager) {
RetryLimitHashedCredentialsMatcher credentialsMatcher = new RetryLimitHashedCredentialsMatcher(redisCacheManager);
credentialsMatcher.setHashAlgorithmName("md5");
credentialsMatcher.setHashIterations(2);
credentialsMatcher.setStoredCredentialsHexEncoded(true);
return credentialsMatcher;
}
/**
* Realm实现
*
* @return
*/
@Bean
public UserRealm userRealm(RetryLimitHashedCredentialsMatcher credentialsMatcher) {
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(credentialsMatcher);
userRealm.setCachingEnabled(false);
return userRealm;
}
/**
* Shiro生命周期处理器
*
* @return
*/
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* 相当于调用SecurityUtils.setSecurityManager(securityManager)
*
* @return
*/
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean(DefaultWebSecurityManager securityManager) {
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
methodInvokingFactoryBean.setArguments(securityManager);
return methodInvokingFactoryBean;
}
}
spring.xml删除,spring-cache.xml删除(后面会集成Redis缓存),ehcache.xml删除,config.properties删除。
log4j.properties删除(使用logback来输出日志)
pom中,springboot版本为2.1.1.RELEASE,mybatis-spring-boot-starter为1.3.2。还要增加依赖
org.apache.tomcat.embed
tomcat-embed-jasper
provided
javax.servlet
jstl
以支持jsp和jstl标签