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就完成了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容