目录
1.FruitType.vue
<template>
<div style="margin-bottom: 10px;">
<el-button v-on:click="hanleAdd" type="primary" size="small">添加</el-button>
</div>
<el-table :data="tableData" border stripe style="width: 100%" >
<el-table-column prop="name" label="名称" width="180" />
<el-table-column label="操作">
<template #default="scope">
<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog v-model="dialogFormVisible" :title="type.id?'编辑':'添加'">
{{type}}
<el-form :model="type">
<el-form-item label="名称">
<el-input v-model="type.name" autocomplete="off" />
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogFormVisible = false">取消</el-button>
<el-button type="primary" @click="handleSave">保存</el-button>
</span>
</template>
</el-dialog>
</template>
<script>
import qs from "qs"
import request from "@/request/request"
export default {
name: "ListView",
data(){
return{
dialogFormVisible:false,
type:{
id:null,
name:null
},
tableData : []
}
},
methods:{
//打开添加对话框
hanleAdd(row){
this.dialogFormVisible = true;
this.type = {
id:null,
name:null
}
},
//打开编辑对话框
handleEdit(row){
this.dialogFormVisible = true;
this.type = row;
},
//删除分类信息
handleDelete(id){
request({
method: 'delete',
url: '/type/'+id
}).then((respData)=>{
if(respData.code ==200){
this.loadType();
}
alert(respData.msg);
});
},
//保存分类信息
handleSave(){
let param= this.type;
if(this.type.id){
//编辑
param.shopId=1;
param = qs.stringify(param);
request({
method: 'put',
url: '/type/'+this.type.id,
data:param
}).then((respData)=>{
if(respData.code ==200){
this.dialogFormVisible = false;
//编辑成功
this.loadType();
}
alert(respData.msg);
});
}else{
//POST请求默认携带的是json参数,如果想转成普通参数格式,我们可以结束qs
param = qs.stringify(param);
//添加
request({
method: 'post',
url: '/type',
data:param
}).then((respData)=>{
if(respData.code ==200){
this.dialogFormVisible = false;
//添加成功
this.loadType();
}
alert(respData.msg);
});
}
},
//发送请求加载店铺下的水果分类信息 【想办法携带token】
loadType(){
request({
method: 'get',
url: '/type'
}).then((respData)=>{
this.tableData = respData.data;
});
}
},
//当组件创建成功后执行里面的方法
created() {
this.loadType();
}
}
</script>
<style scoped>
</style>
2.request.js
import axios from "axios"
const instance=axios.create(
{
baseURL:'http://localhost:8080'
}
);
//添加请求拦截器
instance.interceptors.request.use(function (config){
let token=sessionStorage.getItem("token");
if(token){
config.headers["token"]=token;
}
//在发送请i去之前做些什么
return config;
},function (error){
return Promise.reject(error);
}
);
instance.interceptors.response.use(function (respense){
//对响应数据做点什么
return respense.data;
},function (error){
return Promise.reject(error)
});
export default function (param){
return instance(param);
}
3.TypeController
package com.neu.fruit.controller;
import com.neu.fruit.dto.TypeDTO;
import com.neu.fruit.exception.ParamException;
import com.neu.fruit.service.TypeService;
import com.neu.fruit.utils.JWTUtil;
import com.neu.fruit.utils.ResultModel;
import com.neu.fruit.utils.StringUtil;
import com.neu.fruit.vo.TypeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/type")
public class TypeController {
@Autowired
private TypeService typeService;
@Value("${jwtKey}")
private String jwtKey;
@GetMapping
public ResultModel<List<TypeVO>> find(@RequestHeader("token")String token,TypeDTO typeDTO){
int shopId = Integer.parseInt(JWTUtil.getInfoFromToken(token,jwtKey));
typeDTO.setShopId(shopId);
return typeService.find(typeDTO);
}
@PostMapping
public ResultModel add(@RequestHeader("token")String token, TypeDTO typeDTO){
//需要从token中获取店铺的id
int shopId = Integer.parseInt(JWTUtil.getInfoFromToken(token,jwtKey));
if(StringUtil.isEmpty(typeDTO.getName())){
throw new ParamException("查询分类信息,参数错误");
}
typeDTO.setShopId(shopId);
return typeService.add(typeDTO);
}
@PutMapping("/{id}")
public ResultModel update(@RequestHeader("token")String token,@PathVariable("id")int id, TypeDTO typeDTO){
int shopId = Integer.parseInt(JWTUtil.getInfoFromToken(token,jwtKey));
if(StringUtil.isEmpty(typeDTO.getName())){
throw new ParamException("查询分类信息,参数错误");
}
typeDTO.setShopId(shopId);
return typeService.update(id,typeDTO);
}
@DeleteMapping("/{id}")
public ResultModel deleteById(@RequestHeader("token")String token,@PathVariable("id")int id){
int shopId = Integer.parseInt(JWTUtil.getInfoFromToken(token,jwtKey));
return typeService.deleteByIdAndShopId(id,shopId);
}
}
4.TypeService
package com.neu.fruit.service;
import com.neu.fruit.dto.TypeDTO;
import com.neu.fruit.utils.ResultModel;
import com.neu.fruit.vo.TypeVO;
import java.util.List;
public interface TypeService {
ResultModel<List<TypeVO>> find(TypeDTO typeDTO);
ResultModel add(TypeDTO typeDTO);
ResultModel update(int id, TypeDTO typeDTO);
ResultModel deleteByIdAndShopId(int id,int shopId);
}
5.TypeServiceImpl
package com.neu.fruit.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neu.fruit.dto.TypeDTO;
import com.neu.fruit.exception.BusException;
import com.neu.fruit.mapper.FruitMapper;
import com.neu.fruit.mapper.TypeMapper;
import com.neu.fruit.pojo.Type;
import com.neu.fruit.service.FruitService;
import com.neu.fruit.service.TypeService;
import com.neu.fruit.utils.ResultModel;
import com.neu.fruit.vo.TypeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class TypeServiceImpl implements TypeService {
@Autowired
TypeMapper typeMapper;
@Autowired
FruitService fruitService;
@Override
public ResultModel<List<TypeVO>> find(TypeDTO typeDTO) {
List<TypeVO> typeVOList = new ArrayList<>();
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("shop_id",typeDTO.getShopId());
List<Type> typeList = typeMapper.selectList(queryWrapper);
for(Type type : typeList){
TypeVO typeVO = new TypeVO();
typeVO.setId(type.getId());
typeVO.setName(type.getName());
typeVOList.add(typeVO);
}
return ResultModel.success("查询type成功",2,typeVOList);
}
@Override
public ResultModel add(TypeDTO typeDTO) {
Type type = new Type();
type.setName(typeDTO.getName());
type.setShopId(typeDTO.getShopId());
typeMapper.insert(type);
return ResultModel.success("添加成功");
}
@Override
public ResultModel update(int id, TypeDTO typeDTO) {
Type type = new Type();
type.setId(id);
type.setName(typeDTO.getName());
int count = typeMapper.updateById(type);
if(count>0){
return ResultModel.success("更新成功");
}else{
return ResultModel.failure("更新失败");
}
}
@Override
public ResultModel deleteByIdAndShopId(int id,int shopId) {
long count = fruitService.findCountByType(id);
if(count>0){
throw new BusException("当前分类下还有水果信息,请先删除水果后再删除分类");
}
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("id",id);
queryWrapper.eq("shop_id",shopId);
count = typeMapper.delete(queryWrapper); //shopId=1 typeId=100 [其他店铺的分类的id]
if(count>0){
return ResultModel.success("删除成功");
}else{
return ResultModel.failure("删除失败");
}
}
}
6.TypeMapper
package com.neu.fruit.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.neu.fruit.pojo.Banner;
import com.neu.fruit.pojo.Type;
public interface TypeMapper extends BaseMapper<Type> {
}
7.Type
package com.neu.fruit.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("t_type")
public class Type {
@TableId(type= IdType.AUTO)
private Integer id;
private String name;
private Integer shopId;
}
8.TypeVO
package com.neu.fruit.vo;
import lombok.Data;
@Data
public class TypeVO {
private Integer id;
private String name;
}
9.TypeDTO
package com.neu.fruit.dto;
import lombok.Data;
@Data
public class TypeDTO {
private String name;
private Integer shopId;
}
10.MyWenConfig
import com.example.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");
//addPathPatterns("") 代表当前拦截器要拦截怎样的URL请求 /**所有的请求都会被拦截
}
@Override
public void addCorsMappings(CorsRegistry registry) {
/*
* addMapping:配置可以被跨域的路径,可以任意配置,可以具体到直接请求路径。
* allowCredentials:是否开启Cookie
* allowedMethods:允许的请求方式,如:POST、GET、PUT、DELETE等。
* allowedOrigins:允许访问的url,可以固定单条或者多条内容
* allowedHeaders:允许的请求header,可以自定义设置任意请求头信息。
* maxAge:配置预检请求的有效时间
*/
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.maxAge(3600);
}
}
11.JWTUtil
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
public class JWTUtil {
public static void main(String[] args) {
String token = generateToken("zhangsan","1234",1800);
System.out.println(token);
token = getInfoFromToken(token,"1234");
System.out.println(token);
}
/**
* 生成token
* @param oriInfo
* @param key
* @param expire 过期时间,单位秒
* @return
* @throws Exception
*/
public static String generateToken(String oriInfo, String key, int expire) {
return Jwts.builder()
.claim("info",oriInfo)
.setExpiration(DateTime.now().plusSeconds(expire).toDate())
.signWith(SignatureAlgorithm.HS256,key)
.compact();
}
/**
* 从token中获取原始信息
* @param token
* @param key
* @return
* @throws Exception
*/
public static String getInfoFromToken(String token, String key) {
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(token);
Claims body = claimsJws.getBody();
return body.get("info")+"";
}
}
几乎跟老师给的代码一毛一样