素材巴巴 > 程序开发 >

SpringMVC 与 SpringBoot

程序开发 2023-09-03 06:03:28

SpringMVC

如何将前端传过来的json数据 转化为对象
@ResponseBody //将后端的对象数据转化为json
 @RequestBody //将前端的json数据转化为对象@RequestMapping("/saveAccount")
 //    @ResponseBody //将后端的对象数据转化为json   @RequestBody //将前端的json数据转化为对象 位置 形参的数据类型前public R saveAccount(@RequestBody Account account){System.out.println("处理添加用户信息的请求");R r = new R(200,"添加成功",account);return r;}
 

SpringMVC 项目搭建

1.导入依赖

org.springframeworkspring-webmvc5.3.1org.projectlomboklombok1.18.22providedcom.fasterxml.jackson.corejackson-databind2.13.0com.fasterxml.jackson.corejackson-annotations2.13.0com.fasterxml.jackson.corejackson-core2.13.0javax.servletjavax.servlet-api3.1.0providedjavax.servlet.jspjavax.servlet.jsp-api2.3.3provided
 
 

2.配置相关文件(springmvc.xml 和 web.xml)

​ springmvc.xml


 
 
 

​ web.xml


 DispatcherServletorg.springframework.web.servlet.DispatcherServletcontextConfigLocationclasspath:springmvc.xmlDispatcherServlet/
 
 

3.搭建基本的包目录结构

4.常用的注解

​ controller中的:

@RestController                                       //@RestController:  @Controller+@ResponseBody
 @RequestMapping("/account")   //  窄化请求:防止请求路径冲突
 @RequestMapping(value = "/queryAccount",method = RequestMethod.GET)// 请求路径 处理 get post put delete请求 method = RequestMethod.GET 限定请求方式
 @GetMapping("/queryAccount") //替代 @RequestMapping(value = "/queryAccount",method = RequestMethod.GET)
 @ResponseBody// 将对象转成json字符串返回public R queryAccount(@RequestParam("page") Integer cuurentPage,Integer everyPage){System.out.println("处理查询用户信息的请求");R r = new R(200,"查询成功",null);return r;}
 //    @ResponseBody //将后端的对象数据转化为json   @RequestBody //将前端的json数据转化为对象 位置 形参的数据类型前public R saveAccount(@RequestBody Account account){System.out.println("处理添加用户信息的请求");R r = new R(200,"添加成功",account);return r;}
 

SpringBoot 项目搭建

1.添加依赖 (mysql hutool mybatis-plus)


 com.baomidoumybatis-plus3.5.1
 
 com.baomidoumybatis-plus-boot-starter3.3.2
 
 
 mysqlmysql-connector-java8.0.13
 
 
 cn.hutoolhutool-all5.8.4
 
 

2.创建包结构

​ controller service mapper entity requestParam util

3.继承父类加实现接口

​ 服务层接口 继承IService

​ 服务层实现类 继承ServiceImpl 实现服务层接口

​ 持久层接口 继承 BaseMapper

4.添加注解

​ 启动类添加扫描注解 @MapperScan

​ 控制层 @Controller

​ 服务层实现类 @Service

5.配置application.yml文件

server:port: 8080
 spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/mysql0514?useSSL=false&serverTimezone=UTCusername: rootpassword: 123456
 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #sql日志打印
 

6.实体类搭建mybatis-plus

@Data
 @AllArgsConstructor
 @NoArgsConstructor
 @TableName("account")
 public class Account {@TableId(type = IdType.AUTO)private Integer accid;private String accname;private String accpass;private String accstate;@JsonFormat(pattern = "yyyy-mm-dd hh:mm:ss")// 后台到前台@DateTimeFormat(pattern = "yyyy-mm-dd hh:mm:ss")// 前台到后台@TableField("createDate")private Date createDate;
 } 
 

6.业务逻辑

​ 前端请求控制层—>控制层调用服务层—>服务层调用持久层

@RestController
 @RequestMapping("/account")
 public class AccountController {@Autowiredprivate AccountService accountService;/** @description:用户登录* @param: [param]* @return: com.teao.springboot001.entity.R**/@PostMapping("/login")public R login(AccountParam param){Account account = new Account();BeanUtil.copyProperties(param,account);Account account1 = accountService.login(account);if (account1==null){return new R(-1000,"登录失败",null);}return new R(200,"登录成功",account1);}
 }
 
@Service
 public class AccountServiceImpl extends ServiceImpl implements AccountService {@Resourceprivate AccountMapper accountMapper;@Overridepublic Account login(Account account) {QueryWrapper queryWrapper = new QueryWrapper();queryWrapper.eq("accname",account.getAccname());queryWrapper.eq("accpass",account.getAccpass());Account account1 = accountMapper.selectOne(queryWrapper);return account1;}
 }
 
@Repository
 public interface AccountMapper extends BaseMapper {}   
 

提高开发效率—自动生成代码

1.安装插件MyBatisX

2.连数据库

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AlgTCoRg-1659158699813)(C:UsersTiiTAppDataRoamingTyporatypora-user-imagesimage-20220701085001261.png)]

SpringBoot 总结

1.单表分页条件查询(条件在服务层)

​ 控制层将当前页与每页记录数,以及构成条件的类传到服务层,通过服务层实现类 封装分页(Page)和条件(QueryWrapper),最后调用持久层方法完成查询。

​ 添加分页配置类。

2.多表分页条件查询(条件在mapper.xml中)

​ 需要按部就班的调用 控制层->服务层->持久层->映射到mapper.xml文件中

3.逻辑删除

​ 实体类属性上加注解

@TableLogic
 

4.添加,修改时自动填充数据

​ 添加注解

@TableField(fill = FieldFill.INSERT_UPDATE)
 

​ 添加自动填充配置类

SpringBoot异常处理问题

​ 思想:控制层return成功的结果 服务层return失败的结果

1.自定义两个异常类

​ 自定义异常类:ServiceException 继承 Exception

public class ServiceException extends Exception { //自定义异常类,生成对应的set,get方法private String message;
 }
 

​ 全局异常处理类:CustomExceptionControllerAdvice

@RestControllerAdvice //添加注解
 public class CustomExceptionControllerAdvice {  //全局异常处理类  从上往下处理的范围越来越广@ExceptionHandler(ServiceException.class) // 指定处理的异常类型public R dealServiceException(ServiceException exception){return new R(-1000,"操作失败",exception.getMessage());}@ExceptionHandler(NullPointerException.class)public R dealNullPointerException(){return new R(500,"空指针异常",null);}@ExceptionHandler(Exception.class)public R dealException(){return new R(500,"服务器正在维护",null);}
 }
 

2.服务层实现逻辑(异常一抛到底)

@Override
 public void saveAccount(SaveAccountParam saveAccountParam) throws ServiceException{if(saveAccountParam==null){throw new ServiceException("输入的参数有误,请重新输入");// 抛出异常}Account account = new Account();BeanUtil.copyProperties(saveAccountParam,account);QueryWrapper queryWrapper =  new QueryWrapper();queryWrapper.eq("accname",saveAccountParam.getAccname());Account account1 = accountMapper.selectOne(queryWrapper);// 根据传入的条件查找 有重无添加if (account1==null){accountMapper.insert(account);}else{throw new ServiceException("账号重复,添加失败");}
 }
 

SpringBoot 的请求参数校验注解

SpringBoot 的请求参数校验注解

​ **思想:**形参前加注解 @Validated 或 @Valid,在形参实体类中对应的属性上加数据校验注解


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。