java入门-springboot整合mybatis+layui

源码地址:https://codechina.csdn.net/wwwzhouzy/springboot-ssm

先看看项目启动,访问页面的效果图:

java入门-springboot整合mybatis+layui_第1张图片

需要注意的地方 :

1、引入layui相关资源文件时注意路径,尤其是引用Thymeleaf标签时

java入门-springboot整合mybatis+layui_第2张图片

静态资源默认从static目录下查找 

2、注意json传送数据的编码问题,不然会有乱码

继承WebMvcConfigurationSupport类,重写方法:

    @Bean
    public HttpMessageConverter responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }
	@Override
    public void configureMessageConverters(List> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }
    @Override
   	protected void extendMessageConverters(List> converters) {
   		for (HttpMessageConverter converter : converters) {
               // 解决controller返回普通文本中文乱码问题
   			if (converter instanceof StringHttpMessageConverter) {
   				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
               }
               // 解决controller返回json对象中文乱码问题
   			if (converter instanceof MappingJackson2HttpMessageConverter) {
   				((MappingJackson2HttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
   			}
   		}
   	}

 3、我用的mysql5.0版本,所以springboot采用了2.0.5

    
		org.springframework.boot
		spring-boot-starter-parent
		2.0.5.RELEASE
	

一、项目架构

java入门-springboot整合mybatis+layui_第3张图片

二、核心代码 

1、pom引包




  4.0.0

  com.zhouzy.ssm
  zhouzySsm
  0.0.1-SNAPSHOT

  zhouzySsm
  
  http://www.example.com

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.5.RELEASE
	
    
	
        UTF-8
        UTF-8
        1.8
        Finchley.SR1
    
	
  
      
		
			org.springframework.boot
			spring-boot-starter-web
		

		
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		
		
		
			org.springframework.boot
			spring-boot-starter-jdbc
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.3.2
		
 
		
			mysql
			mysql-connector-java
			runtime
		
		
		
            com.alibaba
            fastjson
            1.2.30
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
  


	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

2、配置文件

application.yml

server:
  port: 8080
 
spring:
  application:
    mame: ssm
  thymeleaf:
    prefix: classpath:/templates/
    cache: false
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/zhouzy?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
 
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.zhouzy.ssm.model
 
#showSql
logging:
  level:
    com:
      example:
        mapper : debug

3、html文件

userList.html




    
    
    layout 后台大布局 - Layui
    
    





4、mybatis映射文件





    
                
                
                
                
                
                
                
                
    

    
                id,
                name,
                age,
                sex,
                address,
                mobile,
                create_time,
                update_time
    

    
        INSERT INTO t_user_info
        
                        
                        name,
                        
                        
                        age,
                        
                        
                        sex,
                        
                        
                        address,
                        
                        
                        mobile,
                        
                        
                        create_time,
                        
                        
                        update_time
                        
        
        
                        
                        #{name},
                        
                        
                        #{age},
                        
                        
                        #{sex},
                        
                        
                        #{address},
                        
                        
                        #{mobile},
                        
                        
                        #{createTime},
                        
                        
                        #{updateTime}
                        
        
    

    
        DELETE FROM t_user_info
        WHERE id = #{id}
    

    
        UPDATE t_user_info
        
                    name = #{name},
                    age = #{age},
                    sex = #{sex},
                    address = #{address},
                    mobile = #{mobile},
                    create_time = #{createTime},
                    update_time = #{updateTime}
        
        WHERE id = #{id}
    


    

    

    

5、mvc配置类

package com.zhouzy.ssm.config;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
	
	//通过重写配置方法覆盖
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
   registry.addResourceHandler("/mapper/**").addResourceLocations("classpath:/mapper/");//mapper.xml
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/templates/");
        super.addResourceHandlers(registry);
    }
    
    @Bean
    public HttpMessageConverter responseBodyConverter() {
        return new StringHttpMessageConverter(Charset.forName("UTF-8"));
    }
	@Override
    public void configureMessageConverters(List> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }
    @Override
   	protected void extendMessageConverters(List> converters) {
   		for (HttpMessageConverter converter : converters) {
               // 解决controller返回普通文本中文乱码问题
   			if (converter instanceof StringHttpMessageConverter) {
   				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
               }
               // 解决controller返回json对象中文乱码问题
   			if (converter instanceof MappingJackson2HttpMessageConverter) {
   				((MappingJackson2HttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
   			}
   		}
   	}
}

6、启动类

package com.zhouzy.ssm;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@MapperScan("com.zhouzy.ssm.mapper") //扫描的mapper
@SpringBootApplication
public class Webapplication {
	public static void main(String[] args) {
		SpringApplication.run(Webapplication.class, args);
	}
}

7、控制层

package com.zhouzy.ssm.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zhouzy.ssm.model.DataGrid;
import com.zhouzy.ssm.model.PageInfo;
import com.zhouzy.ssm.model.UserInfo;
import com.zhouzy.ssm.service.UserInfoService;

@Controller
@RequestMapping("/user")
public class UserInfoController {
	@Resource
    private UserInfoService userInfoService;

    /**
    * 新增
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    @RequestMapping("/insert")
    public void insert(UserInfo userInfo){
        userInfoService.insert(userInfo);
    }

    /**
    * 刪除
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    @RequestMapping("/delete")
    public void delete(int id){
        userInfoService.delete(id);
    }

    /**
    * 更新
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    @RequestMapping("/update")
    public void update(UserInfo userInfo){
        userInfoService.update(userInfo);
    }

    /**
    * 查询 根据主键 id 查询
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    @RequestMapping("/load")
    public Object load(int id){
        return userInfoService.load(id);
    }

    /**
    * 查询 分页查询
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    @RequestMapping("/list")
    public String pageList() {
        return "user/userList";
    }
    
    
    /**
     * 查询 分页查询
     * @author zhouzhiyao
     * @date 2021/08/03
     **/
     @SuppressWarnings("unchecked")
     @RequestMapping("/listData")
     @ResponseBody
     public String listData(PageInfo page) {
     	int pageNum = page.getPage();
     	int size = page.getLimit();
     	Map map = userInfoService.pageList((pageNum-1)*size, size);
     	List data = (List)map.get("data");
     	int count =  (Integer)map.get("count");
     	DataGrid grid = new DataGrid(data,count,0,null);
        return JSONObject.toJSONString(grid);
     }
}

8、service层

package com.zhouzy.ssm.service;

import java.util.Map;

import com.zhouzy.ssm.model.UserInfo;

/**
 * @description 用户信息表
 * @author zhouzhiyao
 * @date 2021-08-03
 */
public interface UserInfoService {

    /**
    * 新增
    */
    public void insert(UserInfo userInfo);

    /**
    * 删除
    */
    public void delete(int id);

    /**
    * 更新
    */
    public void update(UserInfo userInfo);

    /**
    * 根据主键 id 查询
    */
    public UserInfo load(int id);

    /**
    * 分页查询
    */
    public Map pageList(int offset, int pagesize);

}
package com.zhouzy.ssm.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zhouzy.ssm.mapper.UserInfoMapper;
import com.zhouzy.ssm.model.UserInfo;
import com.zhouzy.ssm.service.UserInfoService;

/**
 * @description 用户信息表
 * @author zhouzhiyao
 * @date 2021-08-03
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

	@Resource
	private UserInfoMapper userInfoMapper;


	public void insert(UserInfo userInfo) {

		userInfoMapper.insert(userInfo);
	}


	 public void delete(int id) {
		userInfoMapper.delete(id);
	}


	public void update(UserInfo userInfo) {
		userInfoMapper.update(userInfo);
	}


	public UserInfo load(int id) {
		return userInfoMapper.load(id);
	}


	public Map pageList(int offset, int pagesize) {

		List pageList = userInfoMapper.pageList(offset, pagesize);
		int totalCount = userInfoMapper.pageListCount();

		// result
		Map result = new HashMap();
		result.put("data", pageList);
		result.put("count", totalCount);

		return result;
	}

}

9、mapper层

package com.zhouzy.ssm.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import com.zhouzy.ssm.model.UserInfo;

/**
 * @description 用户信息表
 * @author zhouzhiyao
 * @date 2021-08-03
 */
@Repository
public interface UserInfoMapper {

    /**
    * 新增
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    int insert(UserInfo userInfo);

    /**
    * 刪除
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    int delete(int id);

    /**
    * 更新
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    int update(UserInfo userInfo);

    /**
    * 查询 根据主键 id 查询
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    UserInfo load(int id);

    /**
    * 查询 分页查询
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    List pageList(@Param("offset")int offset,@Param("pageSize")int pageSize);

    /**
    * 查询 分页查询 count
    * @author zhouzhiyao
    * @date 2021/08/03
    **/
    int pageListCount();

}

10、mdelo对象

实体类

package com.zhouzy.ssm.model;

import java.io.Serializable;
import java.util.Date;

/**
 * @description 用户信息表
 * @author zhouzhiyao
 * @date 2021-08-03
 */

public class UserInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
    * id
    */
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    /**
    * 姓名
    */
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    /**
    * 年龄
    */
    private Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    /**
    * 性别:0:男 1:女
    */
    private Integer sex;

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }
    /**
    * 地址
    */
    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    /**
    * 手机号
    */
    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    /**
    * 创建时间
    */
    private Date createTime;

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    /**
    * 更新时间
    */
    private Date updateTime;

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public UserInfo() {}
}

layui表格对应的对象类

package com.zhouzy.ssm.model;

import java.io.Serializable;
import java.util.List;

public class DataGrid implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private int code;
	
	private String msg;
	
	private List data;
	
	private int count;
	public DataGrid(){
		
	}
	
	public DataGrid(List data,int count,int code,String msg){
		this.data = data;
		this.count = count;
		this.code = code;
		this.msg = msg;
	}

	

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public List getData() {
		return data;
	}

	public void setData(List data) {
		this.data = data;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
	
	
	
}
package com.zhouzy.ssm.model;

public class PageInfo {

	private int page = 1;
	
	private int limit = 20;

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	
	
	
}

11、layui文件

需要从layui官网下载对应的资源文件 ,放入resources/static目录下

java入门-springboot整合mybatis+layui_第4张图片

 三、启动测试

访问:http://localhost:8080/

java入门-springboot整合mybatis+layui_第5张图片

你可能感兴趣的:(java入门,java进阶-框架篇,spring,boot,ssm,layui,mybatis,springboot)