本次项目主要由三个部分组成 一、搭建基础的springboot的项目 二、与mysql连接,进行最基础的增删改查的操作 三、使用aop切面,进行参数的捕获和日志的打印
一、搭建最基础的springboot项目
搭建一个由maven项目创建的springboot项目:springboot-demo-bwd
maven的配置如下所示,此处三项式配置maven的路径,setting文件的位置和maven包的存放位置。 pom文件的配置如下所示:
<?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.bwd</groupId>
<artifactId>springboot-demo-bwd</artifactId>
<version>1.0-SNAPSHOT</version>
<!--指定父级依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
</parent>
<!---->
<dependencies>
<!--开发springboot的web应用,需要引入starter-web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--加入链接mysql数据库需要的依赖包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--引入jdbc的依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!--在前端把用map接收的参数转换成vo-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.8</version>
</dependency>
<!--引入log4j的依赖包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!--引入aop的依赖包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
</project>
配置启动该springboot项目的端口: 创建application.yml文件,把启动端口置成8088:
创建一个TestController,启动该springboot项目,具体代码如下所示: package com.bwd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestController {
public static void main(String[] args) {
SpringApplication.run(TestController.class,args);
}
}
如图所示,项目启动成功 项目创建成功之后,可以在这个main方法直接打印语句,简单执行该程序。
二、与mysql连接,进行最基础的增删改查的操作
本次主要采用jdbctemplate的方式执行数据库的操作,主要操作为增删改查用户clerk的信息。 mysql的表信息如下所示: 在application.yml中增加以下的数据库连接信息:
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#druid 数据源配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
ClerkDao接口里的接口方法(增删改查,没有什么技术含量)
package com.bwd.dao;
import com.bwd.bean.Clerk;
import java.util.List;
public interface ClerkDao {
public int addClerk(Clerk clerk);
public int deleteClerkById(String id);
public List<Clerk> queryAllClerks();
public Clerk queryClerkById(String id);
public int updateClerkById(Clerk clerk);
}
Dao接口的实现类ClerkDaoImpl 此处在增加一条用户信息时,id采用了uuid随机生成的形式
package com.bwd.dao.impl;
import com.bwd.bean.Clerk;
import com.bwd.dao.ClerkDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.UUID;
@Repository
public class ClerkDaoImpl implements ClerkDao {
public static String QUERY_SQL = "select * from test_clerk where id = ?";
public static String QUERY_ALL_SQL = "select * from test_clerk";
public static String INSERT_SQL = "insert into test_clerk values(?,?,?,?)";
public static String DETELE_SQL = "delete from test_clerk where id = ? ";
public static String UPDATE_SQL = "update test_clerk set clerkNo = ?, clerkName = ?, clerkAge = ? where id = ?";
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int addClerk(Clerk clerk) {
UUID uuid = UUID.randomUUID();
clerk.setId(uuid.toString().substring(2, 10));
return jdbcTemplate.update(INSERT_SQL,new Object[]{clerk.getId(),clerk.getClerkNo(),clerk.getClerkName(),clerk.getClerkAge()});
}
@Override
public int deleteClerkById(String id) {
return jdbcTemplate.update(DETELE_SQL,new Object[]{id});
}
@Override
public List<Clerk> queryAllClerks() {
return jdbcTemplate.query(QUERY_ALL_SQL,new BeanPropertyRowMapper<Clerk>(Clerk.class));
}
@Override
public Clerk queryClerkById(String id) {
List<Clerk> res = jdbcTemplate.query(QUERY_SQL,new BeanPropertyRowMapper<Clerk>(Clerk.class),new Object[]{id});
return res.size()>0?res.get(0):new Clerk();
}
@Override
public int updateClerkById(Clerk clerk) {
return jdbcTemplate.update(UPDATE_SQL,new Object[]{clerk.getClerkNo(),clerk.getClerkName(),clerk.getClerkAge(),clerk.getId()}); }
}
ClerkService的接口方法:
package com.bwd.service;
import com.bwd.bean.Clerk;
import java.util.List;
public interface ClerkService {
public int addClerk(Clerk clerk);
public int deleteClerkById(String id);
public List<Clerk> queryAllClerks();
public Clerk queryClerkById(String id);
public int updateClerkById(Clerk clerk);
}
ClerkService的的接口实现类ClerkService,此处给该接口类加上了事务注解,因为该类涉及到的所有方法都想做事务控制;
package com.bwd.service.impl;
import com.bwd.bean.Clerk;
import com.bwd.dao.ClerkDao;
import com.bwd.service.ClerkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
@Service("clerkService")
public class ClerkServiceImpl implements ClerkService{
@Autowired
private ClerkDao clerkDao;
@Override
public int addClerk(Clerk clerk) {
return clerkDao.addClerk(clerk);
}
@Override
public int deleteClerkById(String id) {
return clerkDao.deleteClerkById(id);
}
@Override
public List<Clerk> queryAllClerks() {
return clerkDao.queryAllClerks();
}
@Override
public Clerk queryClerkById(String id) {
return clerkDao.queryClerkById(id);
}
@Override
public int updateClerkById(Clerk clerk) {
return clerkDao.updateClerkById(clerk);
}
}
ClerkController中的方法。此处的参数除了get方法外,post方法采用的接收参数统一为map。因为后续想在controller类中加上一个aop切面,用于打印所有从前端发过来的请求参数,map类型的参数是可以直接打印出来的(vo类型的如果要打印估计要重写toString方法)
package com.bwd.controller;
import com.alibaba.fastjson.JSON;
import com.bwd.bean.Clerk;
import com.bwd.service.ClerkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/clerk")
public class ClerkController {
@Autowired
private ClerkService clerkService;
@PostMapping("/queryAllClerks")
@ResponseBody
public List<Clerk> queryAllClerks(){
return clerkService.queryAllClerks();
}
@GetMapping("/queryClerkById")
@ResponseBody
public Clerk queryClerkById(@RequestParam String id){
return clerkService.queryClerkById(id);
}
@PostMapping("/addClerk")
@ResponseBody
public String addClerk(@RequestBody Map<String,Object> params) {
Clerk clerk = JSON.parseObject(JSON.toJSONString(params),Clerk.class);
int res = 0;
try{
res = clerkService.addClerk(clerk);
}catch(Exception e){
}finally {
return "此次共插入了" + res + "条数据";
}
}
@PostMapping("/updateClerkById")
@ResponseBody
public String updateClerkById(@RequestBody Map<String,Object> params){
Clerk clerk = JSON.parseObject(JSON.toJSONString(params),Clerk.class);
int res = 0;
try{
res = clerkService.updateClerkById(clerk);
}catch(Exception e){
}finally {
return "此次共修改了" + res + "条数据";
}
}
@GetMapping("/deleteClerkById")
@ResponseBody
public String deleteClerkById(@RequestParam String id){
int res = 0;
try{
res = clerkService.deleteClerkById(id);
}catch(Exception e){
}finally {
return "此次共删除了" + res + "条数据";
}
}
}
切面方法。目的是为了在前端的请求参数过来的时候能把请求参数打印出来:
package com.bwd.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect
@Component
public class LinkAspect {
private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(public * com.bwd.controller.ClerkController.*(..))")
public void linKAspect(){
logger.info("执行aop方法");
}
@Before("linKAspect()")
public void before(JoinPoint joinPoint)
{
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("URL: {}",request.getRequestURL().toString());
logger.info("HTTP请求类型: {}",request.getMethod());
logger.info("执行方法: {}",joinPoint);
logger.info("传递参数: {}", Arrays.toString(joinPoint.getArgs()));
}
}
最终执行结果: 项目的整体目录如下所示:
项目名称是男朋友的名字缩写,感谢他的大力支持。为了写这篇文章周末的时间基本都在重装系统和各种环境,男朋友隔着视频即使再想玩游戏也都在等我忙完。
|