1. 程式人生 > >從零開始搭建自己的網站二:Springboot專案框架搭建

從零開始搭建自己的網站二:Springboot專案框架搭建

上一篇文章中,講的第一、二步購買伺服器和繫結域名,我就不細細講了。本文中會講解如何構建一個基本的Springboot+freemarker+mybatis專案框架

1、先建立Gradle專案,用Gradle來管理我們的專案。


2、建立目錄結構


3、具體程式碼

1)build.gradle 此處為整個專案的完整jar包。

group 'demo'
version '1.0.0'

apply plugin: 'java'
apply plugin: 'idea'

repositories {
    mavenCentral()
}

buildscript {
    ext {
        springBootVersion = '1.4.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'spring-boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-devtools')
    compile 'org.springframework.boot:spring-boot-starter-freemarker'
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-aop')
    compile('org.springframework.boot:spring-boot-starter-cache')
    compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.1.1')
    compile('mysql:mysql-connector-java:5.1.42')
    compile('commons-dbcp:commons-dbcp:1.2.2')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    compile 'com.alibaba:fastjson:1.2.33'
    compile 'org.apache.commons:commons-lang3:3.6'
    compile("org.springframework.boot:spring-boot-starter-redis:1.3.5.RELEASE")
    compile("org.springframework.data:spring-data-redis:1.7.2.RELEASE")
    compile 'dom4j:dom4j:1.6.1'
    compile 'com.thoughtworks.xstream:xstream:1.4.9'
    compile 'com.qiniu:qiniu-java-sdk:[7.2.0, 7.2.99]'
    compile 'org.json:json'
    compile 'commons-fileupload:commons-fileupload:1.3.2'
    compile 'commons-codec:commons-codec:1.9'
    compile 'net.sf.ehcache:ehcache'
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.17'
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.12'
}

ext {
    profile = System.getProperty("env") ?: "dev"
    println "[current profile]:" + profile
}

sourceSets {
    main {
        resources {
            srcDirs = ["src/main/resources", "env/$profile"]
        }
    }
}

jar {
    String someString = ''
    configurations.runtime.each {someString = someString + " lib//"+it.name}
    manifest {
        attributes 'Main-Class': 'com.dyw.Application'
        attributes 'Class-Path': someString
    }
}
//清除上次的編譯過的檔案
task clearPj(type:Delete){
    delete 'build','target'
}
task copyJar(type:Copy){
    from configurations.runtime
    into ('build/libs/lib')
}
//把JAR複製到目標目錄
task release(type: Copy,dependsOn: [build,copyJar]) {
// from 'conf'
// into ('build/libs/eachend/conf') // 目標位置
}
2)application.yaml 配置檔案,Springboot是約定優於配置
spring.profiles.active: prod
---
spring:
  profiles: local
  http:
    multipart:
      max-file-size: 1024KB
      max-request-size: 1024KB
  devtools.restart.enabled: true
  output.ansi.enabled: ALWAYS
  freemarker:
    suffix: .html
    settings:
      datetime_format: yyyy-MM-dd HH:mm:ss
      date_format: yyyy-MM-dd
      time_format: HH:mm:ss
      number_format: 0.######
      boolean_format: true,false
      auto_import: "'spring.ftl' as spring"
      whitespace_stripping: true
      default_encoding: UTF-8
      tag_syntax: auto_detect
      url_escaping_charset: UTF-8
      template_update_delay: 3
      locale: zh_CN
      cache_storage: strong:20,soft:250
  resources.chain.strategy:
    content.enabled: true
    fixed.version: 1
  mvc:
    favicon.enabled: false
    static-path-pattern: /**
---
spring:
  profiles: prod
  http:
    multipart:
      max-file-size: 1024KB
      max-request-size: 1024KB
  devtools.restart.enabled: true
  output.ansi.enabled: ALWAYS
  freemarker:
    suffix: .html
    settings:
      datetime_format: yyyy-MM-dd HH:mm:ss
      date_format: yyyy-MM-dd
      time_format: HH:mm:ss
      number_format: 0.######
      boolean_format: true,false
      auto_import: "'spring.ftl' as spring"
      whitespace_stripping: true
      default_encoding: UTF-8
      tag_syntax: auto_detect
      url_escaping_charset: UTF-8
      template_update_delay: 3
      locale: zh_CN
      cache_storage: strong:20,soft:250
  resources.chain.strategy:
    content.enabled: true
    fixed.version: 1
  mvc:
    favicon.enabled: false
    static-path-pattern: /**
3)Application 啟動類
/**
 * 程式入口
 */
@MapperScan("com.dyw.dao")
@EnableAutoConfiguration
@EnableCaching
@SpringBootApplication(scanBasePackages = "com.dyw")
public class Application extends WebMvcConfigurerAdapter implements EmbeddedServletContainerCustomizer {
    public static void main(String[] args) throws Exception {
        new SpringApplicationBuilder().bannerMode(Banner.Mode.OFF);
        SpringApplication application = new SpringApplication(Application.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }


    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setPassword("root123");
        dataSource.setUrl("jdbc:mysql://localhost/blog?useUnicode=true&characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }


    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(8088);
    }
}
4)GatewayController ,ArticleService,ArticleServiceImpl,ArticleDao
@Controller
public class GatewayController {
    @Autowired
    private ArticleService articleService;

    /**
     * 首頁
     */
    @RequestMapping(value = {"/", "index"})
    public String gateway(Model model) {
        List<Article> list = articleService.getArticleList();
        model.addAttribute("articles", list);
        return "homepage/index";
    }
}
public interface ArticleService {

    /**
     * 查詢所有的文章列表
     */
    List<Article> getArticleList();
}
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleDao articleDao;

    @Override
    public List<Article> getArticleList() {
        return articleDao.getArticleList();
    }
}
@Component
public interface ArticleDao {

    /**
     * 獲取文章
     */
    List<Article> getArticleList();
}
5)Article實體 此處先不用管欄位,後面我會詳細解釋。
public class Article {
    //ID
    private int id;
    //內容ID
    private int contentId;
    //標題
    private String title;
    //摘要
    private String abstr;
    //分類
    private String categoryId;
    //內容
    private String content;
    //時間
    private String createDate;
    //置頂
    private String top;
    //圖片地址
    private String imgurl;
    //關鍵詞
    private String key;

    private String keyValue;

    private String categoryValue;

    private int click;

    private int comment;

    public int getClick() {
        return click;
    }

    public void setClick(int click) {
        this.click = click;
    }

    public int getComment() {
        return comment;
    }

    public void setComment(int comment) {
        this.comment = comment;
    }

    public String getCategoryValue() {
        return categoryValue;
    }

    public void setCategoryValue(String categoryValue) {
        this.categoryValue = categoryValue;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getKeyValue() {
        return keyValue;
    }

    public void setKeyValue(String keyValue) {
        this.keyValue = keyValue;
    }

    public String getTop() {
        return top;
    }

    public void setTop(String top) {
        this.top = top;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getContentId() {
        return contentId;
    }

    public void setContentId(int contentId) {
        this.contentId = contentId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAbstr() {
        return abstr;
    }

    public void setAbstr(String abstr) {
        this.abstr = abstr;
    }

    public String getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public String getImgurl() {
        return imgurl;
    }

    public void setImgurl(String imgurl) {
        this.imgurl = imgurl;
    }
}
6)article_sqlmap.xml mybatis配置檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dyw.dao.ArticleDao" >
    <resultMap id="article" type="com.dyw.model.Article" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="contentId" property="contentId" jdbcType="INTEGER" />
        <result column="title" property="title" jdbcType="VARCHAR" />
        <result column="abstr" property="abstr" jdbcType="VARCHAR" />
        <result column="categoryId" property="categoryId" jdbcType="VARCHAR" />
        <result column="imgurl" property="imgurl" jdbcType="VARCHAR" />
        <result column="createDate" property="createDate" jdbcType="VARCHAR" />
        <result column="top" property="top" jdbcType="VARCHAR" />
        <result column="key" property="key" jdbcType="VARCHAR" />
        <result column="keyValue" property="keyValue" jdbcType="VARCHAR" />
        <result column="categoryValue" property="categoryValue" jdbcType="VARCHAR" />
    </resultMap>

    <select id="getArticleList" resultMap="article">
        select * from article
    </select>
</mapper>
7)index.html 頁面 我們在上面application.yaml中已經配置了freemarker,所以在頁面中可以直接用freemarker語法
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>丁垠午部落格首頁</title>
</head>

<body>
<#list articles as article>
  ${article.title}</br>
</#list>

</body>
</html>
8)啟動Application中的main方法,執行專案。效果如下,整個專案基本框架搭建完成,而且我們也從http請求到後臺,再到資料庫,再轉回到前端展示整個流程完整的走完。

如果文章中有任何問題,請大家糾正,我會非常感激,一起進步。