SSM整合项目(添加家居)

发布于:2024-03-11 ⋅ 阅读:(49) ⋅ 点赞:(0)

文章目录

1.需求分析

image-20240310143040581

2.设计结构

3.编写Service层

1.创建文件夹

image-20240310151514230

2.FurnService.java
package com.sun.furn.service;

import com.sun.furn.bean.Furn;

/**
 * @author 孙显圣
 * @version 1.0
 */
public interface FurnService {
    //增加一条记录
    public void save(Furn furn);
}

3.FurnServiceImpl.java
package com.sun.furn.service.impl;

import com.sun.furn.bean.Furn;
import com.sun.furn.dao.FurnMapper;
import com.sun.furn.service.FurnService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */
@Service
public class FurnServiceImpl implements FurnService {
    //注入一个FurnMapper的代理对象
    @Resource
    private FurnMapper furnMapper;
    @Override
    public void save(Furn furn) {
        furnMapper.insertSelective(furn);
    }
}

4.单元测试 FurnServiceTest.java
package com.sun.furn.service;


import com.sun.furn.bean.Furn;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.math.BigDecimal;

/**
 * @author 孙显圣
 * @version 1.0
 */
public class FurnServiceTest {
    //获取ioc容器
    private ApplicationContext ioc;
    //获取针对FurnService接口的代理对象
    private FurnService furnService;

    //初始化方法,在所有测试方法之前执行

    @Before
    public void init() {
        //读取sping配置文件,获取ioc容器,此时所有的单例bean已经被反射创建bean对象,依赖注入,初始化完毕
        ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取针对FurnService接口的代理对象
        furnService = ioc.getBean(FurnService.class);
    }

    @Test
    public void save() {
        Furn furn = new Furn(null, "桌子", "熊猫家居", new BigDecimal(12.3), 21, 11, "assets/images/product-image/14.jpg");
        furnService.save(furn);
    }


}

image-20240310151656078

5.指定默认图片位置
1.Furn.java 为imgPath设置默认值

image-20240310153533633

2.Furn.java 的全参构造器内判断imgPath是否为空

image-20240310153614795

4.返回json数据的通用类com/sun/furn/bean/Msg.java

package com.sun.furn.bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据到前端的通用类
 * @author 孙显圣
 * @version 1.0
 */
public class Msg {
    //状态码
    private int code;
    //成功或失败的信息
    private String msg;
    //要返回的信息(一个map就是一个json对象)
    private Map<String, Object> extend = new HashMap<>();

    //静态方法,获取成功的Msg对象
    public static Msg success() {
        Msg success = new Msg();
        //设置状态码和成功的信息
        success.setMsg("success");
        success.setCode(200);
        return success;
    }

    //静态方法,获取失败的Msg对象
    public static Msg fail() {
        Msg fail = new Msg();
        fail.setCode(400);
        fail.setMsg("fail");
        return fail;
    }

    //添加要返回的信息到Msg,并且返回这个对象
    public Msg add(String key, Object value) {
        extend.put(key, value);
        //在使用这个add之前一定是要有一个这个Msg类型的对象
        //当这个对象调用这个实例方法时,为这个对象的属性添加一个值,然后直接返回this就是当前对象
        return this;
    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getExtend() {
        return extend;
    }

    public void setExtend(Map<String, Object> extend) {
        this.extend = extend;
    }
}

5.编写Controller层

com/sun/furn/controller/FurnController.java
package com.sun.furn.controller;

import com.sun.furn.bean.Furn;
import com.sun.furn.bean.Msg;
import com.sun.furn.service.FurnService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @author 孙显圣
 * @version 1.0
 */

@Controller //单例bean注入容器
public class FurnController {
    @Resource //依赖注入,指向针对FurnService接口的代理对象
    private FurnService furnService;

    @ResponseBody //将结果转换成json字符串返回
    @PostMapping("/save")
    public Msg save(@RequestBody Furn furn) { //将接受到的json字符串转换成Furn对象
        furnService.save(furn);
        //如果没有报错,则返回成功的Msg对象
        return Msg.success();
    }


}

6.使用postman测试

1.后端引入处理json数据的依赖jackson

image-20240310162343190

2.pom.xml
  <!--  引入jackson,用于处理json数据-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.4</version>
    </dependency>
3.设置Content-Type

image-20240310163912085

4.进行测试

image-20240310164023346

7.点击新增,前端显示添加表单

1.HomeView.vue在div结束之前添加提示框显示表单
  • 注意:表单属性的名字必须与Furn的属性名一致
    <!--添加提示框-->
    <el-dialog title="提示" v-model="dialogVisible" width="30%">
      <el-form :model="form" label-width="120px">
        <!--注意:表单的属性名字必须与Furn的属性名一致-->
        <el-form-item label="家居名">
          <el-input v-model="form.name" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="厂商">
          <el-input v-model="form.maker" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="销量">
          <el-input v-model="form.sales" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="form.stock" style="width: 80%"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
2.为新增按钮绑定一个点击事件

image-20240310172833504

3.设置数据池
  • 注意:这里的表单对象不需要设置属性,因为在使用表单名.属性的时候就会自动设置属性值
  • 这里虽然是单向绑定,但是效果确跟双向绑定类似

image-20240310172911990

4.结果展示,点击新增

image-20240310173059067

5.解决bug,当点击取消之后再次点击新增数据仍然存在

image-20240310174148562

8.创建Axios Request对象发送请求给后台

1.前端项目安装Axios
1.在IDEA的命令行,的前端项目文件夹输入 npm i axios -S

image-20240310174909585

2.无法识别nodejs,直接使用命令行到前端项目文件夹执行命令

image-20240310183144839

2.创建工具文件封装axios request对象
1.创建一个js工具文件src/utils/request.js

image-20240310194207606

2.编写工具文件,封装axios request对象设置Content-Type为json
//引入axios
import axios from "axios";
//通过axios创建request对象
const request = axios.create({
    timeout: 5000 //设置超时时长为5秒
})
//创建request的拦截器,在请求之前做统一的处理,这里是设置Content-Type
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8'
    return config
}, error => {
    //如果出错则不继续执行
    return Promise.reject(error)
})

//导出
export default request

3.跨域问题
1.修改HomeView.vue在methods中编写save方法将表单数据提交到后端

image-20240310203040542

image-20240310201025214

2.出现跨域问题

image-20240310201115834

3.跨域问题分析
  • localhost:9999去请求localhost:8080
  • 是浏览器阻止了localhost:9999的请求而不是localhost:8080拒绝了请求
4.解决跨域问题
1.修改vue.config.js,设置代理,解决跨域问题
  • 这里的target就是要请求的后端网址的一部分,至少要包括http://localhost:8080
const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true
})
module.exports = {
    devServer: {
        port: 9999, //启动端口
        //设置代理,解决跨域问题
        proxy: {
            '/api': {
                target: 'http://localhost:8080/ssm', //这样设置/api就代表了http://localhost:8080/ssm
                changeOrigin: true, //是否设置同源,这样浏览器就允许跨域访问
                pathRewrite: { //路径重写
                    '/api': '' //选择忽略拦截器里面的单词
                }

            }
        }
    }
}

2.修改HomeView.vue

image-20240310203013218

5.成功返回数据

image-20240310203121149

9.添加家居注意事项

1.在使用postman测试的时候需要指定Content-Type否则会报错415
2.表单数据的名字需要与后端对象的属性名一致
3.点击弹出提示框时记得清除提示框的数据,防止第二次填写的时候数据仍然存在
4.如果需要将json请求自动封装到javabean中需要指定@RequestBody否则会报错500
5.如果后端需要返回json数据需要在方法上配置@ReponseBody否则会报错404
  • 因为如果不写这个注解,他会认为你返回的一个数据是要找一个页面

网站公告

今日签到

点亮在社区的每一天
去签到