1.SSM简介
-SSM:Spring+SpringMVC+MyBatis,一般都是结合者Maven构建SpringBoot结合使用
-Spring:主要是用于Java实例的统一管理
-SpringMVC:主要用于前后端的调用和业务逻辑的处理
-MyBatis:数据库请求框架,通过Java类和数据库表形成映射,进而操作数据库
2.基于SpringBoot的SSM
-创建项目后,记得把编码格式改为UTF-8
-pom.xml基本依赖的添加
$ 整合热部署devtools
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
$ 添加JSON数据处理jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
3.SpringBoot整合MyBatis
====MySQL的依赖和配置========
-pom.xml文件MySql的依赖添加
<!--连接数据库连接驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
-把application.properties改为application.yml并做以下配置
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/你的数据库名字?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 你的数据库密码
====MyBatis的依赖和配置========
-pom.xml文件MyBatis的依赖添加
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
-application.ymlMyBatis的配置
mybatis:
type-aliases-package: com.youhui
config-locations: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
-在resources目录下新建mybatis文件,在其目录下新建mybatis-config.xml文件,并复制以下内容到其中:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--这个文件的作用是:数据库中的字段名在映射到 Java中时,变为驼峰式-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
-在mybatis文件目录下新建mapper文件,然后在其目录下写.xml文件:用来写SQL代码。
注:mapper文件下的每个.xml文件都对应一个Dao接口下的方法。eg:studentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://10.20.91.130/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.youhui.ssmdemo.ssm.s01.S01MapperDao">
<select id="getCurDate" resultType="java.lang.String">
SELECT CURDATE() FROM DUAL
</select>
</mapper>
-跑通数据库
package com.youhui.ssmdemo.ssm.s02;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* User:youHui
*/
@Mapper
public interface StudentDao {
public List<Student> getStudent();
}
package com.youhui.ssmdemo.ssm.s02;
import java.math.BigDecimal;
import java.util.Date;
/**
* User:youHui
*/
public class Student {
private Integer id;
private String realName;
private String username;
private BigDecimal money;
private String password;
private Integer gender;
private String header;
private String mobile;
private Date createAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
}
package com.youhui.ssmdemo.ssm.s02;
import com.alibaba.fastjson.JSONObject;
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.ResponseBody;
import java.util.List;
/**
* User:youHui
*/
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping("/index")
@ResponseBody
public String getStudents(){
List<Student> studentsList = studentService.getStudents();
JSONObject jsonObject = new JSONObject();
jsonObject.put("studentsList",studentsList);
return jsonObject.toJSONString();
}
}
package com.youhui.ssmdemo.ssm.s02;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* User:youHui
*/
@Service
public class StudentService {
@Autowired
StudentDao studentDao;
public List<Student> getStudents(){
return studentDao.getStudent();
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://10.20.91.130/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.youhui.ssmdemo.ssm.s02.StudentDao">
<select id="getStudent" resultType="com.youhui.ssmdemo.ssm.s02.Student">
SELECT * FROM student
</select>
</mapper>
4.SpringBoot整合FreeMarker
-在pom.xml文件中添加FreeMarker依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
-在application.yml文件配置FreeMarker
# FreeMarker
freemarker:
cache: false
checkTemplateLocation: true
contentType: text/html
suffix: .html
templateEncoding: UTF-8
templateLoaderPath: classpath:templates
5.MyBatis:resultMap简介
-resultMap的作用是能更好的将数据库中的字段映射到Java类。
-比如:有时候数据库中的字段用下划线,在FreeMarker取值时导致取不到,这时候resultMap就是最佳选择。
-举例:
<resultMap id="BeanResultMap" type="com.youhui.ssmdemo.ssm.s02.Student" >
<result column="id" property="id" jdbcType="INTEGER"/>
<result column="real_name" property="realName" jdbcType="VARCHAR" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="money" property="money" jdbcType="DECIMAL" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="gender" property="gender" jdbcType="INTEGER" />
<result column="header" property="header" jdbcType="VARCHAR" />
<result column="mobile" property="mobile" jdbcType="VARCHAR" />
<result column="createAt" property="createAt" jdbcType="TIMESTAMP" />
</resultMap>
<select id="getStudent" resultMap="BeanResultMap">
SELECT * FROM student
</select>
6.MyBatis的select和where语法
-select语法和sal语法结合使用
<sql id="ALL_Columns">
id,username,real_name,username,money,password,gender,header
</sql>
<select id="queryList" resultMap="BeanResultMap">
SELECT
<include refid=""All_Colums" />
FROM table_name
</select>
-where语法
<select id="queryStudent" resultMap="BeanResultMap">
SELECT * FROM student
<where>
<if test="id != null">
AND id = #{id,jdbcType=INTEGER}
</if>
<if test="username != null">
AND username like CONCAT('%',#{username},'%' )
</if>
<if test="money != null">
<![CDATA[ AND money > #{money} ]]>
</if>
</where>
</select>
7.Mybatis的insert语法
<insert id="createStudent" parameterType="com.youhui.ssmdemo.ssm.s02.Student" flushCache="true" useGeneratedKeys="true" keyProperty="id">
INSERT INTO student
(id, real_name, username, money, password, gender, header, mobile, createAt)
VALUES
(#{id},#{realName},#{username},#{money},#{password},#{gender},#{header},#{mobile},#{createAt})
</insert>
8.Mybatis的update语法
<update id="updateStudent" parameterType="com.youhui.ssmdemo.ssm.s02.Student" flushCache="true">
UPDATE student
<trim prefix="SET" suffixOverrides="," >
<if test="realName != null ">
real_name = #{realName, jdbcType=VARCHAR},
</if>
<if test="username != null ">
username = #{username, jdbcType=VARCHAR},
</if>
</trim>
WHERE id = #{id, jdbcType = INTEGER}
</update>
9.MyBatis的delete语法
<delete id="deleteStudent" parameterType="java.lang.Integer" >
DELETE
FROM student
WHERE id = #{id, jdbcType=INTEGER}
</delete>
10.学生分页列表的实现
-使用Pagination.java类结合MyBatis实现分页
package com.youhui.ssmdemo.ssm.page;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* User: youhui
*/
public class Pagination<E> {
private List<E> items;//分页记录
private int pageTotalCount = 0;//总页数
private int itemsTotalCount = 0;//总记录数
private List<Integer> showNums = new ArrayList<Integer>();//显示的页码
private int showPage = 10;//显示10个页码
private int pageSize = 10;//每页10条数据
private int pageNum = 1;//从第一页显示
private boolean firstPage;//是否是第一页
private boolean lastPage;//是否是最后一页
private int startIndex;//分页开始
private String sortField="createAt";//排序字段
private String sortDirection = "DESC";//排序方向
public Pagination() {}
public Pagination(int pageNum, int pageSize , int itemsTotalCount , List<E> items) {
this.setItemsTotalCount(itemsTotalCount);
this.setPageNum(pageNum);
this.setPageSize(pageSize);
this.setItems(items);
this.initShowNum();
}
public int getShowPage() {
return showPage;
}
public void setShowPage(int showPage) {
this.showPage = showPage;
}
public void setItemsTotalCount(int itemsTotalCount) {
this.itemsTotalCount = itemsTotalCount;
if(itemsTotalCount % this.pageSize == 0){
this.pageTotalCount = itemsTotalCount/this.pageSize;
}else{
this.pageTotalCount = itemsTotalCount/this.pageSize + 1;
}
if(this.pageNum > this.pageTotalCount){
this.pageNum = 1;
}
if(this.itemsTotalCount <= this.pageSize){
this.firstPage = true;
this.lastPage = true;
}
initShowNum();
}
private void initShowNum(){
int startIndex;
int endIndex;
if(pageNum - showPage/2 > 1){
startIndex = pageNum-showPage/2;
endIndex = pageNum + showPage/2 - 1;
if(endIndex > pageTotalCount){
endIndex = pageTotalCount;
startIndex = endIndex - showPage + 1;
}
if(startIndex <= 0) {
startIndex = 1;
}
}else{
startIndex = 1;
endIndex = Math.min(pageTotalCount, showPage);
}
for(int i = startIndex; i <= endIndex ; i++){
this.showNums.add(i);
}
}
public void setItems(Collection<E> items) {
if (items == null) items = Collections.emptyList();
this.items = new ArrayList<E>(items);
this.lastPage = this.pageNum == this.pageTotalCount;
this.firstPage = this.pageNum == 1;
}
public List<Integer> getShowNums() {
return showNums;
}
public int getPageTotalCount(){
return this.pageTotalCount;
}
public int getFirstPageNum() {
return 1;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
if (pageNum < 1) pageNum = 1;
this.pageNum = pageNum;
}
public int getStartIndex() {
this.startIndex = (this.pageNum - 1) * this.pageSize;
if(this.startIndex <= 0){
this.startIndex = 0;
}
return this.startIndex;
}
public List<E> getItems() {
return items;
}
public boolean isFirstPage() {
firstPage = (getPageNum() <= getFirstPageNum());
return firstPage;
}
public boolean isLastPage() {
lastPage = (getPageNum() >= pageTotalCount);
return lastPage;
}
public int getPrePageNum() {
return isFirstPage() ? getFirstPageNum() : getPageNum() - 1;
}
public int getNextPageNum() {
return isLastPage() ? getPageNum() : getPageNum() + 1;
}
public boolean isEmpty() {
return items.isEmpty();
}
public int getItemsTotalCount() {
return itemsTotalCount;
}
public int getLastPageNum() {
return itemsTotalCount;
}
/**
* 按照sortField升序
* @param sortField:指java bean中的属性
*/
public void ascSortField(String sortField) {
this.sortField = sortField;
this.sortDirection = " ASC ";
}
/**
* 按照sortField降序
* @param sortField :指java bean中的属性
*/
public void descSortField(String sortField) {
this.sortField = sortField;
this.sortDirection = " DESC ";
}
public String getSortDirection() {
return sortDirection;
}
public void setSortDirection(String sortDirection) {
this.sortDirection = sortDirection;
}
public String getSortField() {
return sortField;
}
public void setSortField(String sortField) {
this.sortField = sortField;
}
@Override
public String toString() {
return "Page[" + this.getPageNum() + "]:" + items.toString();
}
}
<!--获取数据总条数 -->
<select id="getStudentCount" parameterType="com.youhui.ssmdemo.ssm.s02.Student" resultType="java.lang.Integer">
SELECT count(id) FROM student
<where>
<if test="id != null">
AND id = #{id,jdbcType=INTEGER}
</if>
<if test="username != null">
AND username like CONCAT('%',#{username},'%' )
</if>
<if test="money != null">
<![CDATA[ AND money > #{money} ]]>
</if>
</where>
</select>
<!--获取分页数据 -->
<select id="pageStudentCount" resultMap="BeanResultMap">
SELECT
id, real_name, username, money, password, gender, header, mobile, createAt
FROM student
<where>
<if test="param1.id != null">
AND id = #{param1.id,jdbcType=INTEGER}
</if>
<if test="param1.username != null">
AND username like CONCAT('%',#{param1.username},'%' )
</if>
<if test="param1.money != null">
<![CDATA[ AND money > #{param1.money} ]]>
</if>
</where>
<if test="param2.sortField != null and param2.sortDirection != null">
ORDER BY ${param2.sortField} ${param2.sortDirection}
</if>
LIMIT #{param2.startIndex,jdbcType=INTEGER}, #{param2.pageSize,jdbcType=INTEGER}
</select>
-MyBatis批量添加数据
<insert id="batchCreate" parameterType="java.util.List">
INSERT INTO student
(id, real_name, username, money, password, gender, header, mobile, createAt)
VALUES
<foreach collection="list" item="item" index="index" separator="," >
(#{item.id},#{item.realName},#{item.username},#{item.money},#{item.password},#{item.gender},#{item.header},#{item.mobile},#{item.createAt})
</foreach>
</insert>
11.Ajax请求数据
-ajax请求
$.ajax({
url:'/ajax/json',
method:'GET',
success:function(data){
alert(data)
}
})
-get请求
$.get('/ajax/json', function (data,status) {
alert(data)
})
-、post请求
$.post('/ajax/json', function (data,status) {
alert(data)
})
12.jQueryForm异步提交Form表单
-调用ajaxSubmit()
$('#studentForm').ajaxSubmit({
datatype : 'json',
success : function(resp) {
let respJson = $.parseJSON(resp);
alert(respJson.errcode)
},
error : function(xhr) {
}
});