项目中使用了一些自定义工具类,工具类没有放在本篇博客上,下篇会把代码粘出来
后端项目已经放在git上提供参考
https://github.com/qigangye/springboot_vue
一、整合iview与vue
1.首先下载iview
打开事先搭建好的vue项目,这里本人推荐的IDE使用idea,在idea的terminal中输入指令,npm install –save iview下载iview
npm install --save iview
2.安装完成后打开src目录下的main.js文件,添加三行代码
import iView from 'iview'
import 'iview/dist/styles/iview.css'
Vue.use(iView)
二、搭建springboot整合mybaitis框架
1.准备数据库
注意:数据库字符集一定要选择utf8mb4,MySQL的utf8编码字符集要选择utf8mb4
嗯嗯,简单的设计一个表意思一下
2.使用idea新建一个maven项目
file->new->project->maven
一路next最后finish
2.配置pom文件,搭建一个springboot项目
<?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>
<groupId>com.gangye</groupId>
<artifactId>springboot-vue-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0.7.0</version>
</dependency>
</dependencies>
</project>
3.整体的项目结构
4.配置项目的配置文件application.properties
server.port=8089
#数据库连接池设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/spring_vue_demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=ok
#mybatis的相关配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.config-location=classpath:mybatis-config.xml
5.配置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>
<properties resource="application.properties"></properties>
<settings>
<!-- 使全局的映射器启用或禁用缓存。 -->
<setting name="cacheEnabled" value="ture" />
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 -->
<setting name="aggressiveLazyLoading" value="true"/>
<!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true -->
<setting name="useColumnLabel" value="true" />
<!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false -->
<setting name="useGeneratedKeys" value="false" />
<!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部 -->
<setting name="autoMappingBehavior" value="PARTIAL" />
<!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) -->
<setting name="defaultExecutorType" value="SIMPLE" />
<setting name="defaultStatementTimeout" value="25" />
<setting name="defaultFetchSize" value="100" />
<setting name="safeRowBoundsEnabled" value="false" />
<!-- 使用驼峰命名法转换字段。 -->
<setting name="mapUnderscoreToCamelCase" value="true" />
<!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session -->
<setting name="localCacheScope" value="SESSION" />
<!-- 默认为OTHER,为了解决oracle插入null报错的问题要设置为NULL -->
<setting name="jdbcTypeForNull" value="NULL" />
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
</settings>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${spring.datasource.driver-class-name}"></property>
<property name="url" value="${spring.datasource.url}"></property>
<property name="username" value="${spring.datasource.username}"></property>
<property name="password" value="${spring.datasource.password}"></property>
</dataSource>
</environment>
</environments>
<databaseIdProvider type="org.apache.ibatis.mapping.VendorDatabaseIdProvider">
<property name="MySQL" value="mysql"></property>
<property name="Oracle" value="Oracle"></property>
</databaseIdProvider>
</configuration>
6.定义日志的配置logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyy-MM-dd HH:mm:ss.SSS} %p %t - %m%n</pattern>
<charset class="java.nio.charset.Charset">UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<appender name="DefaultAppender"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<append>true</append>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>logs/logback-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>300MB</maxFileSize>
<maxHistory>300</maxHistory>
<totalSizeCap>90GB</totalSizeCap>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyy-MM-dd HH:mm:ss.SSS} %p %t - %m%n</pattern>
<charset class="java.nio.charset.Charset">UTF-8</charset>
</encoder>
</appender>
<logger name="com.cscrb.mapper" level="DEBUG" additivity="false">
<appender-ref ref="console" />
</logger>
<root>
<level value="info" />
<appender-ref ref="console" />
<appender-ref ref="DefaultAppender" />
</root>
</configuration>
7.创建项目的实体类UserInfo.java
package com.cscrb.entity;
/**
* @Classname UserInfo
* @Description 用户基本信息
* @Date 2020/3/4 16:50
*/
public class UserInfo {
private Integer id;
private String userName;
private String passWd;
private String address;
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 getPassWd() {
return passWd;
}
public void setPassWd(String passWd) {
this.passWd = passWd;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
8.创建数据访问层
package com.cscrb.mapper;
import com.cscrb.entity.UserInfo;
import java.util.List;
/**
* @Classname UserMapper
* @Description 用户信息mapper层接口
* @Date 2020/3/4 16:51
*/
public interface UserMapper {
//展示所有用户
List<UserInfo> showAllUser();
//根据用户信息返回用户
UserInfo findByUser(UserInfo userInfo);
//根据主键查看用户信息
UserInfo selectByPrimary(Integer id);
//新增用户
void addUser(UserInfo userInfo);
//修改用户信息
void updateUserInfo(UserInfo userInfo);
}
9.创建对应的mapper.xml配置文件注意大小写,文件名与mapper层中的java文件名一致
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cscrb.mapper.UserMapper">
<select id="showAllUser" resultType="com.cscrb.dto.UserInfoDto">
select id,username,address from user_info
</select>
<select id="findByUser" parameterType="com.cscrb.entity.UserInfo" resultType="com.cscrb.entity.UserInfo">
select * from user_info where username = #{userName} and passwd = #{passWd}
</select>
<select id="selectByPrimary" parameterType="java.lang.Integer" resultType="com.cscrb.dto.UserInfoDto">
select id,username,address from user_info where id = #{id}
</select>
<insert id="addUser" parameterType="com.cscrb.entity.UserInfo">
insert into user_info
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userName != null">
username,
</if>
<if test="passWd !=null">
passwd,
</if>
<if test="address !=null">
address,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="passWd != null">
#{passWd,jdbcType=VARCHAR},
</if>
<if test="address != null">
#{address,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateUserInfo" parameterType="com.cscrb.entity.UserInfo" >
update user_info
<set>
<if test="userName != null and userName != ''">username = #{userName},</if>
<if test="passWd != null and passWd != ''">passwd = #{passWd},</if>
<if test="address != null and address != ''">address = #{address},</if>
</set>
where id = #{id}
</update>
</mapper>
9.创建服务层、controller层
package com.cscrb.service;
import com.cscrb.entity.UserInfo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Classname UserService
* @Description 用户的service层
* @Date 2020/3/4 16:57
* @Created by gangye
*/
public interface UserService {
List<UserInfo> showAllUserInfo();
UserInfo findUser(UserInfo userInfo);
UserInfo selectByPrimary(Integer id);
void insertUser(UserInfo userInfo);
void updateUserInfo(UserInfo userInfo);
}
package com.cscrb.service.impl;
import com.cscrb.entity.UserInfo;
import com.cscrb.mapper.UserMapper;
import com.cscrb.service.UserService;
import com.cscrb.utils.SHAPwd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Classname UserServiceImpl
* @Description UserSercice层的实现类
* @Date 2020/3/4 17:00
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<UserInfo> showAllUserInfo() {
return userMapper.showAllUser();
}
@Override
public UserInfo findUser(UserInfo userInfo) {
return userMapper.findByUser(userInfo);
}
@Override
public UserInfo selectByPrimary(Integer id) {
return userMapper.selectByPrimary(id);
}
@Override
public void insertUser(UserInfo userInfo) {
userInfo.setPassWd(SHAPwd.signature(userInfo.getPassWd()));
userMapper.addUser(userInfo);
}
@Override
public void updateUserInfo(UserInfo userInfo) {
userMapper.updateUserInfo(userInfo);
}
}
package com.cscrb.controller;
import com.cscrb.entity.UserInfo;
import com.cscrb.service.UserService;
import com.cscrb.utils.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Classname UserController
* @Description userController
* @Date 2020/3/5 9:21
*/
@RestController
@RequestMapping(value = "/userController")
public class UserController {
private Logger logger = LogUtils.get(UserController.class);
@Autowired
private UserService userService;
//展示所有用户
@PostMapping("/userList")
public Response getAllUserList(){
List<UserInfo> userInfoList = userService.showAllUserInfo();
Response response = Response.newResponse();
return response.setData(userInfoList);
}
//用户注册
@PostMapping("/registerUser")
public Response registerUser(@RequestBody UserInfo userInfo){
Response response = Response.newResponse();
try {
if (StringUtils.isNotEmpty(userInfo.getUserName()) && StringUtils.isNotEmpty(userInfo.getPassWd())) {
userService.insertUser(userInfo);
return response.OK();
} else {
return response.setError(ErrorEnum.account_password_null);
}
} catch (Exception e){
logger.info("用户注册失败");
return response.setCodeAndMessage(9999,"用户注册失败");
}
}
//用户登录
@PostMapping("/userLogin")
public Response login(@RequestBody UserInfo userInfo){
Response response = Response.newResponse();
String pwd = SHAPwd.signature(userInfo.getPassWd());
userInfo.setPassWd(pwd);
if (StringUtils.isNotEmpty(userService.findUser(userInfo).getId())){
return response.OK();
}
return response.setError(ErrorEnum.account_password_err);
}
//根据id查询用户信息
@PostMapping("/showUserInfo")
public Response showUserInfo(Integer id){
Response response = Response.newResponse();
UserInfo userInfo = userService.selectByPrimary(id);
return response.setData(userInfo);
}
//更改用户信息
@PostMapping("/updateUserInfo")
public Response updateUserInfo(@RequestBody UserInfo userInfo){
Response response = Response.newResponse();
if (StringUtils.isNotEmpty(userInfo.getId())){
if (StringUtils.isNotEmpty(userInfo.getPassWd())){
userInfo.setPassWd(SHAPwd.signature(userInfo.getPassWd()));
}
userService.updateUserInfo(userInfo);
return response.OK();
}
return response.setCodeAndMessage(9999,"更改信息失败!");
}
}
10.创建启动类
package com.cscrb;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Classname StartApplication
* @Description 项目启动类
* @Date 2020/3/4 16:35
*/
@SpringBootApplication
@MapperScan("com.cscrb.mapper")
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class ,args);
}
}
此处的MapperScan注解是扫描对应包下的文件
11.搭建完毕使用postman测试
事先使用注册接口测试了几个数据
查看日志
控制台显示debug日志,日志文件记录信息
测试一下登录接口:
查看返回结果状态值(nice)
结合日志(密码使用自定义工具加密了)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/12323.html