前言:利用springBoot+Mybatis创建web,实现简单的增加,删除和查询功能。
1、在IDEA中创建项目
图1 新建项目
图2 选择 Spring Initializr
图3 设置项目结构名称
图4 选择相关依赖包(也可在pom.xml中设置)
图5 设置项目名称
经过上面5个步骤初步创建了一个springboot项目。接下来为配置Mybatis。
2、在项目中创建目录
图6 在 src\main\resources中创建目录static,然后在static中创建目录js和templates.
static中为项目的静态文件,js中存放相关的javasript文件,templates为html静态文件。
图7 业务处理的各层目录结构
config目录中为配置数据库连接的java文件;controller层捕获客户端请求;servier层提供业务处理逻辑;dao层为操作数据库的SQL代码(mapper)和相关的数据库表实体(entity)。
3,代码和配置
(1)数据库连接配置
图8
注意:需要在pom.xml中添加如下:
依赖包
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
DataBaseConfig.java
package com.example.mydemo.config;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.sql.Connection;
@Configuration
//扫描实体类的包
@ComponentScan(basePackages = "com.example.mydemo.dao.entity")
//扫描仓库类的包,在mybatis里面被称为Mapper,一般用来完成数据库的操作
@MapperScan(basePackages = "com.example.mydemo.dao.")
public class DataBaseConfig {
@Bean
public DataSource getDataSource() {
Connection connection = null;
BasicDataSource dataSource = new BasicDataSource();
// 数据库连接配置
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//设置useSSL=false
//本地数据库
dataSource.setUrl("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8");
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setTestWhileIdle(true);
dataSource.setTimeBetweenEvictionRunsMillis(60000 * 30);
dataSource.setValidationQuery("select 1");
return dataSource;
}
//事务管理
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(getDataSource());
}
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(getDataSource());
return sqlSessionFactory.getObject();
}
}
创建数据库:test
表名称为:user
列名称 类型
id int
loginName vchar(20)
password vchar(20)
(2)创建user表对应的实体类
图9 user表的实体类
userEntity.java (属性名与user表字段对应)
package com.example.mydemo.dao.entity;
public class userEntity {
private int id;
private String loginName;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
(3)创建login.html,包含两个文本输入框和三个按钮
图10 login.htm页面
(4)创建javaScript文件user.js,响应页面的点击事件
图11 创建文件
图12 编辑文件
user.js
//文件执行入口
$(function () {
//捕获html页面中id为find的按钮的点击事件
$("#find").click(function () {
getUser()//查询
});
//捕获html页面中di为add的按钮的点击事件
$("#add").click(function () {
addUser()//添加
});
});
//查询用户信息
function getUser() {
//获取html网页中名称为loginName的标签的值
var loginName = $("#loginName").val();
//向后台发起请求
$.ajax({
type: "POST",
url: '/getUser',
data: {
loginName: loginName,
},
success: function (data) {
alert(data)
},
error: function (data) {
alert(data)
}
}
);
}
//添加user
function addUser() {
//获取html网页中名称为loginName和password的标签的值
var loginName = $("#loginName").val();
var password = $("#password").val();
//向后台发起请求
$.ajax({
type: "POST",
url: '/addUser',
data: {
loginName: loginName,
password: password
},
success: function (data) {
alert(data)
},
error: function (data) {
alert(data)
}
}
);
}
(5)在login.html中引入user.js文件(jquery-3.2.1.js请自行在网上下载,并放到相应目录中)
图12 引入js文件
(6)在controller中捕获前端发起的HTTP请求
①首先在pom.xml中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
②提取参数并调用service处理请求
图12 userContrller 捕获请求
package com.example.mydemo.controller;
import com.example.mydemo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
public class userController {
@Autowired
private userService userService;
//捕获请求(查询用户信息)
@RequestMapping(value = "/getUser", method = RequestMethod.POST)
public String getUser(HttpServletRequest request) {
String loginName = request.getParameter("loginName");
String result = userService.getUser(loginName);
return result;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String AddUser(HttpServletRequest request) {
String loginName = request.getParameter("loginName");
String password = request.getParameter("password");
String result = userService.addUser(loginName, password);
return result;
}
}
(7) service层代码
图13 业务处理
userService.java
package com.example.mydemo.service;
import com.example.mydemo.dao.entity.userEntity;
import com.example.mydemo.dao.mapper.userMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class userService {
@Autowired
private userMapper usermapper;
//处理获取用户你信息的操作
public String getUser(String loginName) {
userEntity entity = usermapper.getAllUser(loginName); //根据用户名查询
if (entity == null) {
return "用户不存在!";
} else {
String name = entity.getLoginName();
return name;
}
}
//处理添加操作
public String addUser(String loginName, String password) {
boolean b = usermapper.addUser(loginName, password);//往数据库中添加用户
if (b) {
return "添加成功!";
} else {
return "添加失败!";
}
}
}
(8)mapper中操作数据库的SQL语句
图14
userMapper.java
package com.example.mydemo.dao.mapper;
import com.example.mydemo.dao.entity.userEntity;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface userMapper {
//根据登录名查询用户
@Select("select * from user where loginName=#{name}")
userEntity getAllUser(String name);
@Insert("insert into user(loginName,password) value(#{loginName},#{password})")
boolean addUser(@Param("loginName") String loginName, @Param("password")String password );
@Delete("delete from user where loginName=#{name}")
boolean removeUser(String name);
}
(9)pom.xml
<?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.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mydemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mydemo</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-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</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>
</plugin>
</plugins>
</build>
</project>
4,运行程序
①运行程序
②浏览器中输入http://localhost:8080/templates/login.html
图15 web页面
到此大功告成!!!!!
注:所使用软件
idea 2018
mysql 5.7x
JDK 1.8
demo
链接:https://pan.baidu.com/s/1q53V42QFrUd4rCEKJNXgpg
提取码:1rpy