最近瀏覽很多博客,學習了不少新的知識,收穫頗多,就想着能不能將新學的知識整合一下來練練手,提高自己擼代碼搭框架的能力,還有就是給大家一個新年福利,爬一爬美女圖片網站。上車請刷卡,哈哈。順便就拿這爬來的數據作爲基礎數據來整合最近學習的框架。一勞多得。當然,本文還是以框架整合爲主,爬取美女圖片只是爲了獲取基礎數據而已啦!!
現在我將我的學習成果分享出來,還望各位大神多多指點,有些不規範的地方還望大家指出,多多討論學習,共同進步。源碼我已經託管到我的碼雲上面,大家可以進我的博客查看,如果想要圖片資源的話在評論區留下郵箱吧。
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 個人博客地址:http://z77z.oschina.io/ ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
先上成果(19禁!!)
爬取的圖片,一共爬了一萬多張,夠大家玩一陣了。。。--------羞澀。。
數據庫:
存儲每個圖片集合的鏈接,標題等信息。
存儲每張圖片的鏈接,並且和圖片集合表關聯。
項目整體搭建出來後的效果
使用工具,框架介紹
這裏只介紹下最近學習的框架,其他在後面用到在做介紹。這兩個框架都是對現有的spring和mybatis的一個提升,而並不是替代之前的框架,使開發者能夠達到敏捷開發的目的。只推薦老司機學習,新手還是建議從基礎入手。
- SpringBoot
Spring由於其繁瑣的配置,一度被人認爲“配置地獄”,各種XML、Annotation配置,讓人眼花繚亂,而且如果出錯了也很難找出原因。想想之前搭建一個SSM框架,配置文件相當惱火,springboot的出現就大大減少了這些配置,甚至可以零配置文件。這裏推薦一個此框架學習的博客鏈接:http://blog.720ui.com/page/3/
- MybatisPlus:
這個框架是國內的大神編寫的,我個人認爲這就是一個mybatis的一個增強工具包,好處請大家自行去官方文檔查閱,這裏就不再贅述了。文檔鏈接:http://mp.baomidou.com/docs/index.html
建立數據庫
這裏數據來源是爬蟲爬取的。這裏爬蟲本身就不多介紹,我之前已經寫過爬蟲相關文章,出門左拐,我的個人博客中。
/*
Navicat MySQL Data Transfer
Source Server : 本地
Source Server Version : 50610
Source Host : localhost:3306
Source Database : crawler
Target Server Type : MYSQL
Target Server Version : 50610
File Encoding : 65001
Date: 2017-01-22 22:40:13
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for beautiful_pictures
-- ----------------------------
DROP TABLE IF EXISTS `beautiful_pictures`;
CREATE TABLE `beautiful_pictures` (
`id` varchar(255) NOT NULL COMMENT '美女圖片爬取',
`title` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`pictureurls_num` int(11) DEFAULT NULL,
`zan` int(11) DEFAULT NULL,
`biaoqian` varchar(255) DEFAULT NULL,
`keywords` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for picture
-- ----------------------------
DROP TABLE IF EXISTS `picture`;
CREATE TABLE `picture` (
`id` varchar(255) NOT NULL COMMENT '每張圖片的地址',
`pictures_id` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
整合框架的搭建
新建項目添加配置文件
我這裏使用的IDE工具是Spring Tool Suite,spring開發的首選開發工具 新建一個maven project ,選擇maven-archetypr-webapp這個文件結構模版。 配置pom.xml文件和application.properties文件
pom.xml
<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.baomidou</groupId>
<artifactId>mybatisplus-spring-boot</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>Mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- mybatisPlus代碼生成模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<!-- druid阿里巴巴數據庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
<!-- MP 核心庫 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.0.1</version>
</dependency>
<!-- JUnit test dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.3.3</version>
<scope>test</scope>
</dependency>
<!-- fastjson阿里巴巴jSON處理器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
#view
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
# jdbc_config
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/crawler?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#druid_config
spring.datasource.max-active: 20
spring.datasource.initial-size: 1
spring.datasource.min-idle: 3
spring.datasource.max-wait: 60000
spring.datasource.time-between-eviction-runs-millis: 60000
spring.datasource.min-evictable-idle-time-millis: 300000
spring.datasource.test-while-idle: true
spring.datasource.test-on-borrow: false
spring.datasource.test-on-return: false
spring.datasource.poolPreparedStatements: true
# mybatis_config
mybatis.mapper-locations=classpath:io/z77z/mapper/*Mapper.xml
mybatis.typeAliasesPackage=io.z77z.entity
# log_config DEBUG ERROR INFO WARN
logging.level.root=WARN
logging.file=./logs/spring-boot-logging.log
如果pom.xml報錯,大部分原因都是因爲jar包沒有下載成功,可以手動下載後放到maven本地倉庫裏面,阿里maven鏡像倉庫鏈接:http://maven.aliyun.com/nexus/#welcome
編寫MybatisPlusConfig.java
對mybatisplus的一些配置,配置成Bean交給spring容器管理
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType("mysql");
return page;
}
/**
* 這裏全部使用mybatis-autoconfigure 已經自動加載的資源。不手動指定
* 配置文件和mybatis-boot的配置文件同步
* @return
*/
@Bean
public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(dataSource);
mybatisPlus.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
mybatisPlus.setConfiguration(properties.getConfiguration());
if (!ObjectUtils.isEmpty(this.interceptors)) {
mybatisPlus.setPlugins(this.interceptors);
}
// MP 全局配置,更多內容進入類看註釋
GlobalConfiguration globalConfig = new GlobalConfiguration();
globalConfig.setDbType(DBType.MYSQL.name());
// ID 策略 AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
globalConfig.setIdType(3);
mybatisPlus.setGlobalConfig(globalConfig);
MybatisConfiguration mc = new MybatisConfiguration();
mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
mybatisPlus.setConfiguration(mc);
if (this.databaseIdProvider != null) {
mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
}
return mybatisPlus;
}
使用mybatisplus的代碼生成插件
MpGenerator.java
/**
* <p>
* 代碼生成器演示
* </p>
*/
public class MpGenerator {
/**
* <p>
* MySQL 生成演示
* </p>
*/
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("C://");
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setEnableCache(false);// XML 二級緩存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor("z77z");
// 自定義文件命名,注意 %s 會自動填充表實體屬性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sDao");
// gc.setServiceName("MP%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/crawler?characterEncoding=utf8");
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//strategy.setTablePrefix("beautiful_");// 此處可以修改爲您的表前綴
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[] { "beautiful_pictures" }); // 需要生成的表
strategy.setInclude(new String[] { "picture" }); // 需要生成的表
// strategy.setExclude(new String[]{"test"}); // 排除生成的表
// 字段名生成策略
strategy.setFieldNaming(NamingStrategy.underline_to_camel);
// 自定義實體父類
// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
// 自定義實體,公共字段
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
// 自定義 mapper 父類
// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
// 自定義 service 父類
// strategy.setSuperServiceClass("com.baomidou.demo.TestService");
// 自定義 service 實現類父類
// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
// 自定義 controller 父類
// strategy.setSuperControllerClass("com.baomidou.demo.TestController");
// 【實體】是否生成字段常量(默認 false)
// public static final String ID = "test_id";
// strategy.setEntityColumnConstant(true);
// 【實體】是否爲構建者模型(默認 false)
// public User setName(String name) {this.name = name; return this;}
// strategy.setEntityBuliderModel(true);
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("io");
pc.setModuleName("z77z");
mpg.setPackageInfo(pc);
// 注入自定義配置,可以在 VM 中使用 cfg.abc 設置的值
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
mpg.setCfg(cfg);
// 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/template 下面內容修改,
// 放置自己項目的 src/main/resources/template 目錄下, 默認名稱一下可以不配置,也可以自定義模板名稱
// TemplateConfig tc = new TemplateConfig();
// tc.setController("...");
// tc.setEntity("...");
// tc.setMapper("...");
// tc.setXml("...");
// tc.setService("...");
// tc.setServiceImpl("...");
// mpg.setTemplate(tc);
// 執行生成
mpg.execute();
// 打印注入設置
System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
新建上面java文件,註釋已經解釋的很清楚了,這裏就不多說,配置好後直接運行,就會得到相應模塊代碼,直接將其稍作修改放到項目中即可。
對插件生成的代碼簡要分析
就拿生成的mapper文件做說明:
如上圖所示生成的mapper繼承了一個類,是mybatisplus提供的,查看其源碼可以發現,繼承的類裏面封裝了一些常用的通用的增刪改查的代碼,還有對分頁查詢的處理。簡化了開發的代碼量,只需要專注於業務邏輯的編寫和實現,源碼如下:
/**
* <p>
* Mapper 繼承該接口後,無需編寫 mapper.xml 文件,即可獲得CRUD功能
* </p>
* <p>
* 這個 Mapper 支持 id 泛型
* </p>
*
* @author hubin
* @Date 2016-01-23
*/
public interface BaseMapper<T> {
/**
* <p>
* 插入一條記錄
* </p>
*
* @param entity
* 實體對象
* @return int
*/
Integer insert(T entity);
/**
* <p>
* 根據 ID 刪除
* </p>
*
* @param id
* 主鍵ID
* @return int
*/
Integer deleteById(Serializable id);
/**
* <p>
* 根據 columnMap 條件,刪除記錄
* </p>
*
* @param columnMap
* 表字段 map 對象
* @return int
*/
Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);
/**
* <p>
* 根據 entity 條件,刪除記錄
* </p>
*
* @param wrapper
* 實體對象封裝操作類(可以爲 null)
* @return int
*/
Integer delete(@Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 刪除(根據ID 批量刪除)
* </p>
*
* @param idList
* 主鍵ID列表
* @return int
*/
Integer deleteBatchIds(List<? extends Serializable> idList);
/**
* <p>
* 根據 ID 修改
* </p>
*
* @param entity
* 實體對象
* @return int
*/
Integer updateById(T entity);
/**
* <p>
* 根據 whereEntity 條件,更新記錄
* </p>
*
* @param entity
* 實體對象
* @param wrapper
* 實體對象封裝操作類(可以爲 null)
* @return
*/
Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 根據 ID 查詢
* </p>
*
* @param id
* 主鍵ID
* @return T
*/
T selectById(Serializable id);
/**
* <p>
* 查詢(根據ID 批量查詢)
* </p>
*
* @param idList
* 主鍵ID列表
* @return List<T>
*/
List<T> selectBatchIds(List<? extends Serializable> idList);
/**
* <p>
* 查詢(根據 columnMap 條件)
* </p>
*
* @param columnMap
* 表字段 map 對象
* @return List<T>
*/
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
/**
* <p>
* 根據 entity 條件,查詢一條記錄
* </p>
*
* @param entity
* 實體對象
* @return T
*/
T selectOne(@Param("ew") T entity);
/**
* <p>
* 根據 Wrapper 條件,查詢總記錄數
* </p>
*
* @param wrapper
* 實體對象
* @return int
*/
Integer selectCount(@Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 根據 entity 條件,查詢全部記錄
* </p>
*
* @param wrapper
* 實體對象封裝操作類(可以爲 null)
* @return List<T>
*/
List<T> selectList(@Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 根據 Wrapper 條件,查詢全部記錄
* </p>
*
* @param wrapper
* 實體對象封裝操作類(可以爲 null)
* @return List<T>
*/
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 根據 Wrapper 條件,查詢全部記錄
* </p>
*
* @param wrapper
* 實體對象封裝操作類(可以爲 null)
* @return List<Object>
*/
List<Object> selectObjs(@Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 根據 entity 條件,查詢全部記錄(並翻頁)
* </p>
*
* @param rowBounds
* 分頁查詢條件(可以爲 RowBounds.DEFAULT)
* @param wrapper
* 實體對象封裝操作類(可以爲 null)
* @return List<T>
*/
List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
/**
* <p>
* 根據 Wrapper 條件,查詢全部記錄(並翻頁)
* </p>
*
* @param rowBounds
* 分頁查詢條件(可以爲 RowBounds.DEFAULT)
* @param wrapper
* 實體對象封裝操作類
* @return List<Map<String, Object>>
*/
List<Map<String, Object>> selectMapsPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);
}
對於其他的生成文件大家可以依照這個思路去查看其源碼,結合之前傳統的SSM開發,瞭解其原理。
創建springboot入口Application.java
需要注意的地方我都寫在註釋裏面了,這裏我是把爬蟲的啓動也寫在這個配置文件裏面了,項目一啓動就會執行爬蟲。知道爬取的數據爲空就停止爬取。
/**
* springboot
*
* @author z77z
*
*/
// 掃描指定包下面的mapper接口
@MapperScan("io.z77z.dao")
// 該 @SpringBootApplication 註解等價於以默認屬性使用:
// @Configuration
// @EnableAutoConfiguration
// @ComponentScan
@SpringBootApplication
public class Application extends SpringBootServletInitializer implements CommandLineRunner {
@Autowired
BeautifulPicturesService beautifulPicturesService;
@Autowired
PictureService pictureService;
//入口
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//Java EE應用服務器配置,
//如果要使用tomcat來加載jsp的話就必須繼承SpringBootServletInitializer類並且重寫其中configure方法
@Override
protected SpringApplicationBuilder configure (SpringApplicationBuilder application) {
return application.sources(Application.class);
}
//springboot運行後此方法首先被調用
//實現CommandLineRunner抽象類中的run方法
@Override
public void run(String... args) throws Exception {
//返回值
int result = 1;
//訪問頁碼
Integer page = 1;
//啓動爬蟲
System.out.println("爬蟲開始工作!");
while(result==1){
result = crawler(page.toString());
page+=1;
if(result==0){
System.out.println("爬蟲運行結束!!");
}
}
}
public int crawler(String page){
//初始化返回值
int result = 1;
//網站首頁地址
String homeUrl = "http://www.87g.com/";
//接口地址
String url = "http://www.87g.com/index.php?m=content&c=content_ajax&a=picture_page&siteid=1&catid=35&page="+page;
System.out.println("當前爬取第"+ page +"頁數據");
//訪問接口,
JSONObject resultjson = CrawlerUtil.getReturnJson(url);
if(resultjson!=null){
//獲取其value值
Collection<Object> jsonList = resultjson.values();
for(Object obj : jsonList){
BeautifulPictures beautifulPictures = JSON.parseObject(obj.toString(), BeautifulPictures.class);
String Keywords = beautifulPictures.getKeywords();
//按map條件查詢。判斷是否已經爬過,沒有就入庫
Map<String, Object> map = new HashMap<String, Object>();
map.put("keywords", Keywords);
int cont = beautifulPicturesService.selectByMap(map).size();
if(cont==0){
//入庫
beautifulPicturesService.insert(beautifulPictures);
//訪問鏈接獲取document,並保存裏面的圖片
List<Picture> listPicture = CrawlerUtil.getArticleInfo(homeUrl+beautifulPictures.getUrl(),beautifulPictures);
for(Picture picture : listPicture){
//入庫
pictureService.insert(picture);
}
}else{
System.out.println(homeUrl+beautifulPictures.getUrl()+"頁面數據已經爬過了!!");
}
}
}else{
System.out.println("爬取到"+page+"頁時沒有數據了!!");
result = 0;
}
return result;
}
}
編寫測試jsp和controller
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
helloJsp
<hr>${user}
</body>
</html>
//如果是要返回jsp頁面就必須要使用@Controller而不是@RestController
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
BeautifulPicturesService beautifulPicturesService;
@RequestMapping("/test1")
public String view(Model model,Page<BeautifulPictures> page) {
Page<BeautifulPictures> pageList= beautifulPicturesService.selectPage(page);
model.addAttribute("user",JSON.toJSONString(pageList.getRecords()));
return "index";
}
}
運行
直接運行Application.java啓動項目,項目會運行在springboot內嵌的web容器中,本項目是使用的內嵌tomcat容器。運行成功後,在瀏覽器輸入http://localhost:8080/test/test1?current=2&size=10(curren代表要獲取的頁碼,size代表要獲取的數據條數)就會出現下面效果:
總結
- 使用這套框架來搭建項目,和之前SSM那套比起來簡單多咯,不需要過多的考慮配置文件,着重於業務邏輯代碼的編寫。
- 最開始引入項目pom文件報錯,手動下載jar包加入maven倉庫,解決。其他地方遇到的坑,我寫在代碼註釋裏面。
- 這個整合只是一個最基礎的配置,但是絕大部分需求是夠用了,直接在此框架基礎上橫向擴展就是了,如果有複雜的需求,還需要持續學習完善。
- 之後就拿這個集成框架爲基礎,有什麼新框架學習了就在上面練手。javaee全棧方向。