Springboot+Ajax+Mybatis+Mysql实现异步登录
欢迎访问我的个人博客:http://www.xhcoder.com/
本人大学生,搞了三年的PHP,感觉PHP的生态还是不行,但是PHP仍然是全世界最好的语言!!!上手简单,能快速搭建起一个项目。由于快要找工作了想花一年的时间来搞搞Java,搞了一段时间后发现Java整套是真是完善,可扩展性很强,Java牛逼不是没有道理的。
搭建Springboot项目
springboot是建立在的spring生态的基础上的,以前看spring的时候,有两大概念是纠结了很久的,IOC(控制反转)以及AOP(面向切面的编程)。其实控制反转就是依赖注入,spring提供了一个IOC容器来初始化对象,解决对象间依赖管理和对象的使用,如@Bean、@Autowired等可以实现依赖注入,AOP目前理解是在一些日志框架场景中用到。
平时我们常见的web项目开发,使用的mvc框架、maven管理在springboot依然使用到,springboot最明显的好处是简化了新建一个项目时的各种配置过程,就连tomcat都不用配置了。可以看到我新建一个maven项目大目录结构是这样的
Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
application.yml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
thymeleaf:
cache: false
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>用户登录</title>
<!-- CSS -->
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/supersized.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="page-container">
<h1>用户登录</h1>
<form>
<input type="text" id="username" name="username" value="" placeholder="用户名">
<input type="password" id="password" name="password" value="" placeholder="密码">
<button type="button" onclick="login()">提交</button>
</form><br />
</div>
<!-- Javascript -->
<script src="assets/js/jquery-1.8.2.min.js"></script>
<script src="assets/js/supersized.3.2.7.min.js"></script>
<script src="assets/js/supersized-init.js"></script>
<script src="assets/js/scripts.js"></script>
<!--<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>-->
<script>
function login() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
$.ajax({
type: "POST",
url: "/login_ht",
data: {
username: username,
password: password
},
dataType: "json",
success: function(data){
var msg = data.msg;
alert(msg);
}
})
}
</script>
</body>
</html>
实体类(entity里的Users类)
package com.example.demo.entity;
public class Users {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
定义基本的几个属性后,可以通过键盘上的“alt+insert”键,来进行自动添加该类自带的get和set方法,以及toString方法
mapper(mapper里的UserMapper类):
package com.example.demo.mapper;
import com.example.demo.entity.Users;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper {
@Select("select * from user where id=#{id}")
public Users getUserById(Integer id);
@Select("select username from user where username=#{username} and password=#{password}")
public String login(@Param("username") String username,@Param("password") String password);
@Delete("delete from user where id=#{id}")
public int deleteUserById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into user(username,password) values(#{username},#{password})")
public int insertUser(Users users);
@Update("update user set password=#{password} where id=#{id}")
public int updateUser(Users users);
}
这里我使用的是mybatis的注解的形式实现增删改查的,mybatis还提供了一个xml配置的方式,但是我觉得小demo还是使用注解的方式比较简单。当然这里的登录功能只需要用到查询。
注意一定要加上@Mapper注解,不然容器扫描不到。
UserService:
书写service,业务层,控制业务,主要负责业务逻辑模块的逻辑应用设计
package com.example.demo.service;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public String login(String username,String password){
return userMapper.login(username,password);
}
}
LoginController:
controller控制层,负责具体的业务模块流程的控制,即页面访问控制,调用service层里面的接口控制具体的业务流程
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.util.HashMap;
import java.util.Map;
@Controller
public class LoginController {
@Autowired
UserService userService;
@RequestMapping("/login")
public String login(){
return "login";
}
@ResponseBody
@RequestMapping(value = "/login_ht", method = {RequestMethod.POST, RequestMethod.GET})
public Map<String,Object> login(HttpServletRequest request, HttpSession session){
Map<String,Object> map = new HashMap<String,Object>();
String username = request.getParameter("username");
String password = request.getParameter("password");
String name = userService.login(username,password);
System.out.println(username+password);
System.out.println(name);
session.setAttribute("name", name);
if (name == null) {
map.put("msg","用户名或密码错误");
}
return map;
}
@RequestMapping("/success")
public String success(){
return "success";
}
}
@RequestMapping(value = “/login_ht”, method ={RequestMethod.POST,RequestMethod.GET})
HttpServletRequest request
该value的值/login_ht要与ajax中url值一样,
注意这里一定要加上@ResponseBody注解!!这样才能将数据以Json格式返回到前台!
欢迎访问我的个人博客:http://www.xhcoder.com/