当前位置: 代码迷 >> 综合 >> springboot之集成mybatis mongo shiro druid redis jsp
  详细解决方案

springboot之集成mybatis mongo shiro druid redis jsp

热度:94   发布时间:2023-12-24 23:29:24.0

闲来无事,研究一下spingboot  发现好多地方都不一样了,第一个就是官方默认不支持jsp  于是开始狂找资料  终于让我找到了


首先引入依赖如下:

<!-- tomcat的支持.--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><version>1.5.8.RELEASE</version></dependency><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><version>8.5.12</version></dependency>
 <!-- servlet依赖. --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.0</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency>

然后配置application.yml

 #配置视图解析器mvc:view:prefix: /WEB-INF/jsp/suffix: .jsp

然后在建立webapp文件,

                           

创建启动类

application,java 

@SpringBootApplication
public class Application extends SpringBootServletInitializer{/*** 主函数* @param args* @throws Exception*/public static void main(String[] args) throws Exception {SpringApplication.run(Application.class, args);}/*** 支持jsp需要重写此方法* @param builder* @return*/@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {return builder.sources(this.getClass());}
}


右键运行即可



集成 mybatis 首先引入依赖


 <!-- mybatis核心包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.0</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency>

 <!--mybatis依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-autoconfigure</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.2.2</version></dependency><!--通用Mapper--><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId><version>3.3.8</version></dependency>


然后编写mybatis的配置类


@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {@AutowiredDataSource dataSource;@Bean(name = "sqlSessionFactory")public SqlSessionFactory sqlSessionFactoryBean() {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setTypeAliasesPackage("com.lv.gang.entity.business");//分页插件PageHelper pageHelper = new PageHelper();Properties properties = new Properties();properties.setProperty("reasonable", "true");properties.setProperty("supportMethodsArguments", "true");properties.setProperty("returnPageInfo", "check");properties.setProperty("params", "count=countSql");pageHelper.setProperties(properties);//添加插件bean.setPlugins(new Interceptor[]{pageHelper});//添加XML目录ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();try {bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));return bean.getObject();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}/*** 配置sessionFactory* @param sqlSessionFactory* @return*/@Beanpublic SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate(sqlSessionFactory);}/*** 配置事物* @return*/@Bean@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {return new DataSourceTransactionManager(dataSource);}
}

 */
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");mapperScannerConfigurer.setBasePackage("com.lv.gang.mapper.business");Properties properties = new Properties();properties.setProperty("mappers", "tk.mybatis.mapper.common.Mapper");properties.setProperty("notEmpty", "false");properties.setProperty("IDENTITY", "MYSQL");mapperScannerConfigurer.setProperties(properties);return mapperScannerConfigurer;}}
引入分页依赖

 <!--分页插件--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>4.1.3</version></dependency>



这时候就可以正常使用mybatis了

接下来集成 redis  引入以下依赖


<!--redis依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-redis</artifactId><version>1.4.7.RELEASE</version></dependency>

然后编写redis的配置类

@EnableCaching
@Configuration
public class RedisCacheConfig extends CachingConfigurerSupport {@Autowiredprivate JedisConnectionFactory jedisConnectionFactory;@Beanpublic RedisTemplate redisTemplate() {StringRedisTemplate redisTemplate = new StringRedisTemplate(jedisConnectionFactory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}/*** 配置缓存管理器* @return*/@Beanpublic CacheManager cacheManager() {String[] cacheNames = {"app_default", "users", "blogs", "goods", "configs", "info"};RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate(), Arrays.asList(cacheNames));redisCacheManager.setDefaultExpiration(86400);return redisCacheManager;}/*** 自定义key.* 此方法将会根据类名+方法名+所有参数的值生成唯一的一个key,即使@Cacheable中的value属性一样,key也会不一样。*/@Bean@Overridepublic KeyGenerator keyGenerator() {return (target, method, objects) -> {StringBuilder sb = new StringBuilder();sb.append(target.getClass().getName());sb.append(method.getName());for (Object obj : objects) {sb.append(obj.toString());}return sb.toString();};}
}


接下来配置application,yml

#配置redisredis:host: 127.0.0.1database: 0pool:max-active: 8min-idle: 2port: 6379cluster:nodes:

这个时候就可以正常使用了


接下来集成  mongo  引入以下依赖


<!--mongo--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId><version>1.5.2.RELEASE</version></dependency>

然后配置application.yml   

#配置mongodata:mongodb:host: 127.0.0.1port: 27017database: gang


接下来我们集成druid数据库连接池    首先引入以下依赖

 <!-- jdbc --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId><version>1.5.8.RELEASE</version></dependency>
<!--连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.3</version></dependency>

然后配置application.yml

#配置数据源datasource:name: testurl: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&useAffectedRows=true&allowMultiQueries=trueusername: rootpassword:# 使用druid数据源type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverfilters: statmaxActive: 20initialSize: 1maxWait: 60000minIdle: 1timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: select 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxOpenPreparedStatements: 20


接下来集成shiro  首先引入以下依赖


<!-- shiro spring. --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.2.2</version></dependency><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.3.2</version></dependency><!-- shiro ehcache --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-ehcache</artifactId><version>1.2.2</version></dependency>


编写shiro的配置类


@Configuration
public class ShiroConfiguration {@Autowiredprivate CacheManager cacheManager;/*** 配置shiro过滤器* @param manager* @return*/@Bean(name="shiroFilter")public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();bean.setSecurityManager(manager);//配置登录的url和登录成功的urlbean.setLoginUrl("/login");bean.setSuccessUrl("/home");//配置访问权限, 必须为LinkedHashMapLinkedHashMap<String, String> filterChainDefinitionMap=new LinkedHashMap<>();filterChainDefinitionMap.put("/index*", "anon"); //表示可以匿名访问filterChainDefinitionMap.put("/logout*","anon");filterChainDefinitionMap.put("/jsp/error.jsp*","anon");filterChainDefinitionMap.put("/static/**","anon");filterChainDefinitionMap.put("/*", "authc");//表示需要认证才可以访问bean.setFilterChainDefinitionMap(filterChainDefinitionMap);return bean;}//配置核心安全事务管理器@Bean(name="securityManager")public SecurityManager securityManager(@Qualifier("authRealm") ShiroRealm authRealm) {System.err.println("--------------shiro已经加载----------------");DefaultWebSecurityManager manager=new DefaultWebSecurityManager();//设置自定义realmmanager.setRealm(authRealm);//设置缓存管理manager.setCacheManager(cacheManager);return manager;}/*** 配置缓存管理器* @return*/@Beanpublic CacheManager cacheManager(){EhCacheManager cacheManager=new EhCacheManager();cacheManager.setCacheManagerConfigFile("classpath:shiro-cache.xml");return cacheManager;}/*** 自定义Realm 继承自AuthorizingRealm* @param matcher* @return*/@Bean(name="authRealm")public ShiroRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {ShiroRealm authRealm=new ShiroRealm();authRealm.setCredentialsMatcher(matcher);return authRealm;}//配置自定义的密码比较器@Bean(name="credentialsMatcher")public CredentialsMatcher credentialsMatcher() {HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();credentialsMatcher.setStoredCredentialsHexEncoded(true);credentialsMatcher.setHashAlgorithmName("MD5");credentialsMatcher.setHashIterations(1);return credentialsMatcher;}@Beanpublic LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){return new LifecycleBeanPostProcessor();}@Beanpublic DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){DefaultAdvisorAutoProxyCreator creator=new DefaultAdvisorAutoProxyCreator();creator.setProxyTargetClass(true);return creator;}/*** 配置 securityManager* @param manager* @return*/@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {AuthorizationAttributeSourceAdvisor advisor=new AuthorizationAttributeSourceAdvisor();advisor.setSecurityManager(manager);return advisor;}
}
编写 自定义的realm 

public class ShiroRealm extends AuthorizingRealm {/*** 认证方法* @param principalCollection* @return*/@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {return null;}/*** 授权方法* @param authenticationToken* @return* @throws AuthenticationException*/@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {return null;}/*** 缓存清楚方法*/public void clearCached() {PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();super.clearCache(principals);}
}


此时已经集成完毕  下篇讲解springboot 集成dubbo和mq 请持续关注


这是deamo的下载地址

http://download.csdn.net/download/qq_38665235/10165610

  相关解决方案