用SpringBoot+Mysql+Maven+MyBatis项目写一个最简单注册(即插入)demo

项目SpringBoot+Mysql+Maven+MyBatis。IDE是IDEA 2018.3.X。

1.首先先看一下,pom文件需要的依赖

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>tang.chun</groupId>
    <artifactId>jia</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jia</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier><!-- 指定jdk版本 -->
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.8.1</version>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- mybatis 和 SpringBoot整合 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <!-- Mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <!-- JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
        <resources>
        <!-- maven项目中src源代码下的xml等资源文件编译进classes文件夹,
          注意:如果没有这个,它会自动搜索resources下是否有mapper.xml文件,
          如果没有就会报org.apache.ibatis.binding.BindingException: 
          Invalid bound statement (not found): com.pet.mapper.PetMapper.selectByPrimaryKey-->
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <!--将resources目录下的配置文件编译进classes文件  -->
        </resources>
    </build>
</project>

2.创建User实体类

package tang.chun.jia.registry.entity;
public class User {
    private String username;
    private String password;
    private String idcard;
    private int sex;
    private String realname;
    private Long  mobile;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getIdcard() {
        return idcard;
    }

    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    public Long getMobile() {
        return mobile;
    }

    public void setMobile(Long mobile) {
        this.mobile = mobile;
    }

    @Override
    public String toString() {
        return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", idcard='" + idcard + '\'' + ", sex=" + sex + ", realname='" + realname + '\'' + ", mobile=" + mobile + '}';
    }
}

3.创建UserMapper接口

package tang.chun.jia.registry.mapper;
import org.apache.ibatis.annotations.Mapper;
import tang.chun.jia.registry.entity.User;

@Mapper
public interface UserMapper  {

    void insertUser(User user);
}

4.创建UserMapper.xml

xml文件的名字必须和mapper接口一样

<?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="tang.chun.jia.registry.mapper.UserMapper">

<insert id="insertUser" parameterType ="tang.chun.jia.registry.entity.User">
  insert into user(username,password,idcard,sex,mobile,realname)
  values (#{username},#{password},#{idcard},#{sex},#{mobile},#{realname})
</insert>


</mapper>

5.创建UserService

package tang.chun.jia.registry.service;
import tang.chun.jia.registry.entity.User;

public interface UserService {

    void insertUser(User user);
}

6.创建UserServiceImp

UserService的实现类

package tang.chun.jia.registry.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tang.chun.jia.registry.mapper.UserMapper;
import tang.chun.jia.registry.entity.User;

@Service
public class UserServiceImp implements UserService {
    @Autowired(required=true)
    private UserMapper userMapper;

    public UserMapper getMapper() {
        return userMapper;
    }

    public void setMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void insertUser(User user) {
        userMapper.insertUser(user);

    }
}


7.写一个Controller

package tang.chun.jia.registry.controller;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tang.chun.jia.registry.entity.User;
import tang.chun.jia.registry.service.UserService;


@Controller
public class RegistryUser {
    @Autowired
    private UserService userService;

    @RequestMapping(value="/registry",method= RequestMethod.POST)
    @ResponseBody
    public String insertUser(User user) {
        try {
            userService.insertUser(user);
            return "index.html";
        } catch(Exception e) {
            return "404.html";
        }
    }


}

8.现在写前端页面(样式不多)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <!--import vue-->
    <script type="text/javascript" src="http://vuejs.org/js/vue.min.js"></script>
    <!--import vue-resource-->
    <script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
    <!--import vue-axios-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!--    &lt;!&ndash;import ivew&ndash;&gt;
    <script type="text/javascript" src="http://unpkg.com/iview/dist/iview.min.js"></script>
    &lt;!&ndash;import ivew css&ndash;&gt;
    <link rel="stylesheet" type="text/css" href="http://unpkg.com/iview/dist/styles/iview.css">-->
</head>
<body>
<div id="app">
    <!--    <i-button @click="show">Click me!</i-button>
        <Modal v-model="visible" title="Welcome">Welcome to iView</Modal>-->
    <form action="/registry" method="post" id="user">
        <table>
            <tr>
                <td class="text_right">用户名:</td>
                <td class="text_left"><input placeholder="输入用户名" v-model="user.username" name="username" autocomplete="off"/></td>
            </tr>
            <tr>
                <td class="text_right">密码:</td>
                <td class="text_left"><input placeholder="请输入密码密码" type="password" v-model="user.password" name="password" autocomplete="off"/></td>
            </tr>
            <tr>
                <td class="text_right">再一次输入密码:</td>
                <td class="text_left"><input placeholder="请再次输入密码" type="password" v-model="passwords" autocomplete="off"/></td>
            </tr>
            <tr>
                <td class="text_right"> 身份证:</td>
                <td class="text_left"><input  placeholder="请输入身份证号码" v-model="user.idcard" type="number" name="idcard" autocomplete="off"/></td>
            </tr>
            <tr>
                <td class="text_right">sex:</td>
                <td class="text_left"><input type="radio" value="1" v-model="user.sex" name="sex">男<input type="radio" value="2" v-model="user.sex" name="sex">女</td>
            </tr>
            <tr>
                <td class="text_right">真实姓名:</td>
                <td class="text_left"><input placeholder="请输入真实姓名" v-model="user.realname" type="text" autocomplete="off" name="realname"/></td>
            </tr>
            <tr>
                <td class="text_right">手机号码:</td>
                <td class="text_left"><input  placeholder="请输入手机号码" v-model="user.mobile" type="number" autocomplete="off" name="mobile"/></td>
            </tr>
            <tr>
                <td class="text_right"><input type="submit" value="注册"/></td>
                <td class="text_left"><input type="reset" value="重置" /></td>
            </tr>
        </table>
    </form>
</div>
</body>
<script>
    var Vm =new Vue({
        el:"#app",
        data:{
            user:{},
            passwords:"",
        }
    })
</script>
<style>
    #app{
        text-align: center;
        margin:100px 500px;
    }
    .text_right{
        text-align: right;
    }
    .text_left{
        text-align: left;
    }
</style>
</html>

9.yml文件配置增加Mybatis配置:

mybatis:
  mapper-locations: classpath:tang/chun/jia/registry/mapper/*.xml
  type-aliases-package: tang.chun.jia.registry.entity

10.启动项目,进入页面

在这里插入图片描述点击注册按钮
在这里插入图片描述
查询数据库,发现数据已经进入到数据库里。
在这里插入图片描述

11.项目目录:

在这里插入图片描述
在这里插入图片描述
中间其实会碰到很多问题,比如扫不到Mapper接口,mapper.xml创建不了实例,from表单post不到后端,如果遇到这些问题,仔细对应依赖,接口类的注解,yml的配置,一定会解决的。

  • 15
    点赞
  • 117
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
好的,下面我为您介绍如何使用Spring Boot、Vue和MyBatis实现前后端登录注册的功能。 ### 环境搭建 首先,您需要在本地安装以下环境: - JDK 1.8+ - Maven - Node.js - Vue CLI - MySQL ### 创建数据库和表 在MySQL中创建一个名为“test”的数据库,然后创建一个名为“user”的表,用于存储用户信息。表结构如下: ```sql CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ``` ### 创建Spring Boot项目 使用Spring Initializr创建一个新的Spring Boot项目,并添加以下依赖: ```xml <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.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> ``` ### 配置数据源 在application.properties中添加以下配置: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` ### 创建实体类和Mapper接口 在src/main/java目录下创建一个名为“com.example.demo”的包,然后创建一个名为“User”的实体类: ```java public class User { private Integer id; private String username; private String password; // getter和setter方法省略 } ``` 然后在同一包下创建一个名为“UserMapper”的Mapper接口: ```java @Mapper public interface UserMapper { User selectByUsernameAndPassword(@Param("username") String username, @Param("password") String password); void insert(User user); } ``` ### 创建Controller 在com.example.demo包下创建一个名为“UserController”的Controller,用于处理前端发送的请求: ```java @RestController public class UserController { @Autowired private UserMapper userMapper; @PostMapping("/login") public User login(@RequestBody User user) { return userMapper.selectByUsernameAndPassword(user.getUsername(), user.getPassword()); } @PostMapping("/register") public void register(@RequestBody User user) { userMapper.insert(user); } } ``` ### 创建Vue项目 使用Vue CLI创建一个新的Vue项目,然后在src/main/resources/static目录下添加以下文件: - index.html - main.js - App.vue - Login.vue - Register.vue 其中,index.html作为Vue应用的入口文件,main.js作为Vue应用的入口脚本,App.vue为根组件,Login.vue和Register.vue分别为登录和注册页面的组件。 ### 编前端代码 在Login.vue中添加以下代码,用于发送登录请求: ```vue <template> <div> <input type="text" v-model="username" placeholder="用户名"> <input type="password" v-model="password" placeholder="密码"> <button @click="login">登录</button> </div> </template> <script> export default { data() { return { username: '', password: '' } }, methods: { login() { fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.username, password: this.password }) }) .then(response => response.json()) .then(user => console.log(user)) } } } </script> ``` 在Register.vue中添加以下代码,用于发送注册请求: ```vue <template> <div> <input type="text" v-model="username" placeholder="用户名"> <input type="password" v-model="password" placeholder="密码"> <button @click="register">注册</button> </div> </template> <script> export default { data() { return { username: '', password: '' } }, methods: { register() { fetch('/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: this.username, password: this.password }) }) } } } </script> ``` ### 启动项目 使用MavenSpring Boot项目打包成jar包,然后在命令行中执行以下命令启动项目: ``` java -jar demo.jar ``` 然后进入Vue项目所在的目录,执行以下命令启动前端服务器: ``` npm run serve ``` 最后,在浏览器中访问http://localhost:8080,即可看到登录和注册页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值