bootstrap菜单树

master
10295 7 years ago
parent 9d36ad5abf
commit d0b62adc54
  1. 5
      core/src/main/java/core/aop/Advisor.java
  2. 23
      core/src/main/java/core/dao/BaseDao1.java
  3. 26
      core/src/main/java/core/dao/BaseDao2.java
  4. 31
      core/src/main/java/core/service/BaseService.java
  5. 2
      db/src/main/java/db/AbstractModel.java
  6. 22
      db/src/main/java/db/JsonResult.java
  7. 69
      db/src/main/java/db/PageResult.java
  8. 6
      db/src/main/java/db/ToJSON.java
  9. 17
      db/src/main/java/db/Type.java
  10. 4
      db/src/main/java/db/annotation/BiliBili.java
  11. 7
      db/src/main/java/db/config/AddConfig.java
  12. 195
      db/src/main/java/db/config/HibernateConfig.java
  13. 119
      db/src/main/java/db/model/DataSourceModel.java
  14. 2
      db/src/main/java/db/model/bilibili/CidEntity.java
  15. 4
      db/src/main/java/db/model/bilibili/DataModel.java
  16. 6
      db/src/main/java/db/model/bilibili/MenuModel.java
  17. 2
      db/src/main/java/db/model/bilibili/ScheduledTaskEntity.java
  18. 2
      db/src/main/java/db/model/bilibili/TaskEntity.java
  19. 124
      db/src/main/java/db/util/ClassScaner.java
  20. 1
      web/src/main/java/web/config/AppConfig.java
  21. 24
      web/src/main/java/web/config/SpringConfig.java
  22. 7
      web/src/main/java/web/controller/AdminController.java
  23. 24
      web/src/main/java/web/controller/BaseController.java
  24. 20
      web/src/main/java/web/controller/BiliController.java
  25. 18
      web/src/main/java/web/controller/CommentController.java
  26. 18
      web/src/main/java/web/controller/DataController.java
  27. 7
      web/src/main/java/web/controller/MenuController.java
  28. 47
      web/src/main/java/web/controller/TableController.java
  29. 29
      web/src/main/java/web/html/ElementId.java
  30. 14
      web/src/main/java/web/service/BiliService.java
  31. 18
      web/src/main/java/web/service/DataService.java
  32. 16
      web/src/main/java/web/util/DynamicTimer.java
  33. 20
      web/src/main/resources/config.properties
  34. 13
      web/src/main/resources/db.properties
  35. 4
      web/src/main/webapp/WEB-INF/jsp/index.jsp
  36. 54
      web/src/main/webapp/WEB-INF/jsp/menu.jsp
  37. 82
      web/src/main/webapp/WEB-INF/jsp/table.jsp
  38. 41
      web/src/test/java/SpringTest.java
  39. 4
      web/src/test/java/Test.java
  40. 5
      web/src/test/java/web/controller/TestController.java

@ -1,7 +1,6 @@
package core.aop;
import core.dao.BaseDao1;
import core.dao.BaseDao2;
import core.service.BaseService;
import org.aopalliance.aop.Advice;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.stereotype.Component;
@ -20,7 +19,7 @@ public class Advisor extends StaticMethodMatcherPointcutAdvisor {
@Override
public boolean matches(Method method, Class<?> aClass) {
return BaseDao1.class.isAssignableFrom(aClass)||BaseDao2.class.isAssignableFrom(aClass);
return BaseService.class.isAssignableFrom(aClass);
}
@PostConstruct

@ -1,23 +0,0 @@
package core.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
/**
* Created by reborn on 2017/7/31.
*/
@Repository
public class BaseDao1 extends HibernateTemplate{
@Autowired
public BaseDao1(SessionFactory aliyun) {
super(aliyun);
}
}

@ -1,26 +0,0 @@
package core.dao;
import db.AbstractModel;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
@Repository
public class BaseDao2 extends HibernateTemplate {
@Autowired
public BaseDao2(SessionFactory huaWeiCloud) {
super(huaWeiCloud);
}
public <T extends AbstractModel> void delete(Class<T> tClass, Serializable key) throws DataAccessException {
T model = load(tClass, key);
if (model != null) {
delete(model);
}
}
}

@ -1,45 +1,38 @@
package core.service;
import core.dao.BaseDao1;
import core.dao.BaseDao2;
import db.AbstractModel;
import db.DBAction;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.orm.hibernate5.HibernateTemplate;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by reborn on 2017/7/28.
*/
@Service
public class BaseService {
public abstract class BaseService {
protected static Logger log=LogManager.getLogger();
@Resource
protected BaseDao1 baseDao1;
@Resource
protected BaseDao2 baseDao2;
protected abstract HibernateTemplate getHibernateTemplate() ;
@Transactional("transactionManager1")
public<T extends AbstractModel> T curd(DBAction action, T command) throws DataAccessException {
switch (action) {
case C:
baseDao1.save(command);break;
getHibernateTemplate().save(command);break;
case U:
baseDao1.update(command);break;
getHibernateTemplate().update(command);break;
case R:
AbstractModel model=baseDao1.get(command.getClass(), command.primaryKey());
AbstractModel model=getHibernateTemplate().get(command.getClass(), command.primaryKey());
if(model!=null){
return model.cast();
}
case D:
baseDao1.delete(command);break;
getHibernateTemplate().delete(command);break;
default:
throw new RuntimeException("非法操作:" + action);
}
@ -48,9 +41,11 @@ public class BaseService {
}
public <T extends AbstractModel> List find(T command, int firstResult, int maxResults){
return baseDao1.findByCriteria(command.getCriteria(),firstResult,maxResults);
return getHibernateTemplate().findByCriteria(command.getCriteria(),firstResult,maxResults);
}
public <T extends AbstractModel> Long rowCount(Class<T> tClass){
return getHibernateTemplate().executeWithNativeSession(session -> (Long) DetachedCriteria.forClass(tClass).setProjection(Projections.rowCount()).getExecutableCriteria(session).uniqueResult());
}
}

@ -9,7 +9,7 @@ import java.io.Serializable;
* Created by reborn on 2017/8/3.
*/
public abstract class AbstractModel{
public abstract class AbstractModel extends ToJSON{
public abstract Serializable primaryKey();

@ -1,40 +1,24 @@
package db;
import java.io.Serializable;
public class JsonResult<T> extends ToJSON{
private T data;
private JsonResult.type type;
private Type type;
private DBAction action;
public JsonResult(T data, JsonResult.type type, DBAction action) {
public JsonResult(T data, Type type, DBAction action) {
this.data = data;
this.type = type;
this.action = action;
}
public enum type implements Serializable {
success("成功"),
fail("失败") ;
private String desc;
type(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
public T getData() {
return data;
}
public JsonResult.type getType() {
public Type getType() {
return type;
}

@ -0,0 +1,69 @@
package db;
import java.util.List;
public class PageResult<T extends AbstractModel> {
private long count;
private int currentPage;
private List<T> datas;
private int pageSize;
private long pages;
private Type type;
private String errorMsg;
/**
*
* @param count 总行数
* @param currentPage 当前分页数
* @param datas 数据
* @param pageSize 分页大小
* @param type 操作结果
*/
public PageResult(long count, int currentPage, List<T> datas, int pageSize, Type type) {
this.count = count;
this.currentPage = currentPage+1;
this.datas = datas;
this.pageSize = pageSize;
this.pages=count%pageSize==0?count/pageSize:count/pageSize+1;
this.type = type;
}
public PageResult(Type type, String errorMsg) {
this.type = type;
this.errorMsg = errorMsg;
}
public long getCount() {
return count;
}
public int getCurrentPage() {
return currentPage;
}
public List<T> getDatas() {
return datas;
}
public Type getType() {
return type;
}
public int getPageSize() {
return pageSize;
}
public long getPages() {
return pages;
}
public String getErrorMsg() {
return errorMsg;
}
}

@ -12,7 +12,11 @@ public class ToJSON {
private static Logger log=LogManager.getLogger();
protected void init(){
static {
init();
}
protected static void init(){
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
}

@ -0,0 +1,17 @@
package db;
import java.io.Serializable;
public enum Type implements Serializable {
success("成功"),
fail("失败") ;
private String desc;
Type(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}

@ -0,0 +1,4 @@
package db.annotation;
public @interface BiliBili {
}

@ -0,0 +1,7 @@
package db.config;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
public interface AddConfig {
void addConfig(LocalSessionFactoryBean bean);
}

@ -1,129 +1,192 @@
package db.config;
import com.alibaba.druid.pool.DruidDataSource;
import db.AbstractModel;
import db.model.DataSourceModel;
import db.util.ClassScaner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.*;
/**
* Created by reborn on 2017/7/28.
*/
public class HibernateConfig{
public class HibernateConfig {
private static Logger log=LogManager.getLogger();
private static Logger log = LogManager.getLogger();
@Value("${hibernate.dialect}")
private String dialect;
@Value("${hibernate.connection.driver_class}")
private String driver;
@Value("${hibernate.connection.url}")
@Value("${db_url}")
private String url;
@Value("${hibernate.connection.username}")
@Value("${db_username}")
private String username;
@Value("${hibernate.connection.password}")
@Value("${db_password}")
private String password;
@Value("${hibernate.connection.url2}")
private String url2;
@Value("${hibernate.connection.username2}")
private String username2;
@Value("${hibernate.connection.password2}")
private String password2;
@Resource
private DefaultListableBeanFactory beanFactory;
@Value("${sessionFactory.scan}")
private String packagesToScan[];
private static final String rootKey = "ROOT";
private static final String tableNote="tableNote";
private static final String tableNote = "tableNote";
private LocalSessionFactoryBean aliyun = new LocalSessionFactoryBean();
private static final Class<DataSourceModel> rootClass = DataSourceModel.class;
private LocalSessionFactoryBean huaWeiCloud = new LocalSessionFactoryBean();
private static final String annotation = "db.annotation.";
private DruidDataSource dataSource(String url,String username,String password){
DruidDataSource dataSource=new DruidDataSource();
private static final String basePackage = "db.model";
private static final Map<String, HibernateTemplate> map = new HashMap<>();
public static final HibernateTemplate get(String key) {
return map.get(key);
}
public static final Map<String, HibernateTemplate> get(){
return map;
}
private DruidDataSource dataSource(String url, String username, String password) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driver);
log.info("数据源初始化\nurl="+url+"\nusername="+username+"\npassword="+password);
log.info("数据源初始化\nurl=" + url + "\nusername=" + username + "\npassword=" + password);
return dataSource;
}
private DruidDataSource dataSource(DataSourceModel dataSourceModel) {
String url = "jdbc:mysql://" + dataSourceModel.getHostname() + ":" + dataSourceModel.getDbPort() + "/" + dataSourceModel.getDbName() + "?serverTimezone=UTC&useSSL=false";
return dataSource(url, dataSourceModel.getUsername(), dataSourceModel.getDbPassword());
}
@PostConstruct
private void init() {
initSessionFactory(aliyun,dataSource(url,username,password));
initSessionFactory(huaWeiCloud,dataSource(url2,username2,password2));
private HibernateTemplate initRootDB() {
SessionFactory rootdb_sessionFactory = initSessionFactory(dataSource(url, username, password), (LocalSessionFactoryBean bean) -> {
bean.setAnnotatedClasses(rootClass);
});
return new HibernateTemplate(rootdb_sessionFactory);
}
private void initSessionFactory(LocalSessionFactoryBean bean, DataSource dataSource){
Properties properties=new Properties();
properties.setProperty("hibernate.dialect",dialect);
properties.setProperty("hibernate.format_sql","true");
bean.setHibernateProperties(properties);
bean.setDataSource(dataSource);
bean.setPackagesToScan(packagesToScan);
try {
bean.afterPropertiesSet();
checkClass(bean);
} catch (IOException e) {
e.printStackTrace();
private HibernateTemplate initDB(DataSourceModel dataSourceModel) {
SessionFactory sessionFactory = initSessionFactory(dataSource(dataSourceModel), (LocalSessionFactoryBean bean) -> {
Set<Class> classes;
Class c;
try {
c = Class.forName(annotation + dataSourceModel.getAnnotation());
} catch (ClassNotFoundException e) {
return;
}
if (Annotation.class.isAssignableFrom(c)) {
classes = ClassScaner.scan(basePackage, (Class<? extends Annotation>) c);
bean.setAnnotatedClasses(classes.toArray(new Class[classes.size()]));
} else {
log.error(c+"不是注解!!!");
}
});
if (sessionFactory != null) {
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(sessionFactory);
beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbDesc(),DBBeanNameManager.transactionManager),hibernateTransactionManager);
return new HibernateTemplate(sessionFactory);
} else {
return null;
}
}
@Bean("aliyun")
public SessionFactory aliyun(){
return aliyun.getObject();
}
public enum DBBeanNameManager {
hibernateTemplate,
transactionManager;
public static String getName(String key,DBBeanNameManager type){
return type.name()+"_"+key;
}
@Bean("huaWeiCloud")
public SessionFactory huaWeiCloud(){
return huaWeiCloud.getObject();
public static String getName(DBBeanNameManager type){
return type.name()+"_root";
}
}
@Bean("transactionManager1")
public HibernateTransactionManager aliyunTransaction() {
HibernateTransactionManager hibernateTransactionManager=new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(aliyun());
return hibernateTransactionManager;
@PostConstruct
private void init() {
HibernateTemplate root = initRootDB();
beanFactory.registerSingleton(DBBeanNameManager.getName(DBBeanNameManager.hibernateTemplate),root);
map.put(rootKey, root);
List<DataSourceModel> dataSourceModels = root.loadAll(rootClass);
for (DataSourceModel dataSourceModel : dataSourceModels) {
HibernateTemplate hibernateTemplate = initDB(dataSourceModel);
if (hibernateTemplate != null) {
beanFactory.registerSingleton(DBBeanNameManager.getName(dataSourceModel.getDbDesc(),DBBeanNameManager.hibernateTemplate),hibernateTemplate);
map.put(dataSourceModel.getDbDesc(), hibernateTemplate);
}
}
}
@Bean("transactionManager2")
public HibernateTransactionManager huaweiTransaction() {
HibernateTransactionManager hibernateTransactionManager=new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(huaWeiCloud());
return hibernateTransactionManager;
private SessionFactory initSessionFactory(DataSource dataSource, AddConfig config) {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", dialect);
properties.setProperty("hibernate.format_sql", "true");
bean.setHibernateProperties(properties);
bean.setDataSource(dataSource);
try {
config.addConfig(bean);
bean.afterPropertiesSet();
checkClass(bean);
return bean.getObject();
} catch (IOException e) {
log.error(e);
}
return null;
}
private void checkClass(LocalSessionFactoryBean bean){
for(Class c:bean.getMetadataSources().getAnnotatedClasses()){
try {
Method method=ReflectionUtils.findMethod(c,tableNote);
Object result=ReflectionUtils.invokeMethod(method,c.newInstance());
if(ObjectUtils.isEmpty(result)){
throw new RuntimeException(method+"没有正确重写");
private void checkClass(LocalSessionFactoryBean bean) {
for (Class c : bean.getMetadataSources().getAnnotatedClasses()) {
if (AbstractModel.class.isAssignableFrom(c)) {
try {
Method method = ReflectionUtils.findMethod(c, tableNote);
Object result = ReflectionUtils.invokeMethod(method, c.newInstance());
if (ObjectUtils.isEmpty(result)) {
throw new RuntimeException(method + "没有正确重写");
}else{
log.info("扫描实体类:"+c+",映射表:"+result);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} else {
log.error(c + "没有继承" + AbstractModel.class);
}
}
}

@ -0,0 +1,119 @@
package db.model;
import db.AbstractModel;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@Entity
@Table(name = "datasource", schema = "rootdb", catalog = "")
public class DataSourceModel extends AbstractModel {
private String dbDesc;
private String hostname;
private int dbPort;
private String username;
private String dbPassword;
private String dbName;
private String annotation;
@Id
@Column(name = "db_desc", nullable = false, length = 10)
public String getDbDesc() {
return dbDesc;
}
public void setDbDesc(String dbDesc) {
this.dbDesc = dbDesc;
}
@Basic
@Column(name = "hostname", nullable = false, length = 32)
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
@Basic
@Column(name = "db_port", nullable = false)
public int getDbPort() {
return dbPort;
}
public void setDbPort(int dbPort) {
this.dbPort = dbPort;
}
@Basic
@Column(name = "username", nullable = false, length = 10)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "db_password", nullable = false, length = 10)
public String getDbPassword() {
return dbPassword;
}
public void setDbPassword(String dbPassword) {
this.dbPassword = dbPassword;
}
@Basic
@Column(name = "db_name", nullable = false, length = 10)
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
@Basic
@Column(name = "annotation", nullable = true, length = 10)
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DataSourceModel that = (DataSourceModel) o;
return dbPort == that.dbPort &&
Objects.equals(dbDesc, that.dbDesc) &&
Objects.equals(hostname, that.hostname) &&
Objects.equals(username, that.username) &&
Objects.equals(dbPassword, that.dbPassword) &&
Objects.equals(dbName, that.dbName) &&
Objects.equals(annotation, that.annotation);
}
@Override
public int hashCode() {
return Objects.hash(dbDesc, hostname, dbPort, username, dbPassword, dbName, annotation);
}
@Override
public Serializable primaryKey() {
return getDbDesc();
}
@Override
public String tableNote() {
return "数据源";
}
}

@ -1,4 +1,4 @@
package db.model;
package db.model.bilibili;
import db.AbstractModel;

@ -1,11 +1,13 @@
package db.model;
package db.model.bilibili;
import db.AbstractModel;
import db.annotation.BiliBili;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@BiliBili
@Entity
@Table(name = "data", schema = "bilibili", catalog = "bilibili")
public class DataModel extends AbstractModel {

@ -1,6 +1,7 @@
package db.model;
package db.model.bilibili;
import db.AbstractModel;
import db.annotation.BiliBili;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
@ -10,6 +11,7 @@ import java.io.Serializable;
import java.util.List;
import java.util.Objects;
@BiliBili
@Entity
@Table(name = "menu", schema = "bilibili", catalog = "bilibili")
public class MenuModel extends AbstractModel {
@ -87,7 +89,7 @@ public class MenuModel extends AbstractModel {
@Override
public String tableNote() {
return "测试表";
return "菜单表";
}
@Basic

@ -1,4 +1,4 @@
package db.model;
package db.model.bilibili;
import db.AbstractModel;

@ -0,0 +1,124 @@
package db.util;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.StringUtils;
import org.springframework.util.SystemPropertyUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class ClassScaner implements ResourceLoaderAware {
//保存过滤规则要排除的注解
private final List<TypeFilter> includeFilters = new LinkedList<TypeFilter>();
private final List<TypeFilter> excludeFilters = new LinkedList<TypeFilter>();
private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
public static Set<Class> scan(String[] basePackages,
Class<? extends Annotation>... annotations) {
ClassScaner cs = new ClassScaner();
if(ArrayUtils.isNotEmpty(annotations)) {
for (Class anno : annotations) {
cs.addIncludeFilter(new AnnotationTypeFilter(anno));
}
}
Set<Class> classes = new HashSet<Class>();
for (String s : basePackages)
classes.addAll(cs.doScan(s));
return classes;
}
public static Set<Class> scan(String basePackages, Class<? extends Annotation>... annotations) {
return ClassScaner.scan(StringUtils.tokenizeToStringArray(basePackages, ",; \t\n"), annotations);
}
public final ResourceLoader getResourceLoader() {
return this.resourcePatternResolver;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourcePatternResolver = ResourcePatternUtils
.getResourcePatternResolver(resourceLoader);
this.metadataReaderFactory = new CachingMetadataReaderFactory(
resourceLoader);
}
public void addIncludeFilter(TypeFilter includeFilter) {
this.includeFilters.add(includeFilter);
}
public void addExcludeFilter(TypeFilter excludeFilter) {
this.excludeFilters.add(0, excludeFilter);
}
public void resetFilters(boolean useDefaultFilters) {
this.includeFilters.clear();
this.excludeFilters.clear();
}
public Set<Class> doScan(String basePackage) {
Set<Class> classes = new HashSet<Class>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
+ org.springframework.util.ClassUtils
.convertClassNameToResourcePath(SystemPropertyUtils
.resolvePlaceholders(basePackage))
+ "/**/*.class";
Resource[] resources = this.resourcePatternResolver
.getResources(packageSearchPath);
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
if (resource.isReadable()) {
MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
if ((includeFilters.size() == 0 && excludeFilters.size() == 0)
|| matches(metadataReader)) {
try {
classes.add(Class.forName(metadataReader
.getClassMetadata().getClassName()));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException ex) {
throw new BeanDefinitionStoreException(
"I/O failure during classpath scanning", ex);
}
return classes;
}
protected boolean matches(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, this.metadataReaderFactory)) {
return true;
}
}
return false;
}
}

@ -11,4 +11,5 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan({"core"})
@Import(HibernateConfig.class)
public class AppConfig {
}

@ -1,30 +1,32 @@
package web.config;
import core.dao.BaseDao1;
import db.config.HibernateConfig;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.OpenSessionInViewInterceptor;
import org.springframework.web.servlet.config.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* Created by reborn on 2017/7/28.
*/
@Configuration
@EnableWebMvc
@PropertySource("classpath:config.properties")
@ComponentScan({"web.controller","web.service"})
@PropertySource({"classpath:config.properties"})
@ComponentScan({"web.controller","web.service","web.util"})
public class SpringConfig implements WebMvcConfigurer {
@Resource
private BaseDao1 baseDao;
private DefaultListableBeanFactory beanFactory;
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
@ -40,9 +42,13 @@ public class SpringConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
OpenSessionInViewInterceptor interceptor=new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(baseDao.getSessionFactory());
registry.addWebRequestInterceptor(interceptor);
Map<String, HibernateTemplate> hibernateTemplateMap= HibernateConfig.get();
for(String key:hibernateTemplateMap.keySet()) {
OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor();
interceptor.setSessionFactory(hibernateTemplateMap.get(key).getSessionFactory());
registry.addWebRequestInterceptor(interceptor);
}
}
@Override
@ -51,4 +57,6 @@ public class SpringConfig implements WebMvcConfigurer {
builder.indentOutput(true);
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}

@ -2,7 +2,9 @@ package web.controller;
import db.DBAction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import web.html.ElementId;
import javax.servlet.http.HttpServletRequest;
@ -10,11 +12,12 @@ import javax.servlet.http.HttpServletRequest;
* Created by reborn on 2017/9/14.
*/
@Controller
public class AdminController extends BaseController{
public class AdminController extends BiliController{
@RequestMapping("index")
private String index(HttpServletRequest request){
private String index(HttpServletRequest request,Model model){
log.info("进入首页");
model.addAttribute("elementPreifx",ElementId.getAll());
return "index";
}

@ -4,6 +4,7 @@ import core.service.BaseService;
import db.AbstractModel;
import db.DBAction;
import db.JsonResult;
import db.Type;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.dao.DataAccessException;
@ -13,16 +14,15 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/**
* Created by reborn on 2017/9/14.
*/
public abstract class BaseController<T extends AbstractModel>{
public abstract class BaseController<T extends AbstractModel,E extends BaseService>{
protected static Logger log=LogManager.getLogger();
@Resource
public BaseService baseService;
protected E service;
protected abstract void setService(E service);
@ResponseBody
@RequestMapping(value = "{action}", produces = MediaType.APPLICATION_JSON_VALUE)
@ -30,13 +30,13 @@ public abstract class BaseController<T extends AbstractModel>{
log.info(model.tableNote()+ "进行" + action.getCh() + "操作请求");
if(checkAction(action)) {
try {
return new JsonResult<T>(baseService.curd(action, model),JsonResult.type.success,action);
return new JsonResult<>(service.curd(action, model), Type.success, action);
}catch (DataAccessException e){
log.error(e);
return new JsonResult<String>("非法操作",JsonResult.type.fail,action);
return new JsonResult<>("非法操作", Type.fail, action);
}
}else{
return new JsonResult<>(model.tableNote() + "不允许" + action.getCh() + "操作", JsonResult.type.fail,action);
return new JsonResult<>(model.tableNote() + "不允许" + action.getCh() + "操作", Type.fail,action);
}
}
@ -47,17 +47,17 @@ public abstract class BaseController<T extends AbstractModel>{
log.info(queryCommand.tableNote()+ "进行批量" + action.getCh() + "操作请求");
if(checkAction(action)) {
try {
return new JsonResult<>(baseService.find(queryCommand, firstResult, maxResults), JsonResult.type.success, action);
return new JsonResult<>(service.find(queryCommand, firstResult, maxResults), Type.success, action);
} catch (DataAccessException e) {
log.error(e);
return new JsonResult<String>("非法操作",JsonResult.type.fail,action);
return new JsonResult<>("非法操作", Type.fail, action);
}
}else{
return new JsonResult<>(queryCommand.tableNote() + "不允许" + action.getCh() + "操作", JsonResult.type.fail,action);
return new JsonResult<>(queryCommand.tableNote() + "不允许" + action.getCh() + "操作", Type.fail,action);
}
}
public abstract boolean checkAction(DBAction action);
protected abstract boolean checkAction(DBAction action);
}

@ -0,0 +1,20 @@
package web.controller;
import db.AbstractModel;
import db.DBAction;
import org.springframework.beans.factory.annotation.Autowired;
import web.service.BiliService;
public class BiliController<T extends AbstractModel> extends BaseController<T,BiliService>{
@Override
@Autowired
protected void setService(BiliService service) {
this.service=service;
}
@Override
protected boolean checkAction(DBAction action) {
return false;
}
}

@ -1,18 +0,0 @@
package web.controller;
import db.DBAction;
import db.model.DataModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/comment")
public class CommentController extends BaseController<DataModel>{
@Override
public boolean checkAction(DBAction action) {
return true;
}
}

@ -1,8 +1,11 @@
package web.controller;
import db.AbstractModel;
import db.DBAction;
import db.model.DataModel;
import db.model.bilibili.DataModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import web.service.DataService;
@ -12,11 +15,16 @@ import java.util.EnumSet;
@Controller
@RequestMapping("/data")
public class DataController extends BaseController<DataModel> {
public class DataController extends TableController<DataModel,DataService> {
@Resource
private DataService dataService;
@RequestMapping
public <T extends AbstractModel> String find(Model model, DataModel queryCommand){
return super.find(model,queryCommand,0,10);
}
@RequestMapping("start/{size}")
public void start(@PathVariable Integer size){
stop();
@ -28,6 +36,12 @@ public class DataController extends BaseController<DataModel> {
dataService.stop();
}
@Override
@Autowired
protected void setService(DataService service) {
this.service=service;
}
@Override
public boolean checkAction(DBAction action) {
return !EnumSet.of(DBAction.D).contains(action);

@ -2,7 +2,7 @@ package web.controller;
import db.AbstractModel;
import db.DBAction;
import db.model.MenuModel;
import db.model.bilibili.MenuModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@ -10,9 +10,10 @@ import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController<MenuModel> {
public class MenuController extends BiliController<MenuModel> {
@RequestMapping
@RequestMapping()
public <T extends AbstractModel> String find(Model model, MenuModel queryCommand, @RequestParam Integer firstResult, @RequestParam Integer maxResults){
model.addAttribute("menus", super.find(DBAction.R, queryCommand, firstResult, maxResults).toString());
return "menu";

@ -0,0 +1,47 @@
package web.controller;
import core.service.BaseService;
import db.AbstractModel;
import db.DBAction;
import db.PageResult;
import db.Type;
import org.springframework.dao.DataAccessException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
public abstract class TableController<T extends AbstractModel,E extends BaseService> extends BaseController<T,E> {
@RequestMapping("table")
public <T extends AbstractModel> String find(Model model, T queryCommand, @RequestParam Integer firstResult, @RequestParam Integer maxResults){
DBAction action=DBAction.R;
log.info(queryCommand.tableNote()+ "进行批量" + action.getCh() + "操作请求");
PageResult result;
if(checkAction(action)) {
try {
Long rowCount=service.rowCount(queryCommand.getClass());
if(rowCount>0) {
List list = service.find(queryCommand, firstResult*maxResults, maxResults);
result=new PageResult<T>(rowCount, firstResult,list,maxResults , Type.success);
}else{
result=new PageResult(Type.fail,"没有记录");
}
} catch (DataAccessException e) {
log.error(e);
result=new PageResult(Type.fail,"非法操作");
}
}else{
result=new PageResult(Type.fail,queryCommand.tableNote() + "不允许" + action.getCh() + "操作");
}
model.addAttribute("datas", result);
return "table";
}
@Override
protected boolean checkAction(DBAction action) {
return false;
}
}

@ -0,0 +1,29 @@
package web.html;
import java.util.HashMap;
import java.util.Map;
public enum ElementId {
menu("menu_"),
button("btn_"),
iframe("iframe_")
;
private String id;
ElementId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public static Map<String,ElementId> getAll(){
Map<String,ElementId> map=new HashMap<>();
for(ElementId id:ElementId.values()){
map.put(id.name(),id);
}
return map;
}
}

@ -0,0 +1,14 @@
package web.service;
import core.service.BaseService;
import db.config.HibernateConfig;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Service;
@Service
public class BiliService extends BaseService {
@Override
protected HibernateTemplate getHibernateTemplate() {
return HibernateConfig.get("test2");
}
}

@ -1,12 +1,14 @@
package web.service;
import core.service.BaseService;
import db.model.CidEntity;
import db.model.DataModel;
import db.config.HibernateConfig;
import db.model.bilibili.CidEntity;
import db.model.bilibili.DataModel;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
@ -25,6 +27,11 @@ public class DataService extends BaseService {
private boolean isStop;
@Override
protected HibernateTemplate getHibernateTemplate() {
return HibernateConfig.get("test1");
}
public void start(Integer threadSize){
isStop=false;
executor = new ThreadPoolTaskExecutor();
@ -99,12 +106,12 @@ public class DataService extends BaseService {
private void save(Integer id) {
try {
DataModel dataModel = baseDao1.get(DataModel.class, id);
CidEntity cidEntity = baseDao1.get(CidEntity.class, id);
DataModel dataModel = getHibernateTemplate().get(DataModel.class, id);
CidEntity cidEntity = getHibernateTemplate().get(CidEntity.class, id);
if (dataModel != null && cidEntity != null && cidEntity.getTypeid() != null) {
dataModel.setTypeId(cidEntity.getTypeid());
baseDao2.executeWithNativeSession((Session session) -> {
getHibernateTemplate().executeWithNativeSession((Session session) -> {
session.beginTransaction();
int i = 1;
String sql = "insert into data_" + cidEntity.getTypeid() + " (aid, author, backup_vid, cache, cover, dispatch, dispatch_servers, dp_done, dp_done_flv, dp_done_hdmp4, dp_done_mp4, duration, files, letv_addr, letv_vid, letv_vu, mid, page, storage, storage_server, subtitle, title, type, type_id, upload, upload_meta, vid, vp, cid) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
@ -123,4 +130,5 @@ public class DataService extends BaseService {
}
}
}

@ -1,19 +1,18 @@
package web.util;
import core.dao.BaseDao1;
import db.model.ScheduledTaskEntity;
import db.model.TaskEntity;
import db.model.bilibili.ScheduledTaskEntity;
import db.model.bilibili.TaskEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
@ -25,16 +24,17 @@ import java.util.List;
* Created by reborn on 2017/5/8.
* 动态定时器任务管理类
*/
@Component
//@Component
public class DynamicTimer extends ScheduledTaskRegistrar {
private static Logger log=LogManager.getLogger();
@Resource
private BaseDao1 baseDao;
@Resource
private HibernateTemplate hibernateTemplate;
@PostConstruct
public void init(){
List<ScheduledTaskEntity> taskList=baseDao.loadAll(ScheduledTaskEntity.class);
List<ScheduledTaskEntity> taskList=hibernateTemplate.loadAll(ScheduledTaskEntity.class);
for(ScheduledTaskEntity task:taskList){
addTriggerTask(task);
}

@ -1,16 +1,8 @@
#-----------------------hibernate\u914D\u7F6E-----------------------------
#hibernate\u914D\u7F6E
db_url=jdbc:mysql://mysql.sukura.top:8635/rootdb?serverTimezone=UTC&useSSL=false
db_username=sukura
db_password=Luffy9412!
hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver
#\u6570\u636E\u6E901
hibernate.connection.url=jdbc:mysql://sukura.top:3306/bilibili?serverTimezone=UTC&useSSL=false
hibernate.connection.username=sukura
hibernate.connection.password=@
#\u6570\u636E\u6E902
hibernate.connection.url2=jdbc:mysql://mysql.sukura.top:8635/bilibili?serverTimezone=UTC&useSSL=false
hibernate.connection.username2=sukura
hibernate.connection.password2=Luffy9412!
#-----------------------DruidDataSource\u914D\u7F6E-----------------------
druid.maxActive=20
spring.scan=core,web,db
sessionFactory.scan=db.model
#DruidDataSource\u914D\u7F6E
druid.maxActive=20

@ -0,0 +1,13 @@
#
#
##\u6570\u636E\u6E901
#hibernate.connection.url1=jdbc:mysql://sukura.top:3306/bilibili?serverTimezone=UTC&useSSL=false
#hibernate.connection.username1=sukura
#hibernate.connection.password1=@
#
##\u6570\u636E\u6E902
#hibernate.connection.url2=jdbc:mysql://mysql.sukura.top:8635/bilibili?serverTimezone=UTC&useSSL=false
#hibernate.connection.username2=sukura
#hibernate.connection.password2=Luffy9412!

@ -32,7 +32,7 @@
$(this).addClass('active');
$(this).siblings().removeClass('active');
iframe=$('#iframe_'+$(this).data("id"));
iframe=$('#${elementPreifx['iframe'].id}'+$(this).data('id'));
iframe.addClass('active show');
iframe.siblings().removeClass('active show');
@ -50,7 +50,7 @@
button.remove();
$('#iframe_'+button.data("id")).remove();
$('#${elementPreifx['iframe'].id}'+$(this).parent().data('id')).remove();
});
});
</script>

@ -7,10 +7,11 @@
--%>
<!DOCTYPE html>
<html lang="en">
<%@ page pageEncoding="utf-8"%>
<%@ page pageEncoding="utf-8" %>
<head>
<script id="a_tmpl" type="text/x-jquery-tmpl">
<a href="#" class="list-group-item list-group-item-action list-group-item-success" id="menu{{= id}}" data-id="{{= id}}" data-name="{{= name}}" data-href="{{= href}}"></a>
<a href="#" class="list-group-item list-group-item-action list-group-item-success" id="${elementPreifx['menu'].id}{{= id}}" data-id="{{= id}}" data-name="{{= name}}" data-href="{{= href}}"></a>
</script>
<script id="span_tmpl" type="text/x-jquery-tmpl">
@ -25,13 +26,21 @@
{{/if}}
</script>
<script id="button_tmpl" type="text/x-jquery-tmpl">
<button type="button" id="btn_{{= id}}" class="btn btn-secondary btn-lg" data-id="{{= id}}">
<button type="button" id="${elementPreifx['button'].id}{{= id}}" class="btn btn-secondary btn-lg" data-id="{{= id}}">
{{= name}}
<i class="fas fa-times" style="display: none"></i>
</button>
</script>
<script id="iframe_tmpl" type="text/x-jquery-tmpl">
<div id="${elementPreifx['iframe'].id}{{= id}}" class="tab-pane fade embed-responsive embed-responsive-16by9" >
<iframe class="embed-responsive-item" src="{{= src}}" ></iframe>
</div>
</script>
<script>
@ -64,39 +73,42 @@
for (var menu in menus) {
id = menus[menu].id;
menuId=$("#a_tmpl").tmpl({'id':id,'name':menus[menu].menuName,'href':menus[menu].href}).appendTo('.list-group');
menuId = $("#a_tmpl").tmpl({
'id': id,
'name': menus[menu].menuName,
'href': menus[menu].href
}).appendTo('.list-group');
if (menus[menu].menuLevel > 0) {
menuId.addClass('offset-' + menus[menu].menuLevel).addClass('menu' + menus[menu].parentId);
menuId.addClass('offset-' + menus[menu].menuLevel).addClass('${elementPreifx['menu'].id}' + menus[menu].parentId);
menuId.hide();
}
$("#span_tmpl").tmpl({'name':menus[menu].menuName,'length':menus[menu].childMenu.length}).appendTo(menuId);
$("#span_tmpl").tmpl({
'name': menus[menu].menuName,
'length': menus[menu].childMenu.length
}).appendTo(menuId);
if (menus[menu].childMenu.length > 0) {
menuId.click(showMenu);
addMenu(menus[menu].childMenu,menus[menu].href);
addMenu(menus[menu].childMenu, menus[menu].href);
} else {
menuId.click(function () {
btnId = '#btn_' + $(this).data('id');
button = $("#button_tmpl").tmpl({'id': $(this).data('id'), 'name': $(this).text()});
if ($(btnId).length == 0) {
$("#tabs").append('<button type="button" id="' + btnId.substr(1) + '" class="btn btn-secondary btn-lg" data-id="' + $(this).data('id') + '">' + $(this).text() + '\n' +
' <i class="fas fa-times" style="display: none"></i>\n' +
' </button>')
if ($('#' + button.attr('id')).length === 0) {
button.appendTo("#tabs");
}
$(btnId).click();
$('#' + button.attr('id')).click();
iframe = $("#iframe_tmpl").tmpl({'id':$(this).data('id'),'src':$(this).data('href')});
if ($('#' + iframe.attr('id')).length === 0) {
iframe.appendTo('#nav-tabContent');
iframe = '#iframe_' + $(this).data('id');
if ($(iframe).length == 0) {
$(top.document).find('#nav-tabContent').append('<div id="' + iframe.substr(1) + '" class="tab-pane fade embed-responsive embed-responsive-16by9" >\n' +
' <iframe class="embed-responsive-item" src="' + $(this).data('href') + '"></iframe>\n' +
' </div>');
}
$(iframe).addClass('active show');
$(iframe).siblings().removeClass('active show');
iframe.addClass('active show');
iframe.siblings().removeClass('active show');
});
}
}

@ -1,11 +1,87 @@
<!DOCTYPE html>
<html lang="en">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!--输出,条件,迭代标签库-->
<%@ page pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!--输出,条件,迭代标签库-->
<%@ page pageEncoding="utf-8" %>
<head>
<c:import url="head.jsp"/>
<script>
$(function () {
$("#pageButton button").click(function () {
$("[name=firstResult]").val($(this).val());
$('#command').submit();
});
});
</script>
</head>
<body>
table
<c:choose>
<c:when test="${datas.type=='success'}">
<table class="table">
<thead>
<tr>
<th scope="col">cid</th>
<th scope="col">aid</th>
<th scope="col">title</th>
<th scope="col">subtitle</th>
<th scope="col">author</th>
</tr>
</thead>
<tbody>
<c:forEach items="${datas.datas}" var="data">
<tr>
<td>${data.cid}</td>
<td>${data.aid}</td>
<td>${data.title}</td>
<td>${data.subtitle}</td>
<td>${data.author}</td>
</tr>
</c:forEach>
</tbody>
</table>
<form:form action="/data/table">
<input type="hidden" name="firstResult" value="0"/>
<input type="hidden" name="maxResults" value="${datas.pageSize}"/>
<div class="row">
<div class="col-sm-6">
<p class="text-justify font-weight-bold">
Showing ${(datas.currentPage-1)*datas.pageSize+1} to ${datas.currentPage*datas.pageSize}
of ${datas.count} entries
</p>
</div>
<div class="col-sm-6">
<div id="pageButton" class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group mr-2" role="group">
<button value="0" type="button" class="btn btn-secondary">首页</button>
<button value="${datas.currentPage-2}" type="button" class="btn btn-secondary"
<c:if test="${datas.currentPage-2==-1}">disabled</c:if>>上一页
</button>
<button value="${datas.currentPage}" type="button" class="btn btn-secondary">下一页</button>
<button value="${datas.pages}" type="button" class="btn btn-secondary">尾页</button>
</div>
<div class="btn-group mr-2" role="group">
<c:forEach begin="${datas.currentPage+1}"
end="${datas.currentPage+9}" var="i">
<c:if test="${i<=datas.pages}">
<button value="${i}" type="button" class="btn btn-secondary">${i}</button>
</c:if>
</c:forEach>
</div>
</div>
</div>
</div>
</form:form>
</c:when>
<c:otherwise>
<div class="alert alert-danger text-center" role="alert">
请求数据失败
</div>
</c:otherwise>
</c:choose>
</body>
</html>

@ -1,6 +1,5 @@
import core.dao.BaseDao1;
import db.model.CidEntity;
import db.model.DataModel;
import db.model.bilibili.CidEntity;
import db.model.bilibili.DataModel;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
@ -14,25 +13,25 @@ import org.hibernate.criterion.Projections;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import web.config.AppConfig;
import web.config.SpringConfig;
import web.service.DataService;
import javax.annotation.Resource;
import java.io.File;
@ -48,14 +47,21 @@ import java.util.List;
public class SpringTest {
private static Logger log = LogManager.getLogger();
private MockMvc mockMvc;
@Autowired
WebApplicationContext wac;
@Resource
private BaseDao1 baseDao1;
private DefaultListableBeanFactory beanFactory;
@Resource
private DataService dataService;
private MockMvc mockMvc;
@Autowired
WebApplicationContext wac;
@Qualifier("hibernateTemplate_test1")
private HibernateTemplate baseDao1;
@Before
public void setup(){
@ -63,15 +69,15 @@ public class SpringTest {
}
@Test
public void test() throws Exception {
ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.get("/menu").param("firstResult","0").param("maxResults","0"));
ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.get("/data/table").param("firstResult","0").param("maxResults","10"));
resultActions.andDo(MockMvcResultHandlers.print()).andReturn();
}
// @Test
public void exportTableSql() {
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(baseDao1.getSessionFactory().getProperties()).build();
Metadata metadata = new MetadataSources(serviceRegistry).addAnnotatedClass(DataModel.class).buildMetadata();
SchemaExport schemaExport = new SchemaExport();
@ -131,16 +137,11 @@ public class SpringTest {
}
}
// @Test
@Test
public void test4() throws IOException {
DetachedCriteria criteria = DetachedCriteria.forClass(DataModel.class);
List<DataModel> dataEntities = (List<DataModel>) baseDao1.findByCriteria(criteria, 10, 10);
for (DataModel dataEntity : dataEntities) {
log.info(dataEntity.getCid());
}
// 查询总条数
Long count = baseDao1.executeWithNativeSession((Session session) -> (Long) DetachedCriteria.forClass(DataModel.class).setProjection(Projections.rowCount()).setProjection(Projections.groupProperty("groupId")).getExecutableCriteria(session).uniqueResult());
Long count = baseDao1.executeWithNativeSession((Session session) -> (Long) DetachedCriteria.forClass(DataModel.class).setProjection(Projections.rowCount()).getExecutableCriteria(session).uniqueResult());
log.info(count);
}
}

@ -1,3 +1,5 @@
import db.annotation.BiliBili;
import db.util.ClassScaner;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@ -5,6 +7,6 @@ public class Test {
private static Logger log = LogManager.getLogger();
public static void main(String[] args) {
ClassScaner.scan("db.model",BiliBili.class).forEach(aClass -> System.out.println(aClass));
}
}

@ -2,14 +2,13 @@ package web.controller;
import db.DBAction;
import db.model.TaskModel;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/test")
public class TestController extends BaseController<TaskModel>{
public class TestController extends BiliController<TaskModel>{
@Override
public boolean checkAction(DBAction action) {

Loading…
Cancel
Save