SpringBoot+SpringMVC+MybatisPlus框架整合練習(xí)之【美女圖片】爬蟲---圖文詳細流程

最近瀏覽很多博客,學(xué)習(xí)了不少新的知識,收獲頗多绊诲,就想著能不能將新學(xué)的知識整合一下來練練手,提高自己擼代碼搭框架的能力栓袖,還有就是給大家一個新年福利,爬一爬美女圖片網(wǎng)站店诗。上車請刷卡裹刮,哈哈。順便就拿這爬來的數(shù)據(jù)作為基礎(chǔ)數(shù)據(jù)來整合最近學(xué)習(xí)的框架庞瘸。一勞多得必指。當然,本文還是以框架整合為主恕洲,爬取美女圖片只是為了獲取基礎(chǔ)數(shù)據(jù)而已啦K稹!

現(xiàn)在我將我的學(xué)習(xí)成果分享出來霜第,還望各位大神多多指點葛家,有些不規(guī)范的地方還望大家指出,多多討論學(xué)習(xí)泌类,共同進步癞谒。源碼我已經(jīng)托管到我的碼云上面,大家可以進我的博客查看刃榨,如果想要圖片資源的話在評論區(qū)留下郵箱吧弹砚。

、枢希、桌吃、、苞轿、茅诱、逗物、、瑟俭、翎卓、、摆寄、失暴、、微饥、逗扒、、畜号、、允瞧、简软、、述暂、痹升、、畦韭、疼蛾、、艺配、察郁、、
個人博客地址:http://z77z.oschina.io/
转唉,皮钠,,赠法,麦轰,,砖织,款侵,,侧纯,新锈,,眶熬,壕鹉,剃幌,,晾浴,负乡,,脊凰,抖棘,,狸涌,切省,,帕胆,朝捆,,懒豹,芙盘,,脸秽,儒老,

先上成果(19禁!<遣汀)

爬取的圖片驮樊,一共爬了一萬多張,夠大家玩一陣了片酝。囚衔。。--------羞澀雕沿。佳魔。

爬取的圖片

數(shù)據(jù)庫:

存儲每個圖片集合的鏈接,標題等信息晦炊。

文章信息表

存儲每張圖片的鏈接鞠鲜,并且和圖片集合表關(guān)聯(lián)。

圖片信息表

項目整體搭建出來后的效果

項目文件結(jié)構(gòu)

使用工具断国,框架介紹

這里只介紹下最近學(xué)習(xí)的框架贤姆,其他在后面用到在做介紹。這兩個框架都是對現(xiàn)有的spring和mybatis的一個提升稳衬,而并不是替代之前的框架霞捡,使開發(fā)者能夠達到敏捷開發(fā)的目的。只推薦老司機學(xué)習(xí)薄疚,新手還是建議從基礎(chǔ)入手碧信。

  • SpringBoot

Spring由于其繁瑣的配置赊琳,一度被人認為“配置地獄”,各種XML砰碴、Annotation配置躏筏,讓人眼花繚亂,而且如果出錯了也很難找出原因呈枉。想想之前搭建一個SSM框架趁尼,配置文件相當惱火,springboot的出現(xiàn)就大大減少了這些配置猖辫,甚至可以零配置文件酥泞。這里推薦一個此框架學(xué)習(xí)的博客鏈接:http://blog.720ui.com/page/3/

  • MybatisPlus:

這個框架是國內(nèi)的大神編寫的,我個人認為這就是一個mybatis的一個增強工具包啃憎,好處請大家自行去官方文檔查閱芝囤,這里就不再贅述了。文檔鏈接:http://mp.baomidou.com/docs/index.html

建立數(shù)據(jù)庫

這里數(shù)據(jù)來源是爬蟲爬取的辛萍。這里爬蟲本身就不多介紹悯姊,我之前已經(jīng)寫過爬蟲相關(guān)文章,出門左拐叹阔,我的個人博客中挠轴。

/*
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開發(fā)的首選開發(fā)工具
新建一個maven project 耳幢,選擇maven-archetypr-webapp這個文件結(jié)構(gòu)模版。
配置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阿里巴巴數(shù)據(jù)庫連接池 -->
        <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 已經(jīng)自動加載的資源店印。不手動指定
 * 配置文件和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 全局配置,更多內(nèi)容進入類看注釋
    GlobalConfiguration globalConfig = new GlobalConfiguration();
    globalConfig.setDbType(DBType.MYSQL.name());
    // ID 策略 AUTO->`0`("數(shù)據(jù)庫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);
        // 數(shù)據(jù)源配置
        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 實現(xiàn)類父類
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定義 controller 父類
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【實體】是否生成字段常量(默認 false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【實體】是否為構(gòu)建者模型(默認 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 設(shè)置的值
        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 下面內(nèi)容修改,
        // 放置自己項目的 src/main/resources/template 目錄下, 默認名稱一下可以不配置付秕,也可以自定義模板名稱
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // mpg.setTemplate(tc);
        // 執(zhí)行生成
        mpg.execute();
        // 打印注入設(shè)置
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }
}

新建上面java文件兰珍,注釋已經(jīng)解釋的很清楚了,這里就不多說询吴,配置好后直接運行掠河,就會得到相應(yīng)模塊代碼亮元,直接將其稍作修改放到項目中即可。

對插件生成的代碼簡要分析

就拿生成的mapper文件做說明:

生成的mapper文件

如上圖所示生成的mapper繼承了一個類唠摹,是mybatisplus提供的爆捞,查看其源碼可以發(fā)現(xiàn),繼承的類里面封裝了一些常用的通用的增刪改查的代碼跃闹,還有對分頁查詢的處理嵌削。簡化了開發(fā)的代碼量,只需要專注于業(yè)務(wù)邏輯的編寫和實現(xiàn)望艺,源碼如下:

/**
 * <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>
     * 根據(jù) ID 刪除
     * </p>
     * 
     * @param id
     *            主鍵ID
     * @return int
     */
    Integer deleteById(Serializable id);

    /**
     * <p>
     * 根據(jù) columnMap 條件找默,刪除記錄
     * </p>
     * 
     * @param columnMap
     *            表字段 map 對象
     * @return int
     */
    Integer deleteByMap(@Param("cm") Map<String, Object> columnMap);

    /**
     * <p>
     * 根據(jù) entity 條件艇劫,刪除記錄
     * </p>
     * 
     * @param wrapper
     *            實體對象封裝操作類(可以為 null)
     * @return int
     */
    Integer delete(@Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 刪除(根據(jù)ID 批量刪除)
     * </p>
     * 
     * @param idList
     *            主鍵ID列表
     * @return int
     */
    Integer deleteBatchIds(List<? extends Serializable> idList);

    /**
     * <p>
     * 根據(jù) ID 修改
     * </p>
     * 
     * @param entity
     *            實體對象
     * @return int
     */
    Integer updateById(T entity);

    /**
     * <p>
     * 根據(jù) whereEntity 條件,更新記錄
     * </p>
     * 
     * @param entity
     *            實體對象
     * @param wrapper
     *            實體對象封裝操作類(可以為 null)
     * @return
     */
    Integer update(@Param("et") T entity, @Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 根據(jù) ID 查詢
     * </p>
     * 
     * @param id
     *            主鍵ID
     * @return T
     */
    T selectById(Serializable id);

    /**
     * <p>
     * 查詢(根據(jù)ID 批量查詢)
     * </p>
     * 
     * @param idList
     *            主鍵ID列表
     * @return List<T>
     */
    List<T> selectBatchIds(List<? extends Serializable> idList);

    /**
     * <p>
     * 查詢(根據(jù) columnMap 條件)
     * </p>
     * 
     * @param columnMap
     *            表字段 map 對象
     * @return List<T>
     */
    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    /**
     * <p>
     * 根據(jù) entity 條件惩激,查詢一條記錄
     * </p>
     * 
     * @param entity
     *            實體對象
     * @return T
     */
    T selectOne(@Param("ew") T entity);

    /**
     * <p>
     * 根據(jù) Wrapper 條件店煞,查詢總記錄數(shù)
     * </p>
     * 
     * @param wrapper
     *            實體對象
     * @return int
     */
    Integer selectCount(@Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 根據(jù) entity 條件,查詢?nèi)坑涗?     * </p>
     * 
     * @param wrapper
     *            實體對象封裝操作類(可以為 null)
     * @return List<T>
     */
    List<T> selectList(@Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 根據(jù) Wrapper 條件风钻,查詢?nèi)坑涗?     * </p>
     *
     * @param wrapper
     *            實體對象封裝操作類(可以為 null)
     * @return List<T>
     */
    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 根據(jù) Wrapper 條件顷蟀,查詢?nèi)坑涗?     * </p>
     *
     * @param wrapper
     *            實體對象封裝操作類(可以為 null)
     * @return List<Object>
     */
    List<Object> selectObjs(@Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 根據(jù) entity 條件,查詢?nèi)坑涗洠ú⒎摚?     * </p>
     * 
     * @param rowBounds
     *            分頁查詢條件(可以為 RowBounds.DEFAULT)
     * @param wrapper
     *            實體對象封裝操作類(可以為 null)
     * @return List<T>
     */
    List<T> selectPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);

    /**
     * <p>
     * 根據(jù) Wrapper 條件骡技,查詢?nèi)坑涗洠ú⒎摚?     * </p>
     *
     * @param rowBounds
     *            分頁查詢條件(可以為 RowBounds.DEFAULT)
     * @param wrapper
     *            實體對象封裝操作類
     * @return List<Map<String, Object>>
     */
    List<Map<String, Object>> selectMapsPage(RowBounds rowBounds, @Param("ew") Wrapper<T> wrapper);

}

對于其他的生成文件大家可以依照這個思路去查看其源碼鸣个,結(jié)合之前傳統(tǒng)的SSM開發(fā),了解其原理布朦。

創(chuàng)建springboot入口Application.java

需要注意的地方我都寫在注釋里面了囤萤,這里我是把爬蟲的啟動也寫在這個配置文件里面了,項目一啟動就會執(zhí)行爬蟲是趴。知道爬取的數(shù)據(jù)為空就停止爬取涛舍。

/**
 * 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應(yīng)用服務(wù)器配置,
    //如果要使用tomcat來加載jsp的話就必須繼承SpringBootServletInitializer類并且重寫其中configure方法
    @Override
    protected SpringApplicationBuilder configure (SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
    //springboot運行后此方法首先被調(diào)用
    //實現(xiàn)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("爬蟲運行結(jié)束8谎拧!");
            }
        }
    }
    
    
    
    public int crawler(String page){ 
        //初始化返回值
        int result = 1;
        //網(wǎng)站首頁地址
        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 +"頁數(shù)據(jù)");
        //訪問接口肛搬,
        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條件查詢没佑。判斷是否已經(jīng)爬過,沒有就入庫
                    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()+"頁面數(shù)據(jù)已經(jīng)爬過了M汲铩!");
                    }
                }
        }else{
            System.out.println("爬取到"+page+"頁時沒有數(shù)據(jù)了!远剩!");
            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內(nèi)嵌的web容器中,本項目是使用的內(nèi)嵌tomcat容器瓜晤。運行成功后锥余,在瀏覽器輸入http://localhost:8080/test/test1?current=2&size=10(curren代表要獲取的頁碼,size代表要獲取的數(shù)據(jù)條數(shù))就會出現(xiàn)下面效果:

這里寫圖片描述

總結(jié)

  • 使用這套框架來搭建項目痢掠,和之前SSM那套比起來簡單多咯驱犹,不需要過多的考慮配置文件,著重于業(yè)務(wù)邏輯代碼的編寫足画。
  • 最開始引入項目pom文件報錯雄驹,手動下載jar包加入maven倉庫,解決淹辞。其他地方遇到的坑医舆,我寫在代碼注釋里面。
  • 這個整合只是一個最基礎(chǔ)的配置象缀,但是絕大部分需求是夠用了蔬将,直接在此框架基礎(chǔ)上橫向擴展就是了,如果有復(fù)雜的需求央星,還需要持續(xù)學(xué)習(xí)完善霞怀。
  • 之后就拿這個集成框架為基礎(chǔ),有什么新框架學(xué)習(xí)了就在上面練手莉给。javaee全棧方向毙石。

荊軻~~ 刺秦王~~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市禁谦,隨后出現(xiàn)的幾起案子胁黑,更是在濱河造成了極大的恐慌废封,老刑警劉巖州泊,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異漂洋,居然都是意外死亡遥皂,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進店門刽漂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來演训,“玉大人,你說我怎么就攤上這事贝咙⊙颍” “怎么了?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長窟她。 經(jīng)常有香客問我陈症,道長,這世上最難降的妖魔是什么震糖? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任录肯,我火速辦了婚禮,結(jié)果婚禮上吊说,老公的妹妹穿的比我還像新娘论咏。我一直安慰自己,他們只是感情好颁井,可當我...
    茶點故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布厅贪。 她就那樣靜靜地躺著,像睡著了一般雅宾。 火紅的嫁衣襯著肌膚如雪卦溢。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天秀又,我揣著相機與錄音单寂,去河邊找鬼。 笑死吐辙,一個胖子當著我的面吹牛宣决,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播昏苏,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼尊沸,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了贤惯?” 一聲冷哼從身側(cè)響起洼专,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎孵构,沒想到半個月后屁商,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡颈墅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年蜡镶,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片恤筛。...
    茶點故事閱讀 40,424評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡官还,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出毒坛,到底是詐尸還是另有隱情望伦,我是刑警寧澤林说,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站屯伞,受9級特大地震影響述么,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜愕掏,卻給世界環(huán)境...
    茶點故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一度秘、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧饵撑,春花似錦剑梳、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至语卤,卻和暖如春追逮,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背粹舵。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工钮孵, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人眼滤。 一個月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓巴席,卻偏偏與公主長得像,于是被迫代替她去往敵國和親诅需。 傳聞我的和親對象是個殘疾皇子漾唉,可洞房花燭夜當晚...
    茶點故事閱讀 45,435評論 2 359

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)堰塌,斷路器赵刑,智...
    卡卡羅2017閱讀 134,693評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,838評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,262評論 25 707
  • 說一個人干凈般此,如今,是個極高的評價摇邦。 說一個男人干凈恤煞,是說他為人坦蕩屎勘,沒有陰暗施籍,算計,背叛概漱,欺瞞丑慎,兩面三刀,陽奉陰...
    午后窗前的貓閱讀 555評論 0 0
  • 文:橘島少女 圖:選自花瓣 又到了要交房租的時候 看了看自己的余額,再數(shù)了數(shù)接下來要過得日子 實在沒辦法竿裂,再一次向...
    橘島少女閱讀 183評論 0 2