泛微e9开发 编写前端请求后端接口方法以及编写后端接口

泛微e9开发 前端请求后端接口以及后端发布接口

前端请求后端接口

前端发起get请求

javascript 复制代码
fetch('/api/youpath', {
    method: 'GET',  // 默认 GET 方法,可以省略
    headers: {
        'Content-Type': 'application/json',  // 通常 GET 请求无需指定 body,Content-Type 不太重要
    },
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

前端发起post请求

javascript 复制代码
fetch('/api/youpath', {
    method: 'POST',  // 指定请求方法为 POST
    headers: {
        'Content-Type': 'application/json',  // 指定请求体格式为 JSON
    },
    body: JSON.stringify({  // 将 JavaScript 对象转为 JSON 字符串
        name: 'John Doe',
        age: 30
    }),
})
    .then(response => response.json())  // 解析 JSON 响应
    .then(data => console.log(data))  // 处理响应数据
    .catch(error => console.error('Error:', error));  // 错误处理

后端发布接口

首先这个后端接口的路径必须是在com/api这个目录的下面!!!

get类型的接口

java 复制代码
package com.api.customization.kq.web;

import com.alibaba.fastjson.JSON;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;

@Path("/customization/hrm/kq")
public class CardReplacementAction {

    @GET
    @Path("/card/getNumber")
    @Produces(MediaType.APPLICATION_JSON)
    public String intervene(@QueryParam("userid")int userid, @QueryParam("date")String date) {
        BaseBean baseBean = new BaseBean();
        HashMap<String, Object> result = new HashMap<>();
        // 接受参数调用方法
        RecordSet recordSet = new RecordSet();
        String sql = "select * from formtable_main_26 where sqr = "+userid+" and sqrq like '"+date.substring(0, 7)+"%'";
        recordSet.executeQuery(sql);
        try {
            result.put("number", recordSet.getArray().size());
        }catch (Exception e) {
            baseBean.writeLog("==lzl==error:"+e.getMessage());
        }
        return JSON.toJSONString(result);
    }
}

post 类型的接口

方法一:通过从request对象中读取参数值

java 复制代码
@POST
@Path("/getSomethingList")
@Produces(MediaType.TEXT_PLAIN)
public String List(@Context HttpServletRequest request, @Context HttpServletResponse response) {
	Map<String, Object> apidatas = new HashMap<String, Object>();
	String requestname = Util.null2String(request.getParameter("requestname"));
    String workflowid = Util.null2String(request.getParameter("workflowid"));
	apidatas.put("status", "1");
	return JSONObject.toJSONString(apidatas);
}

方法二:用类接收参数

java 复制代码
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

// 定义路径
@Path("/users")
public class UserResource {

    // 接收 POST 请求
    @POST
    @Consumes(MediaType.APPLICATION_JSON)  // 接收 JSON 数据
    @Produces(MediaType.APPLICATION_JSON)  // 返回 JSON 数据
    public Response createUser(User user) {
        // 这里,JAX-RS 自动将 JSON 请求体解析为 User 对象

        // 打印接收到的用户信息
        System.out.println("Received user: " + user.getName() + ", " + user.getAge());

        // 返回成功响应,并返回用户对象
        return Response.status(201)  // HTTP 201 状态码:资源已创建
                .entity(user)  // 将用户对象作为响应返回
                .build();
    }
}

注意事项

  • 首先接口必须发布在com.api包下
  • 前端访问后端接口路径的时候需要在你编写的接口路径前加上/api比如访问上面的post接口就得访问/api/users
相关推荐
在路上`几秒前
前端学习之后端小白java的一些理论知识(框架)
java·学习
成小白11 分钟前
前端实现两个页面之间的通讯
前端·javascript
练习时长两年半的Java练习生(升级中)18 分钟前
从0开始学习Java+AI知识点总结-18.web基础知识(Java操作数据库)
java·学习·web
啷咯哩咯啷21 分钟前
element-plus el-tree-v2大数据量勾选节点卡顿问题
前端·javascript·vue.js
计算机程序员小杨42 分钟前
计算机专业的你懂的:大数据毕设就选贵州茅台股票分析系统准没错|计算机毕业设计|数据可视化|数据分析
java·大数据
y1y1z1 小时前
EasyExcel篇
java·excel
DokiDoki之父1 小时前
多线程—飞机大战排行榜功能(2.0版本)
android·java·开发语言
高山上有一只小老虎1 小时前
走方格的方案数
java·算法
whatever who cares1 小时前
Java 中表示数据集的常用集合类
java·开发语言
EndingCoder1 小时前
测试 Next.js 应用:工具与策略
开发语言·前端·javascript·log4j·测试·全栈·next.js