Idea 从头搭建Springboot+Maven的web项目

1、Springboot

1.1、Idea 从头搭建Springboot+Maven的web项目

1.创建新项目

打开编辑器,File-->New-->project,

2.配置环境变量

然后选择Spring Initializr,配置包的名称,路径等


3.添加依赖

选择依赖,这里我们添加Spring Web,Mybatis Framework,MySQLDriver这几个就可以,添加成功后可以在右侧看到


4.项目目录结构

点击Finish项目创建完毕,目录结构如下所示:


5.配置application.yml

首先将application.properties重命名为.yml文件,然后配置端口、数据库、和mybatis

server:

port:8080

spring:

devtools:

restart:

enabled:false

    livereload:

enabled:true

  datasource:

url: jdbc:mysql://localhost:3306/edison?serverTimezone=Asia/Shanghai&characterEncoding=utf-8

username: root

password: 4568

driver-class-name:com.mysql.cj.jdbc.Driver

mybatis:

mapper-locations: classpath:mapping/*.xml

type-aliases-package: com.example.model

#showSql

logging:

level:

com:

example:

mapper :debug


6.web界面测试

在static目录下创建index.html,随便写点测试内容,然后点击右上角的启动按钮


项目启动完成之后,打凯浏览器,输入“localhost:8080”,即可访问刚才写的测试页面


7.整合mybatis

a.使用generatoConfig.xml的配置完成逆向工程配置

首先在pom.xml中添加相关依赖和插件

<?xmlversion="1.0" encoding="UTF-8"?>

<projectxmlns="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 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.6.4</version>

<relativePath/><!-- lookup parent from repository -->

</parent>

<groupId>com.example</groupId>

<artifactId>springbootDemo</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>springbootDemo</name>

<description>springbootDemo</description>

<properties>

<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.mybatis.spring.boot</groupId>

<artifactId>mybatis-spring-boot-starter</artifactId>

<version>2.2.2</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.13</version>

</dependency>

<dependency>

<groupId>org.mybatis.generator</groupId>

<artifactId>mybatis-generator-core</artifactId>

<version>1.3.6</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis</artifactId>

<version>3.4.6</version>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

<!-- generator自动生成代码依赖包 -->

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

<!--generator插件-->

<plugin>

<groupId>org.mybatis.generator</groupId>

<artifactId>mybatis-generator-maven-plugin</artifactId>

<version>1.3.6</version>

<!--指定mybatis  core 可省略-->

<dependencies>

<dependency>

<groupId>org.mybatis.generator</groupId>

<artifactId>mybatis-generator-core</artifactId>

<version>1.3.6</version>

</dependency>

</dependencies>

<!--导入之后执行-->

<executions>

<execution>

<id>mybatis-generattor</id>

<!--phase阶段-->

<phase>package</phase>

<!--目的-->

<goals>

<goal>generate</goal>

</goals>

</execution>

</executions>

<!--插件配置-->

<configuration>

<!--是否允许移动生成的文件-->

<verbose>true</verbose>

<!--是否循序自动覆盖,测试环境为true 非测试false-->

<overwrite>true</overwrite>

<!--mybatis配置文件路径-->

<configurationFile>

                       src/main/resources/mybatis/generatorConfig.xml

</configurationFile>

</configuration>

</plugin>

</plugins>

</build>

</project>

然后在src/main/resources/mybatis下创建generatorConfig.xml,目录路径与pom.xml中的路径保持一致。具体配置信息如下:(注意生成文件的存放路径需要与项目的实际路径保持一致)。

<?xmlversion="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration

PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->

<classPathEntrylocation="D:\MvnLocal2\mysql\mysql-connector-java\8.0.13\mysql-connector-java-8.0.13.jar"/>

<contextid="mysql"targetRuntime="MyBatis3">

<commentGenerator>

<propertyname="suppressDate"value="true"/>

<!-- 是否去除自动生成的注释 true:是 : false:否 -->

<propertyname="suppressAllComments"value="true"/>

</commentGenerator>

<!--数据库链接URL,用户名、密码 -->

<jdbcConnectiondriverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://127.0.0.1:3306/edison?&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useLegacyDatetimeCode=false&amp;serverTimezone=Asia/Shanghai"

userId="root"password="4568">

</jdbcConnection>

<javaTypeResolver>

<propertyname="forceBigDecimals"value="false"/>

</javaTypeResolver>

<!-- 生成模型的包名和位置-->

<javaModelGeneratortargetPackage="com.example.springbootDemo.model"targetProject="src/main/java">

<propertyname="enableSubPackages"value="true"/>

<propertyname="trimStrings"value="true"/>

</javaModelGenerator>

<!-- 生成映射文件的包名和位置-->

<sqlMapGeneratortargetPackage="mapping"targetProject="src/main/resources">

<propertyname="enableSubPackages"value="true"/>

</sqlMapGenerator>

<!-- 生成DAO的包名和位置-->

<javaClientGeneratortype="XMLMAPPER"targetPackage="com.example.springbootDemo.dao"targetProject="src/main/java">

<propertyname="enableSubPackages"value="true"/>

</javaClientGenerator>

<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->

<tableschema=""tableName="userinfo"domainObjectName="UserInfo"enableCountByExample="true"

enableUpdateByExample="true"enableDeleteByExample="true"enableSelectByExample="true"

selectByExampleQueryId="true">

</table>

</context>

</generatorConfiguration>

配置完成后,Reload项目,然后点击maven下的mybatis-generator插件


运行结束后,dao、mapper、model自动创建完成,之后目录结构如下:


8.web查询demo

接下来我们可以通过简单的demo来实现前后台交互完成查询。

a.controller层

packagecom.example.controller;

importcom.alibaba.fastjson.JSONObject;

importcom.example.service.UserInfoService;

importcom.example.model.UserInfo;

importcom.example.model.UserInfoExample;

importcom.example.util.PbConstants;

importcom.sun.deploy.net.HttpResponse;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.web.bind.annotation.RequestMapping;

importorg.springframework.web.bind.annotation.RequestMethod;

importorg.springframework.web.bind.annotation.RestController;

importorg.springframework.web.servlet.ModelAndView;

importjavax.servlet.http.HttpServletRequest;

importjava.util.ArrayList;

importjava.util.List;

@RestController

@RequestMapping("/user")

publicclassUserInfoController{

@Autowired

privateUserInfoServiceuserInfoService;

/**

* 登录

* @return

*/

@RequestMapping(value="/login",method=RequestMethod.POST)

publicList<UserInfo>loginByusername(Stringusername,Stringpassword){

//        username = "edison";

//        password = "111";

returnuserInfoService.getUserInfo(username,password);

   }

/**

* 获取所有用户

* @return

*/

@RequestMapping(value="/getAllUserInfo",method=RequestMethod.GET)

publicList<UserInfo>getAllUserInfo(){

returnuserInfoService.getAllUserInfo();

   }

}

b.service层

packagecom.example.service;

importcom.alibaba.fastjson.JSONObject;

importcom.example.mapper.UserInfoMapper;

importcom.example.model.UserInfo;

importcom.example.model.UserInfoExample;

importcom.example.util.PbConstants;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.stereotype.Service;

importorg.springframework.web.servlet.ModelAndView;

importjava.util.ArrayList;

importjava.util.List;

@Service

publicclassUserInfoService{

@Autowired

privateUserInfoMapperuserInfoMapper;

publicList<UserInfo>getUserInfo(Stringusername,Stringpassword){

List<UserInfo>list=userInfoMapper.getUserInfo(username,password);

returnlist;

       }

publicList<UserInfo>getAllUserInfo(){

List<UserInfo>userInfos=newArrayList<>();

userInfos=userInfoMapper.getAllUserInfo();

returnuserInfos;

       }

}

c.由于model和mapper是自动生成的,因为我另外新加了一个查询所以表记录的方法,因此这里只展示mapper代码:

packagecom.example.mapper;

importcom.example.model.UserInfo;

importcom.example.model.UserInfoExample;

importjava.util.List;

importorg.apache.ibatis.annotations.*;

@Mapper

publicinterfaceUserInfoMapper{

longcountByExample(UserInfoExampleexample);

intdeleteByExample(UserInfoExampleexample);

@Delete({

"delete from userinfo",

"where id = #{id,jdbcType=VARCHAR}"

   })

intdeleteByPrimaryKey(Stringid);

@Insert({

"insert into userinfo (id, username, ",

"password, yxbz, ",

"by1, by2, by3, ",

"by4)",

"values (#{id,jdbcType=VARCHAR}, #{username,jdbcType=VARCHAR}, ",

"#{password,jdbcType=VARCHAR}, #{yxbz,jdbcType=VARCHAR}, ",

"#{by1,jdbcType=VARCHAR}, #{by2,jdbcType=VARCHAR}, #{by3,jdbcType=VARCHAR}, ",

"#{by4,jdbcType=VARCHAR})"

   })

intinsert(UserInforecord);

intinsertSelective(UserInforecord);

List<UserInfo>selectByExample(UserInfoExampleexample);

@Select({

"select",

"id, username, password, yxbz, by1, by2, by3, by4",

"from userinfo",

"where id = #{id,jdbcType=VARCHAR}"

   })

@ResultMap("com.example.mapper.UserInfoMapper.BaseResultMap")

UserInfoselectByPrimaryKey(Stringid);

@Select({

"select",

"id, username, password, yxbz, by1, by2, by3, by4",

"from userinfo",

"where username = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR} "

   })

@ResultMap("com.example.mapper.UserInfoMapper.BaseResultMap")

List<UserInfo>getUserInfo(Stringusername,Stringpassword);

@Select({

"select",

"id, username, password, yxbz, by1, by2, by3, by4",

"from userinfo"

   })

@ResultMap("com.example.mapper.UserInfoMapper.BaseResultMap")

List<UserInfo>getAllUserInfo();

intupdateByExampleSelective(@Param("record")UserInforecord,@Param("example")UserInfoExampleexample);

intupdateByExample(@Param("record")UserInforecord,@Param("example")UserInfoExampleexample);

intupdateByPrimaryKeySelective(UserInforecord);

@Update({

"update userinfo",

"set username = #{username,jdbcType=VARCHAR},",

"password = #{password,jdbcType=VARCHAR},",

"yxbz = #{yxbz,jdbcType=VARCHAR},",

"by1 = #{by1,jdbcType=VARCHAR},",

"by2 = #{by2,jdbcType=VARCHAR},",

"by3 = #{by3,jdbcType=VARCHAR},",

"by4 = #{by4,jdbcType=VARCHAR}",

"where id = #{id,jdbcType=VARCHAR}"

   })

intupdateByPrimaryKey(UserInforecord);

}

d.测试页面index.html

<!DOCTYPE html>

<htmllang="en">

<head>

<metacharset="UTF-8">

<title>springbootDemo</title>

<style>

       *{

margin:0;

padding:0;

       }

.result{

position:fixed;

width:100%;

bottom:0;

left:0;

height:600px;

background-color:rgba(0,0,0,.8);

color:white;

text-align:center;

letter-spacing:2px;

padding-top:20px;

font-size:18px;

line-height:28px;

overflow:scroll;

       }

</style>

</head>

<body>

<scriptsrc="https://code.jquery.com/jquery-3.1.1.min.js"></script>

<buttonstyle="display: block;margin: 20px auto;width: 160px;height: 60px;"onclick="getAll()">查看所有用户信息</button>

<divclass="result"id="result"></div>

<script>

functiongetAll(){

$.ajax({

type:"get",

url:"user/getAllUserInfo",

data: {

           },

success:function(data) {

console.log(data)

$("#result").empty()

for(vari=0;i<data.length;i++){

$("#result").append(JSON.stringify(data[i])+"<br>")

               }

           },

       });

   }

</script>

</body>

</html>

e.结果展示

点击运行项目,浏览输入localhost:8080,点击查询所有用户信息


至此,一个简单的springboot+maven的web项目demo就完成了。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容