【Spring Boot&&Spring Cloud系列】使用Intellij构建Spring Boot和Mybatis项目

本文介绍如何使用IntelliJ IDEA搭建SpringBoot与MyBatis整合的开发环境,并通过具体示例展示用户注册功能的实现过程。

一、创建项目

1、File->New->Project->spring initializer

2、勾选Web SQL Template Engines

3、项目生成之后,点击add as maven project 这时候会自动下载jar包

4、项目生成的目录结构

其中DemoApplication.java是项目主入口,编辑run/debug configuration即可运行

5、在生成的项目中新建自己需要的包

controller

entity

mapper

service

util

resources下的static文件夹下新建

css

fonts

img

js

resources下templates下新建需要的html文件

6、修改application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/dev
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#页面热加载
spring.thymeleaf.cache=false

二、代码编写

HelloWorld.controller.java

 1 package com.slp.controller;
 2 
 3 import com.slp.entity.User;
 4 import com.slp.service.IRegService;
 5 import com.slp.util.GenerateKeyUtil;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 8 import org.springframework.stereotype.Controller;
 9 import org.springframework.util.StringUtils;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestParam;
12 import org.springframework.web.bind.annotation.ResponseBody;
13 
14 import java.math.BigInteger;
15 import java.security.MessageDigest;
16 import java.security.NoSuchAlgorithmException;
17 
18 /**
19  * Created by sangliping on 2017/8/15.
20  * @Controller注解返回指定页面,也就是template文件夹下的页面
21  * @RestController相当于@Controller和@ResponseBody
22  * springboot默认会缓存templates下的文件,如果html页面修改后,看不到修改后的效果则修改热部署为false
23  */
24 @Controller
25 @EnableAutoConfiguration
26 public class HelloWorldController {
27     @Autowired
28     private IRegService regService;
29     @RequestMapping("/")
30     String home(){
31         return "index";
32     }
33 
34     @RequestMapping("/reg")
35     @ResponseBody
36     Boolean reg(@RequestParam("loginPwd")String loginNum,@RequestParam("userId")String userId){
37         System.out.println("进入注册页面");
38         User user = regService.findUserById(userId);//根据用户id查询用户
39         if(StringUtils.isEmpty(user)){//如果用户不存在则进行注册
40             String pwd =  this.createMD5(loginNum);
41             System.out.println(userId+"==="+loginNum);
42             String id = GenerateKeyUtil.getCharAndNumr(20);
43             regService.regUser(userId,pwd,id);
44         }
45      return true;
46     }
47 
48 
49     private String createMD5(String loginNum){
50         MessageDigest md = null;
51         try {
52             md = MessageDigest.getInstance("MD5");
53             md.update(loginNum.getBytes());
54         }catch (NoSuchAlgorithmException e){
55             e.printStackTrace();
56         }
57         return new BigInteger(1,md.digest()).toString();
58     }
59 
60 
61 
62     @RequestMapping("/register")
63     private String register(){
64         System.out.println("进入注册页面");
65 
66         return "login";
67     }
68 }

User.java

 1 package com.slp.entity;
 2 
 3 /**
 4  * Created by sangliping on 2017/8/15.
 5  */
 6 public class User {
 7     private String id;
 8     private String userId;
 9     private String pwd;
10 
11     public String getId() {
12         return id;
13     }
14 
15     public void setId(String id) {
16         this.id = id;
17     }
18 
19     public String getUserId() {
20         return userId;
21     }
22 
23     public void setUserId(String userId) {
24         this.userId = userId;
25     }
26 
27     public String getPwd() {
28         return pwd;
29     }
30 
31     public void setPwd(String pwd) {
32         this.pwd = pwd;
33     }
34 
35     @Override
36     public String toString() {
37         return "User{" +
38                 "id='" + id + '\'' +
39                 ", userId='" + userId + '\'' +
40                 ", pwd='" + pwd + '\'' +
41                 '}';
42     }
43 }

UserMapper.java

 1 package com.slp.mapper;
 2 
 3 import com.slp.entity.User;
 4 import org.apache.ibatis.annotations.Insert;
 5 import org.apache.ibatis.annotations.Mapper;
 6 import org.apache.ibatis.annotations.Param;
 7 import org.apache.ibatis.annotations.Select;
 8 
 9 /**
10  * Created by sangliping on 2017/8/15.
11  */
12 @Mapper
13 public interface UserMapper {
14     @Select("select * from users where userId = #{userId}")
15     User findUserByUserId(@Param("userId") String userId);
16 
17     @Insert("insert into users(id,userId,pwd) values(#{id},#{userId},#{pwd})")
18     boolean insertUsers (@Param("userId")String userId,@Param("pwd")String pwd,@Param("id")String id);
19 }

IRegService.java

 1 package com.slp.service;
 2 
 3 import com.slp.entity.User;
 4 
 5 /**
 6  * Created by sangliping on 2017/8/15.
 7  */
 8 public interface IRegService {
 9     boolean regUser(String userId,String pwd,String id);
10     User findUserById(String userId);
11 }

RegService.java

 1 package com.slp.service;
 2 
 3 import com.slp.entity.User;
 4 import com.slp.mapper.UserMapper;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 /**
 9  * Created by sangliping on 2017/8/15.
10  */
11 @Service()
12 public class RegService implements IRegService{
13     @Autowired
14     private UserMapper userMapper;
15 
16     @Override
17     public boolean regUser(String userId, String pwd,String id) {
18         boolean  flag = userMapper.insertUsers(userId,pwd,id);
19         return flag;
20     }
21 
22     @Override
23     public User findUserById(String userId) {
24         User user = userMapper.findUserByUserId(userId);
25         return user;
26     }
27 }

GenerateKeyUtil.java

 1 package com.slp.util;
 2 
 3 import java.util.Random;
 4 
 5 /**
 6  * Created by sangliping on 2017/8/15.
 7  */
 8 public class GenerateKeyUtil {
 9     public static String getCharAndNumr(int length) {
10         String val = "";
11         Random random = new Random();
12         for (int i = 0; i < length; i++) {
13             // 输出字母还是数字
14             String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
15             // 字符串
16             if ("char".equalsIgnoreCase(charOrNum)) {
17                 // 取得大写字母还是小写字母
18                 int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
19                 val += (char) (choice + random.nextInt(26));
20             } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
21                 val += String.valueOf(random.nextInt(10));
22             }
23         }
24         return val;
25     }
26 }

页面index.html

  1 <!DOCTYPE html>
  2 <html xmlns="http://www.thymeleaf.org">
  3 <head>
  4 
  5     <meta charset="utf-8"/>
  6     <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  7     <meta name="viewport" content="width=device-width, initial-scale=1"/>
  8     <title>登陆页面</title>
  9     <!-- CSS -->
 10     <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500"/>
 11     <link rel="stylesheet" href="/css/bootstrap.min.css"/>
 12     <link rel="stylesheet" href="/css/font-awesome.min.css"/>
 13     <link rel="stylesheet" href="/css/form-elements.css"/>
 14     <link rel="stylesheet" href="/css/style.css"/>
 15 
 16     <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
 17     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
 18     <!--[if lt IE 9]>
 19     <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
 20     <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
 21     <![endif]-->
 22 
 23     <!-- Favicon and touch icons -->
 24     <link rel="shortcut icon" href="/img/favicon.png"/>
 25     <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/img/apple-touch-icon-144-precomposed.png"/>
 26     <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/img/apple-touch-icon-114-precomposed.png"/>
 27     <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/img/apple-touch-icon-72-precomposed.png"/>
 28     <link rel="apple-touch-icon-precomposed" href="/img/apple-touch-icon-57-precomposed.png"/>
 29 
 30 </head>
 31 
 32 <body>
 33 
 34 <!-- Top content -->
 35 <div class="top-content">
 36 
 37     <div class="inner-bg">
 38         <div class="container">
 39             <div class="row">
 40                 <div class="col-sm-8 col-sm-offset-2 text">
 41                     <h3>没有账户请先<a href="http://localhost:8080/register">注册</a> </h3>
 42                     <div class="description">
 43                         <p>
 44 
 45                         </p>
 46                     </div>
 47                 </div>
 48             </div>
 49             <div class="row">
 50                 <div class="col-sm-6 col-sm-offset-3 form-box">
 51                     <div class="form-top">
 52                         <div class="form-top-left">
 53                             <h3>登 陆</h3>
 54                             <p>输入用户名和密码:</p>
 55                         </div>
 56                         <div class="form-top-right">
 57                             <i class="fa fa-key"></i>
 58                         </div>
 59                     </div>
 60                     <div class="form-bottom">
 61                         <form role="form" action="" method="post" class="login-form">
 62                             <div class="form-group">
 63                                 <label class="sr-only" for="form-username">用户名</label>
 64                                 <input type="text" name="form-username" placeholder="请输入用户名" class="form-username form-control" id="form-username"/>
 65                             </div>
 66                             <div class="form-group">
 67                                 <label class="sr-only" for="form-password">密  码</label>
 68                                 <input type="password" name="form-password" placeholder="请输入密码" class="form-password form-control" id="form-password"/>
 69                             </div>
 70                             <button type="submit" class="btn">登 陆!</button>
 71                         </form>
 72                     </div>
 73                 </div>
 74             </div>
 75             <div class="row">
 76                 <div class="col-sm-6 col-sm-offset-3 social-login">
 77                     <h3>或者使用第三方账户登陆:</h3>
 78                     <div class="social-login-buttons">
 79                         <a class="btn btn-link-1 btn-link-1-facebook" href="#">
 80                             <i class="fa fa-facebook"></i> Facebook
 81                         </a>
 82                         <a class="btn btn-link-1 btn-link-1-twitter" href="#">
 83                             <i class="fa fa-twitter"></i> Twitter
 84                         </a>
 85                         <a class="btn btn-link-1 btn-link-1-google-plus" href="#">
 86                             <i class="fa fa-google-plus"></i> Google Plus
 87                         </a>
 88                     </div>
 89                 </div>
 90             </div>
 91         </div>
 92     </div>
 93 
 94 </div>
 95 
 96 
 97 <!-- Javascript -->
 98 <script src="/js/jquery-1.11.1.min.js"></script>
 99 <script src="/js/bootstrap.min.js"></script>
100 <script src="/js/jquery.backstretch.min.js"></script>
101 <script src="/js/scripts.js"></script>
102 
103 <!--[if lt IE 10]>
104 <script src="/js/placeholder.js"></script>
105 <![endif]-->
106 
107 </body>
108 </html>

启动预览

到此为止使用Intellij创建Spring boot+mybatis的简单的项目就完成了

表结构:

 

转载于:https://www.cnblogs.com/dream-to-pku/p/7381178.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值