目录
1、代码结构
config
package com.course.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.pathMapping("/")
.select()
.paths(PathSelectors.regex("/.*"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("UserManager service API")
.contact(new Contact("dazhou", "", "42197393@qq.com"))
.description("this is UserManager service API")
.version("1.0")
.build();
}
}
controller
package com.course.controller;
import com.course.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
@Log4j
@RestController
@Api(value = "v1",tags = "用户管理系统")
@RequestMapping("v1")
public class UserManager {
//首先获取一个执行sql语句的对象
@Autowired
private SqlSessionTemplate template;
@ApiOperation(value = "登陆接口",httpMethod = "POST")
@RequestMapping(value = "/login",method = RequestMethod.POST)
public Boolean login(HttpServletResponse response, @RequestBody User user){
//拿过user来到数据库里面插,是不是有这个用户
//login01需要和mysql.xml中 <!--登陆接口sql-->中的id一致
int i = template.selectOne("login01",user);
//如果有就成功返回对应的cookies信息 login:true
Cookie cookie = new Cookie("login","true");
response.addCookie(cookie);
log.info("查看到的结果是"+i);
if(i==1){
return true;
}
return false;
}
@ApiOperation(value = "添加用户接口",httpMethod = "POST")
@RequestMapping(value = "/addUser",method = RequestMethod.POST)
public boolean addUser(HttpServletRequest request,@RequestBody User user){
Boolean x = verifyCookies(request);
int result = 0;
if(x != null){
result = template.insert("addUser",user);
}
if(result>0){
log.info("添加用户的数量是:"+result);
return true;
}
return false;
}
private Boolean verifyCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if(Objects.isNull(cookies)){
log.info("cookies为空");
return false;
}
for(Cookie cookie : cookies){
if(cookie.getName().equals("login") &&
cookie.getValue().equals("true")){
log.info("cookies验证通过");
return true;
}
}
return false;
}
@ApiOperation(value = "获取用户(列表)信息接口",httpMethod = "POST")
@RequestMapping(value = "/getUserInfo",method = RequestMethod.POST)
public List<User> getUserInfo(HttpServletRequest request,@RequestBody User user){
Boolean x = verifyCookies(request);
if(x==true){
List<User> users = template.selectList("getUserInfo",user);
log.info("getUserInfo获取到的用户数量是" +users.size());
return users;
}else {
return null;
}
}
@ApiOperation(value = "更新/删除用户接口",httpMethod = "POST")
@RequestMapping(value = "/updateUserInfo",method = RequestMethod.POST)
public int updateUser(HttpServletRequest request,@RequestBody User user){
Boolean x = verifyCookies(request);
int i = 0;
if(x==true) {
i = template.update("updateUserInfo", user);
}
log.info("更新数据的条目数为:" + i);
return i;
}
}
model
package com.course.model;
import lombok.Data;
@Data
public class User {
private int id;
private String userName;
private String password;
private String age;
private String sex;
private String permission;
private String isDelete;
}
springboot启动类
package com.course;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.annotation.PreDestroy;
@EnableScheduling
@SpringBootApplication
public class Application {
private static ConfigurableApplicationContext context;
public static void main(String[] args) {
Application.context = SpringApplication.run(Application.class,args);
}
@PreDestroy
public void close(){
Application.context.close();
}
}
2、配置资源
mysql.xml
<?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.course">
<!--登陆接口sql-->
<select id="login01" parameterType="com.course.model.User" resultType="Integer">
select count(*) from user
where userName=#{userName}
and password=#{password}
</select>
<!--添加用户接口-->
<insert id="addUser" parameterType="com.course.model.User">
insert into
user (userName,password,sex,age,permission,isDelete)
values (#{userName},#{password},#{sex},#{age},#{permission},#{isDelete});
</insert>
<!--获取用户信息sql-->
<select id="getUserInfo" parameterType="com.course.model.User" resultType="com.course.model.User">
select * from user
<trim prefix="WHERE" prefixOverrides="and">
<if test="null != id and '' !=id">
AND id=#{id}
</if>
<if test="null != userName and '' !=userName">
AND userName=#{userName}
</if>
<if test="null != sex and '' !=sex">
AND sex=#{sex}
</if>
<if test="null != age and '' !=age">
AND age=#{age}
</if>
<if test="null != permission and '' !=permission">
AND permission=#{permission}
</if>
<if test="null != isDelete and '' !=isDelete">
AND isDelete=#{isDelete}
</if>
</trim>
</select>
<!--更新/删除用户信息动作-->
<update id="updateUserInfo" parameterType="com.course.model.User">
update user
<trim prefix="SET" suffixOverrides=",">
<if test="null != userName and '' !=userName">
userName=#{userName},
</if>
<if test="null != sex and '' !=sex">
sex=#{sex},
</if>
<if test="null != age and '' !=age">
age=#{age},
</if>
<if test="null != permission and '' !=permission">
permission=#{permission},
</if>
<if test="null != isDelete and '' !=isDelete">
isDelete=#{isDelete},
</if>
</trim>
where id = #{id}
</update>
</mapper>
application.yml
server:
port: 8888
logging:
# 日志文件的路径
path: logs
file:
# 日志文件的名字
name: mylog.log
pattern:
# file 是指日志文件中日志的格式
console: "%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger{50}- %msg%n"
file: "%d{yyyy/MM/dd-HH:mm:ss} ---- [%thread] %-5level %logger{50}- %msg%n"
spring:
application:
name: report
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/course
username: root
password: 123456
mybatis:
type-aliases-package: com.course.model
mapper-locations:
- mapper/*
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n"/>
<property name="LOG_PATH" value="${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}"/>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/${LOG_FILE}.%d{yyyy-MM-dd}</fileNamePattern>
</rollingPolicy>
<encoder charset="UTF-8">
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<appender name="CRAWLER_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/event.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/event.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%msg%n</pattern>
</encoder>
</appender>
<logger name="com.business.intelligence.util.CrawlerLogger" level="INFO" additivity="false">
<appender-ref ref="CRAWLER_LOG"/>
</logger>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
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>
<typeAliases>
<package name="com.course.model"/>
</typeAliases>
<mappers>
<mapper resource="mapper/mysql.xml"/>
</mappers>
</configuration>
数据库配置
3、测试验证
可以看到返回值为true了,说明已经在数据库查到相对于的数据了