环境搭建配置
首先去建一个项目选择Spring initializr,选择jdk(sdk),选择Defult
在Artifact中进行修改(注意不能为大写字母),创建的时静态Java包中名字
选中Core,Web,SQL中的总共四项
给自己的项目起一个名字点击完成
项目创建完成之后,对环境进行搭建打开application.properties
在application.properties文件中输入:
(注意数据源的连接在spring.datasource.url=jdbc:mysql://localhost:3306/test 这个test是我的数据库名称,大家要写自己的数据库的名称)
#数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.initialSize=20
spring.datasource.minIdle=50
spring.datasource.maxActive=500
#上下文配置
server.port=8888
server.servlet.context-path=/kude
#配置jpa
#帮我们自动生成表结构
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
#redis的配置
# Redis_config
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接超时时间(毫秒)
spring.redis.timeout=3600
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# jedis超时
spring.redis.jedis.shutdown-timeout=100
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
#定义分页每页的记录数
mypager.perPagerSize=10
接下来进行引入jar包(idea在maven中进行下载引入),只需在pom.xml中书写以下代码
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<!--mysql驱动-->
<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>
<!-- druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--添加阿里巴巴的json解析类库fastjson-->
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<!--springboot操作redis的组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--添加糊涂工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.6</version>
</dependency>
<!--javamail依赖用来发送电子邮件-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
</dependencies>
分包管理
增删改查和分页操作
首先去进行分包:controller对用户信息进行控制,dao层对数据库的操作,entity实体类(类名与属性与数据库中表一一对应),service服务层调用dao层,与控制层交接。
在entity去建一个实体类:
package com.example.stu.entity;
import javax.persistence.*;
@Entity//标识实体类
@Table(name ="Student")//建立的实体类会有多个,进行区别
public class Student {
@Id//标识id
@GeneratedValue(strategy = GenerationType.IDENTITY)//设置id字段进行自增操作
private Integer id;
@Column(length = 22)//设置字段长度
private String stuname;
@Column(length = 11)
private String password;
@Column(length = 2)
private String gender;
public Student() {
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuname='" + stuname + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Dao层:
package com.example.stu.dao;
import com.example.stu.entity.Student;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
*定义dao层接口 继承JapRepository(含有我们需要的数据库中的增删改查)
* 当我们进行复杂操作的时候需要自己书写SqL语句
*/
public interface StudentDao extends JpaRepository<Student,Integer> {
Student findStudentById(Integer id);//根据id去查询一条学生信息
/**
* 根据名字去查询学生信息
* 复杂查询自己书写Sql语句
* @Query(name = "方法名",nativeQuery = true,value =
* "Sql语句")
* @Param("参数名") 进行标识参数(在进行复杂查询的时候,不止一个参数)
* @param stuname
* @return
*/
@Query(name = "findStuByName",nativeQuery = true,value =
"select * from student where stuname=:stuname")
List<Student> findStuByName(@Param("stuname") String stuname);
/**
* 根据名字与密码进行登录
* @param stuname
* @param password
* @return
*/
@Query(name="login",nativeQuery = true,value =
"select * from student where stuname=:stuname and password=:password")
Student login(@Param("stuname") String stuname, @Param("password") String password);
/**
* 根据id和密码进行登录
* @param id
* @param password
* @return
*/
@Query(name = "loginbyId", nativeQuery = true, value =
"select * from student where id=:id and password=:password")
Student loginbyId(@Param("id") Integer id, @Param("password") String password);
}
Service层:
定义Service接口,去实现接口
package com.example.stu.service;
import com.example.stu.entity.Student;
import org.springframework.data.domain.Page;
import java.util.List;
public interface StudentService {
List<Student> findAll();//查询学生所有信息
Student findStudentById(Integer id);//根据id查询一条学生信息
Student save(Student student);//插入一条学生信息
Student updateById(Student student);//根据id来进行修改一条学生信息
List<Student> findStudentByStuname(String stuname);//根据名字查询学生信息
Student login(String stuname,String password);//根据名字与密码进行登录
void deletById(Integer id);//根据id删除学生信息
Page<Student> findAll(int page, int pageSize);//分页查询
Student loginById(Integer id,String password);//根据id和密码去进行登录
}
实现Service接口
在Service包中建立一个impl对service接口的实现全写在了其中(注意我的修改操作,save()也能当做修改,但它进行修改的前提是,你在给它进行传入修改对象的属性时,需要传入全部,没有传入的,Save()会默认会空,就是说,一个对象有名字,年龄,性别,你使用save()只进行修改其中一个两个,另当做null去保存到数据库中,你数据库中的这个对象没有进行修改的会为空,所以需要判断操作)
package com.example.stu.service.impl;
import com.example.stu.dao.StudentDao;
import com.example.stu.entity.Student;
import com.example.stu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 对接口studentservice的实现
*/
//标识service
@Service
public class StudentServiceImpl implements StudentService {
//自动注入
@Autowired
private StudentDao studentDao;//每个方法都需要使用,设为成员变量
/**
* 查询所有学生信息
* @return
*/
@Override
public List<Student> findAll() {
return studentDao.findAll();
}
/**
* 根据id查询一条学生信息
* @param id
* @return
*/
@Override
public Student findStudentById(Integer id) {
return studentDao.findStudentById(id);
}
/**
* 插入一条学生信息
* @param student
* @return
*/
@Override
public Student save(Student student) {
return studentDao.save(student);
}
/**
* 根据id去修改一条学生信息
* @param student
* @return
*/
@Override
public Student updateById(Student student) {
Student stu=studentDao.findStudentById(student.getId());
if(student.getStuname()==null){
stu.setStuname(stu.getStuname());
}else {
stu.setStuname(student.getStuname());
}
if(student.getPassword()==null){
stu.setPassword(stu.getPassword());
}else{
stu.setPassword(student.getPassword());
}
if(student.getGender()==null){
stu.setGender(stu.getGender());
}else {
stu.setGender(student.getGender());
}
return studentDao.save(stu);
}
/**
* 根据名字去查找学生信息
* @param stuname
* @return
*/
@Override
public List<Student> findStudentByStuname(String stuname) {
return studentDao.findStuByName(stuname);
}
/**
* 根据学生名称密码进行登录
* @param stuname
* @param password
* @return
*/
@Override
public Student login(String stuname, String password) {
return studentDao.login(stuname,password);
}
/**
* 根据id和密码去登录
* @param id
* @return
*/
@Override
public Student loginById(Integer id,String password) {
return studentDao.loginbyId(id,password);
}
/**
* 根据id去删除学生信息
* @param id
*/
@Override
public void deletById(Integer id) {
studentDao.deleteById(id);
}
/**
* 分页查询所有数据
* @param page 当前页
* @param pageSize 每页记录数
* @return
*/
@Override
public Page<Student> findAll(int page, int pageSize) {
Pageable pageable= PageRequest.of(page,pageSize);
return studentDao.findAll(pageable);
}
}
Controller控制层:
package com.example.stu.controller;
import com.example.stu.entity.Student;
import com.example.stu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController//相当于restbody+controller标识这个类为控制器,同时返回的数据为json数据
@RequestMapping("/student")//控制器的名字
public class StudentController {
@Autowired
private StudentService studentService;
/**
* 查询学生所有信息
* @return
*/
@GetMapping("/findAll")//使用get请求,postmapping是post的请求
public List<Student> findAll(){
return studentService.findAll();
}
/**
* 根据Id查询一条学生信息
* @param id
* @return
*/
@GetMapping("/findOneById")
public Student findOneById(Integer id){
return studentService.findStudentById(id);
}
/**
* 新增一条学生信息
* @param student
* @return
*/
@PostMapping("/rgs")
public Student rgs(Student student){
return studentService.save(student);
}
/**
* 根据学生id去修改学生信息
* @param student
* @return
*/
@GetMapping("/update/{student}")
public Student update(@PathVariable Student student){
return studentService.updateById(student);
}
/**
* 根据学生名称查询学生信息
* @param stuname
* @return
*/
@GetMapping("/findstubystuname")
public List<Student> findStuByStuname(String stuname){
return studentService.findStudentByStuname(stuname);
}
/**
* 根据id去删除学生信息
* @param id
*/
@GetMapping("/delete/{id}")//这种格式,在进行地址栏输入为/delete/id值,不需要/delete?id=id值
public void delete(@PathVariable Integer id){
studentService.deletById( id);
}
/**
* 根据学生名称和密码进行登录
* @param stuname
* @param password
* @return
*/
@GetMapping("/login")
public Student login(String stuname,String password){
return studentService.login(stuname,password);
}
/**
* 根据学生id和密码进行登录
* @param id
* @param password
* @return
*/
@GetMapping("/loginbyid")
public Student loginById(Integer id,String password){
return studentService.loginById(id,password);
}
/**
* 分页查找显示所有
* @param page
* @param response
* @return
*/
@GetMapping("/pagefindall")
public Page<Student> pagefindAll(Integer page, HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin","*");//解决跨域请求
if(page==null || page<=0){
page = 0;
}else{
page -= 1;
}
return studentService.findAll(page,5);
}
}
前端页面
展示所有信息的页面
你需要下载JQuery,layui。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="layui/css/layui.css" media="all">
<!-- <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script> -->
<script src="layui/lay/modules/jquery.js" type="text/javascript" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<div style="margin-bottom: 5px;">
<!-- 示例-970 -->
<ins class="adsbygoogle" style="display:inline-block;width:970px;height:90px" data-ad-client="ca-pub-6111334333458862" data-ad-slot="3820120620"></ins>
</div>
<div class="layui-btn-group demoTable">
<button class="layui-btn" data-type="getCheckData">获取选中行数据</button>
<button class="layui-btn" data-type="getCheckLength">获取选中数目</button>
<button class="layui-btn" data-type="isAll">验证是否全选</button>
<button class="layui-btn" data-type="addStu">添加一条新的学生信息</button>
</div>
<table class="layui-table" lay-data="{url:'http://localhost:8888/kude/student/pagefindall', page:true, id:'idTest'}" lay-filter="demo">
<thead>
<tr>
<th lay-data="{type:'checkbox', fixed: 'left'}"></th>
<th lay-data="{field:'id', sort: true, fixed: true}">ID</th>
<th lay-data="{field:'stuname'}">用户名</th>
<th lay-data="{field:'password'}">密码</th>
<th lay-data="{field:'gender',sort: true}">性别</th>
<th lay-data="{fixed: 'right', width:178, align:'center', toolbar: '#barDemo'}"></th>
</tr>
</thead>
</table>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script src="layui/layui.js" charset="utf-8"></script>
<script src="layui/lay/modules/jquery.js" type="text/javascript" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.use('table', function(){
var table = layui.table;
//监听表格复选框选择
table.on('checkbox(demo)', function(obj){
console.log(obj)
});
//监听工具条
table.on('tool(demo)', function(obj){
var data = obj.data;
if(obj.event === 'detail'){
layer.msg('ID:'+ data.id +',用户名:'+data.stuname+',密码:'+data.password+',性别:'+data.gender);
} else if(obj.event === 'del'){
layer.confirm('真的要删除用户:'+data.stuname+'吗?', function(index){
$.get("http://localhost:8888/kude/student/delete/"+data.id)
obj.del();
layer.close(index);
});
} else if(obj.event === 'edit'){
layer.open({
type:2,
skin:'layui-layer-rim',//边框
area:['500px','400px'],//宽高
fixed:false,
content:'update.html',
success:function(layero,index){
var body=layer.getChildFrame('body',index);
body.find("#sid").val(data.id);
body.find("#sname").val(data.stuname);
body.find("#spassword").val(data.password);
body.find("#sex").val(data.gender);
if(data.gender=="男"){
body.find("#boy").attr('checked','checked');
}else{
body.find("#girl").attr('checked','checked');
}
},
});
}
});
var $ = layui.$, active = {
getCheckData: function(){ //获取选中数据
var checkStatus = table.checkStatus('idTest')
,data = checkStatus.data;
layer.alert(JSON.stringify(data));
}
,getCheckLength: function(){ //获取选中数目
var checkStatus = table.checkStatus('idTest')
,data = checkStatus.data;
layer.msg('选中了:'+ data.length + ' 个');
}
,isAll: function(){ //验证是否全选
var checkStatus = table.checkStatus('idTest');
layer.msg(checkStatus.isAll ? '全选': '未全选')
},
addStu:function(){
layer.open({
type:2,
skin:'layui-layer-rim',//边框
area:['500px','400px'],//宽高
fixed:false,
content:'add.html',
})
},
};
$('.demoTable .layui-btn').on('click', function(){
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
});
</script>
</body>
</html>
添加学生信息的页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="layui/css/layui.css" media="all">
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
<legend>添加学生信息</legend>
</fieldset>
<form class="layui-form layui-form-pane" action="http://localhost:8888/kude/student/rgs" method="post">
<input type="hidden" name="id"/>
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-inline">
<input type="text" name="stuname" id="sname" lay-verify="required" placeholder="请输入用户名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item" pane="">
<label class="layui-form-label">性别</label>
<div class="layui-input-block">
<input type="radio" name="gender" lay-verify="required" value="男" title="男" checked="checked">
<input type="radio" name="gender" lay-verify="required" value="女" title="女" >
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn" lay-submit="" lay-filter="demo2">确认添加</button>
</div>
</form>
<script src="layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.use(['form', 'layedit', 'laydate'], function(){
var form = layui.form
,layer = layui.layer
,layedit = layui.layedit
,laydate = layui.laydate;
//监听提交
form.on('submit(demo1)', function(data){
layer.alert(JSON.stringify(data.field), {
title: '最终的提交信息'
})
return false;
});
});
</script>
</body>
</html>
修改学生信息页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="layui/css/layui.css" media="all">
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
<legend>学生信息的修改</legend>
</fieldset>
<form class="layui-form layui-form-pane" action="http://localhost:8888/kude/student/update" method="post">
<input type="hidden" name="id" id="sid"/>
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-inline">
<input type="text" name="stuname" id="sname" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="text" name="password" id="spassword" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">性别</label>
<div class="layui-input-inline">
<input type="text" name="gender" id="sex" lay-verify="required" placeholder="请输入性别" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn" lay-submit="" lay-filter="demo2">确认修改</button>
</div>
</form>
<script src="layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.use(['form', 'layedit', 'laydate'], function(){
var form = layui.form
,layer = layui.layer
,layedit = layui.layedit
,laydate = layui.laydate;
//监听提交
form.on('submit(demo1)', function(data){
layer.alert(JSON.stringify(data.field), {
title: '最终的提交信息'
})
return false;
});
});
</script>
</body>
</html>
学生登录页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="layui/css/layui.css" media="all">
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
<legend>学生登录</legend>
</fieldset>
<form class="layui-form layui-form-pane" action="http://localhost:8888/kude/student/loginbyid/" >
<div class="layui-form-item">
<label class="layui-form-label">账号</label>
<div class="layui-input-inline">
<input type="text" name="id" lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-inline">
<input type="text" name="password" lay-verify="required" placeholder="请输入密码" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn" lay-submit="" lay-filter="demo2">确认登录</button>
</div>
</form>
<button class="layui-btn" onclick=javascrtpt:jump()>没有账号进行注册</button>
<script src="layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
function jump(){
window.location.href="add.html";
}
</script>
</body>
</html>
(简单的案例,还有些页面的操作完成之后的跳转没有进行完善,底层的功能也比较简陋,仅供参考)