上一篇文章中,讲的第一、二步购买服务器和绑定域名,我就不细细讲了。本文中会讲解如何构建一个基本的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 配置文件,这里配置了2种环境下的配置,分别是local本地和prod生产环境。到时方便发布
spring.profiles.active: local
---
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请求到后台,再到数据库,再转回到前端展示整个流程完整的走完。
欢迎转载,转载请注明出处 http://www.dingyinwu.com
如果文章中有任何问题,请大家纠正,我会非常感激,一起进步。
网友评论