任务1.对数据表进行CRUD操作
第一个任务首先是最基本的CRUD操作,很简单,直接放代码
package com.example.demo.demos.web.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Column {private int id; //充电桩idprivate String number; //编号private String pileId; //对应充电站idprivate int voltageMin; //充电桩最小电压private int voltageMax; //充电桩最大电压private int voltage; //充电速率(1-快充 2-慢充)private int state; //充电桩状态(1-正常 2-故障)
}
package com.example.demo.demos.web.mapper;import com.example.demo.demos.web.pojo.Column;
import org.apache.ibatis.annotations.*;import java.util.List;@Mapper
public interface ColumnMapper {@Select("select * from `column`")List<Column> list();@Insert("insert into `column`(id,number,pile_id) values(#{id},#{number},#{pileId})")void insert(Column column);@Delete("delete from `column` where id = #{id}")void deleteById(Integer id);@Select("select count(*) from `column` where id = #{id}")String checkId(Integer id);@Update("update `column` set number = #{number} where id = #{id}")void update(Column column);@Select("select count(*) from `column` where number = #{number}")String checkNumberDuplicate(String number);
}
package com.example.demo.demos.web.controller;import com.example.demo.demos.web.pojo.Column;
import com.example.demo.demos.web.pojo.Result;
import com.example.demo.demos.web.service.ColumnService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;import java.util.List;
@RestController
@Slf4j
@RequestMapping("/column")
public class ColumnController {@Autowiredprivate ColumnService columnService;@GetMapping("/select")public Result getAllColumn() {log.info("查询全部充电桩信息");List<Column> columnList = columnService.list();return Result.success(columnList);}@PostMapping("/insert")public Result insertColumn(Column column) {log.info("新增充电桩:{}", column);columnService.add(column);return Result.success(column);}@DeleteMapping("/delete/{id}")public Result deleteColumn(@PathVariable Integer id) {log.info("根据id删除充电桩:{}",id);String ss = columnService.delete(id);return Result.success(ss);}@PutMapping("/update")public Result updateColumn(Column column) {log.info("修改充电桩信息:{}", column);String ss = columnService.update(column);return Result.success(ss);}}
package com.example.demo.demos.web.service;import com.example.demo.demos.web.pojo.Column;import java.util.List;public interface ColumnService {List<Column> list();void add(Column column);String delete(Integer id);String update(Column column);
}
package com.example.demo.demos.web.service.impl;import com.example.demo.demos.web.mapper.ColumnMapper;
import com.example.demo.demos.web.pojo.Column;
import com.example.demo.demos.web.service.ColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class ColumnServiceImpl implements ColumnService {@Autowiredprivate ColumnMapper columnMapper;@Overridepublic List<Column> list(){List<Column> ss= columnMapper.list();return ss;}@Overridepublic void add(Column column){columnMapper.insert(column);}@Overridepublic String delete(Integer id){List<Column> ss= columnMapper.list();for (Column column:ss){if (column.getId() == id){columnMapper.deleteById(id);return "删除成功";}}return "删除失败,编号不存在";}@Overridepublic String update(Column column) {checkNumberDuplicate(column.getNumber());if (checkNumberDuplicate(column.getNumber())){columnMapper.update(column);return "修改成功";}return "修改失败,编号重复";}public boolean checkNumberDuplicate(String number){List<Column> ss= columnMapper.list();for (Column column : ss){if (column.getNumber().equals(number)){return false;}}return true;}
}
任务2:对删除和修改操作添加条件
第一个是根据id删除数据,要判断是否存在该id,就在mapper中添加一条:
@Delete("delete from `column` where id = #{id}")void deleteById(Integer id);@Select("select count(*) from `column` where id = #{id}")String checkId(Integer id);
并且在ColumnServiceImpl添加一个判断语句:
@Overridepublic String delete(Integer id){List<Column> ss= columnMapper.list();for (Column column:ss){if (column.getId() == id){columnMapper.deleteById(id);return "删除成功";}}return "删除失败,编号不存在";}
这样就完成了对id的检查。
第二个是在修改数据信息时,number数据内容不能重复,同样在mapper中添加一条语句:
@Update("update `column` set number = #{number} where id = #{id}")void update(Column column);@Select("select count(*) from `column` where number = #{number}")String checkNumberDuplicate(String number);
并且在ColumnServiceImpl添加一个判断语句和一个判断方法:
@Overridepublic String update(Column column) {checkNumberDuplicate(column.getNumber());if (checkNumberDuplicate(column.getNumber())){columnMapper.update(column);return "修改成功";}return "修改失败,编号重复";}public boolean checkNumberDuplicate(String number){List<Column> ss= columnMapper.list();for (Column column : ss){if (column.getNumber().equals(number)){return false;}}return true;}
这样就完成了条件限制。
任务3:添加拦截器拦截查询请求
新建一个filter包,用于存放拦截器文件。
@Component
public class SelectInterceptor implements HandlerInterceptor {private static final Logger logger = Logger.getLogger(String.valueOf(SelectInterceptor.class));@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String path = request.getRequestURI();logger.info(path);if (path.contains("/select")) {logger.info("请求禁用,系统维护中");response.setContentType("text/plain;charset=UTF-8");response.getWriter().write("系统维护中");return false;} else {return true;}}
}
新建类SelectInterceptor,去进行拦截操作,return false表示禁用,禁用拦截后,在操作台打印出“请求禁用,系统维护中”,使用response返回提示信息。
另外还需要新建一个WebConfig注入拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate SelectInterceptor selectInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(selectInterceptor);}
}
这样就完成了任务3。
任务4:写一个上传文件的接口
这个其实很简单,基本和网上的示例差不多,稍加修改就好
这边的需求是将文件存至指定位置,并且使用当前时间为文件命名
package com.example.demo.demos.web.controller;import lombok.extern.flogger.Flogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@RestController
public class FileUploadController {@PostMapping("/upload")public ResponseEntity<String> uploadFile(MultipartFile file) {if (file.isEmpty()) {return new ResponseEntity<>(HttpStatus.BAD_REQUEST);}try {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String fileName = sdf.format(new Date()) + "_" + file.getOriginalFilename();String filePath = "D:/UploadTest/" + fileName;File dest = new File(filePath);file.transferTo(dest);log.info("文件上传成功,新文件名:" + fileName);return new ResponseEntity<>(HttpStatus.OK);} catch (IOException e) {log.info("文件上传失败");return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);}}
}
另外,附上项目结构图