小张推荐:瑞吉外卖Day01,瑞吉外卖Day03
1.登陆功能
1.1结果封装类
- 导入返回结果类R此类是一个通用结果类。
- 服务端响应的所有结果最终都会包装成此种类型返回给前端页面
注意属性名,莫要写错,不然与前端很难对接!!!!
/**
* 通用返回结果
* @param <T>
*/
@Data
public class R<T> {
private Integer code;//编码:1:成功,0:失败
private String msg;//错误信息
private T data;//数据
private Map map=new HashMap();//动态数据
/**
* 响应成功
* @param object
* @param <T>
* @return
*/
public static <T>R<T> success(T object){
R<T> r=new R<>();
r.data=object;
r.code=1;
return r;
}
/**
* 响应错误
* @param mgs
* @param <T>
* @return
*/
public static <T>R<T> error(String mgs){
R<T> r=new R<>();
r.mgs=mgs;
r.code=0;
return r;
}
public R<T> add(String key,Object value){
this.map.put(key,value);
return this;
}
}
1.2实体类
/**
* 员工实体类
*/
@Data
@TableName("employee")
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Long id;
private String username;
private String name;
private String password;
private String phone;
private String sex;
private String idNumber;
private Integer status;
private LocalDateTime createTime;
private LocalDateTime updateTime;
private Long createUser;
private Long updateUser;
}
1.3mapper层
@Repository
@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}
1.4Service层
public interface EmployeeService extends IService<Employee> {
}
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
}
1.5Controller层
@Autowired
private EmployeeService employeeService;
/**
* 登录
*/
@PostMapping("/login")
public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
//md5加密
String password = employee.getPassword();
password = DigestUtils.md5DigestAsHex(password.getBytes());
//查数据库
LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
queryWrapper.eq(Employee::getUsername, employee.getUsername());
Employee emp = employeeService.getOne(queryWrapper);
//判断是否有用户
if (emp == null) {
return R.error("用户不存在~");
}
//判断密码
if (!emp.getPassword().equals(password)) {
return R.error("密码错误,请重新输入~");
}
//判断状态
if (emp.getStatus() == 0) {
return R.error("该账号已禁用!!!");
}
//登陆成功,将员工id存入Session并返回登陆成功
request.setAttribute("employee", emp.getId());
return R.success(emp);
}
2.退出功能
2.1Controller层
/**
* 退出
*/
@PostMapping("/logout")
public R<String> logout(HttpServletRequest request) {
//清除session中保存的当前登陆者的id
request.getSession().removeAttribute("employee");
return R.success("退出成功");
}
2.2添加登录拦截
- 存在一个问题:用户如果不登录,直接访问系统首页面,照样可以正常访问。
- 解决:使用过滤器或者拦截器,在过滤器或者拦截器中判断用户是否已经完成登录,如果没有登录则跳转到登录页面。
- 记得主程序类上添加@ServletComponentScan
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
//路径匹配器
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//1.获取本次请求的uri
String requestURI = request.getRequestURI();
log.info("拦截到请求:{}",requestURI);
//2.定义放行的请求路径
String[] urls = new String[]{"/employee/login", "/employee/logout", "/backend/**", "/front/**"};
//3.判断本次请求是否需要处理
boolean check = check(urls,requestURI);
//4.如果不需要处理,直接放行
if (check) {//true,不需要处理
log.info("本次请求不需要处理{}",requestURI);
//放行
filterChain.doFilter(request, response);
return;
}
//5.判断当前登陆状态,如果已经登录,则直接放行
Object employee = request.getSession().getAttribute("employee");
log.info("用户:"+employee);
if (request.getSession().getAttribute("employee") != null) {
log.info("后台用户已登录,用户id:{}",request.getSession().getAttribute("employee"));
filterChain.doFilter(request, response);
return;
}
log.info("用户未登录");
//6.如果未登录,返回未登录结果,通过输出流向客户端响应数据
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
}
/**
* 路径匹配,是否需要放行
*
* @param requestURI
* @param urls
* @return
*/
public boolean check(String[] urls,String requestURI) {
//循环放行的路径的数组
for (String url : urls) {
//当前路径是否与放行路径匹配
boolean match = PATH_MATCHER.match(url, requestURI);
if (match) {
//不需要处理
return true;
}
}
//需要处理
return false;
}
}
3.新增员工
3.1controller层
/**
*新增员工
*/
@PostMapping
public R<String> save(@RequestBody Employee employee,HttpServletRequest request){
log.info("新增员工,员工信息:{}",employee.toString());
//设置初始密码123456,但需要MD5加密
employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
//获取当前登录用户的id
Long id = (Long) request.getSession().getAttribute("employee");
employee.setCreateUser(id);
employee.setUpdateUser(id);
employeeService.save(employee);
return R.success("新增员工成功");
}
3.2美中不足
- 因为数据库中的username字段设置了唯一标识,当添加相同账号时,会抛出异常:java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '666888' for key 'employee.idx_username'
3.3完美解决
- 1.添加try-cratch捕获,这种方法会导致后面要写大量try-catch
- 2.添加全局异常处理器(推荐)
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常处理方法
* @return
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
log.error(exception.getMessage());
if (exception.getMessage().contains("Duplicate entry")){
String[] arr = exception.getMessage().split(" ");
String msg=arr[2]+"已存在";
return R.error(msg);
}
return R.error("未知错误");
}
}
3.5@ControllerAdvice作用
- 1·结合方法型注解@ExceptionHandler,用于捕获Controller中抛出的指定类型的异常,从而达到不同类型的异常区别处理的目的。
- 2·结合方法型注解@InitBinder,用于request中自定义参数解析方式进行注册,从而达到自定义指定格式参数的目的
- 3.结合方法型注解@ModelAttribute,表示其注解的方法将会在目标Controller方法执行之前执行。
4.员工信息分页查询
4.1添加分页插件
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor=new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
}
4.2分页查询
@GetMapping("/page")
public R<Page> page(int page, int pageSize, String name) {
log.info("page:{},pageSize:{},name:{}",page,pageSize,name);
//构造分页构造器
Page pageInfo=new Page(page,pageSize);
//构造条件构造器
LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
//过滤条件
queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
//排序条件
queryWrapper.orderByDesc(Employee::getUpdateTime);
//分页查询
employeeService.page(pageInfo,queryWrapper);
return R.success(pageInfo);
}