栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

创建REST服务,消费REST服务(含JS和JQ调用REST端点示例)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

创建REST服务,消费REST服务(含JS和JQ调用REST端点示例)

前言

  • 一、pandas是什么?
  • 二、使用步骤
    • 1.引入库
    • 2.读入数据
  • 总结

一、使用spring提供REST API 1. 项目准备
  • 创建springboot项目
  • 引入spring web、spring data-jpa等起步依赖
  • 配置web端口、数据库连接
2. 生成数据库用户表实体
package readinglist.entity;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "ATBL_USER_LV", schema = "PRODUCTION", catalog = "")
public class AtblUserLv {
    private long id;
    private String password;
    private String username;
    private Date addtime;

    @SequenceGenerator(name = "generator", sequenceName = "SEQ_A_TBL", allocationSize = 1)
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator")
    @Column(name = "ID", unique = true, nullable = false, scale = 0)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Basic
    @Column(name = "PASSWORD")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "USERNAME")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ADDTIME")
    public Date getAddtime() {
        return addtime;
    }

    public void setAddtime(Date addtime) {
        this.addtime = addtime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AtblUserLv that = (AtblUserLv) o;

        if (id != that.id) return false;
        if (password != null ? !password.equals(that.password) : that.password != null) return false;
        if (username != null ? !username.equals(that.username) : that.username != null) return false;
        if (addtime != null ? !addtime.equals(that.addtime) : that.addtime != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (password != null ? password.hashCode() : 0);
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (addtime != null ? addtime.hashCode() : 0);
        return result;
    }
}
3. 使用Spring MVC的控制器创建RESTful端点

创建RESTful控制器需要使用@RestController注解,此注解会告诉Spring,控制器中的所有处理器方法的返回值都要直接写入响应体中,而不是将值放到模型中并传递给一个视图以便于进行渲染。

package readinglist.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import readinglist.entity.AtblUserLv;
import readinglist.repository.UserRepository;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;


@RestController //注解为REST控制器类
@CrossOrigin(origins = "*") //允许跨域请求
@RequestMapping(path = "/jsondata")
public class JsonRestController {

    @Autowired  //自动装备DB数据层类
    private UserRepository userRepository;

    @GetMapping("/getjData")
    public String getjData(){
        String jsonStr = "{"id": 2, "title": "json title标题", "concf": {"width": 34,"height": 35}, "arrlist": ["JAVA", "JavaScript", "PHP"]}";
        //String jsonStr = "{"id": 2, "title": "json title标题", "arrlist": ["JAVA", "JavaScript", "PHP"]}";
        //String jsonStr="{"aaname": "兮动人","aaid":22,"sex": "男","xueli": "本科"}";
        return jsonStr;
    }

    
    @GetMapping("/getuserlist")
    public List getusers(){
        System.out.println("进入getuserlist请求...");
        PageRequest page=PageRequest.of(0,2, Sort.by("addtime").descending());
        return userRepository.findAll(page).getContent();
    }

    
    @GetMapping("/getuser/{id}")
    public AtblUserLv userById(@PathVariable("id") Long id){
        System.out.println("id===="+id);
        Optional optUser=userRepository.findById(id);
        if(optUser.isPresent()){
            return optUser.get();
        }
        return null;
    }

    
    @GetMapping("/findUser/{id}")
    public ResponseEntity userByIdEntity(@PathVariable("id") Long id){
        System.out.println("userByIdEntity--id:"+id);
        Optional optUser=userRepository.findById(id);
        if(optUser.isPresent()){
            return new ResponseEntity<>(optUser.get(), HttpStatus.OK);
        }
        return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
    }

    
    @PostMapping(path = "/addpostusr")
    @ResponseStatus(HttpStatus.CREATED)
    public AtblUserLv postAddUser(@RequestBody AtblUserLv atbluserlv,HttpServletRequest request) {
        System.out.println("进入方法:postAddUser---request.getMethod():"+request.getMethod());
        System.out.println("request.getQueryString():"+request.getQueryString());
        System.out.println("request.getRequestURI():"+request.getRequestURI());
        System.out.println("===---------"+atbluserlv.getUsername()+atbluserlv.getPassword());
        atbluserlv.setAddtime(new Date());
        return userRepository.save(atbluserlv);
    }
}
二、Spring 消费REST服务 API 1. 项目准备
  • 创建消费端springboot项目
  • 引入spring web等起步依赖
2. 创建消费端用户领域类
package com.sbootwo.resttemplate.entity;

import java.util.Date;

public class AtblUserLv {
    private long id;
    private String password;
    private String username;
    private Date addtime;


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getAddtime() {
        return addtime;
    }

    public void setAddtime(Date addtime) {
        this.addtime = addtime;
    }

}
3. 使用RestTemplate消费REST API

Spring 应用可以采用多种方式来消费 REST API,包括以下几种方式。

  • RestTemplate:Spring 核心框架提供的简单、同步 REST 客户端。
  • Traverson:Spring HATEOAS 提供的支持超链接、同步的 REST 客户端,其灵感来源于同名的 JavaScript 库。
  • WebClient:Spring 5 所引用的反应式、异步 REST 客户端。

本节主要讲解使用 RestTemplate 消费 REST 端点,创建 Rest 端点 API 消费类

package com.sbootwo.resttemplate;

import com.sbootwo.resttemplate.entity.AtblUserLv;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;


public class RestConsume {
    
    RestTemplate rest=new RestTemplate();

    
    public AtblUserLv getIdUserOne(String id){
        return rest.getForObject("http://localhost:8080/jsondata/getuser/{id}",AtblUserLv.class,id);
    }

    
    public AtblUserLv getIdUserTwo(String uid){
        Map mapurl=new HashMap<>();
        mapurl.put("id",uid);
        URI url= UriComponentsBuilder.fromHttpUrl("http://localhost:8080/jsondata/getuser/{id}").build(mapurl);
        return rest.getForObject(url,AtblUserLv.class);
    }

    
    public AtblUserLv getIdUserThree(String uid){
        ResponseEntity responseEntity= rest.getForEntity("http://localhost:8080/jsondata/getuser/{id}",AtblUserLv.class,uid);
        System.out.println("获得响应头信息:"+responseEntity.getHeaders().getDate());
        return responseEntity.getBody();
    }

    
    public AtblUserLv addAtblUserLvOne(AtblUserLv atblUserLv){
        return rest.postForObject("http://localhost:8080/jsondata/addpostusr",atblUserLv,AtblUserLv.class);
    }

    
    public AtblUserLv addAtblUserLvTwo(AtblUserLv atblUserLv){
        ResponseEntity responseEntity=rest.postForEntity("http://localhost:8080/jsondata/addpostusr",atblUserLv,AtblUserLv.class);
        System.out.println("获得响应头信息:"+responseEntity.getHeaders().getDate()+"--"+responseEntity.getHeaders().getLocation());
        return responseEntity.getBody();
    }

    public static void main(String[] args) {
        RestConsume restConsume=new RestConsume();

        //-------------GET资源获取信用户信息-------------
        AtblUserLv tuserone=restConsume.getIdUserOne("8");
        System.out.println("----"+tuserone.getId()+"||"+tuserone.getUsername()+"||"+tuserone.getPassword()+"||"+tuserone.getAddtime());

        AtblUserLv tusertwo=restConsume.getIdUserTwo("7");
        System.out.println("=========="+tusertwo.getId()+"||"+tusertwo.getUsername()+"||"+tusertwo.getPassword()+"||"+tusertwo.getAddtime());

        AtblUserLv tuserThree=restConsume.getIdUserThree("9");
        System.out.println("====---===---"+tuserThree.getId()+"||"+tuserThree.getUsername()+"||"+tuserThree.getPassword()+"||"+tuserThree.getAddtime());

        //-------------POST资源添加新用户-------------
        AtblUserLv userObj=new AtblUserLv();
        userObj.setUsername("nuser4");
        userObj.setPassword("new123");
        AtblUserLv newUserOne=restConsume.addAtblUserLvOne(userObj);
        System.out.println("打印出新增用户的ID值:"+newUserOne.getId());

        AtblUserLv userObj2=new AtblUserLv();
        userObj2.setUsername("nuser5");
        userObj2.setPassword("new123");
        AtblUserLv newUserTwo=restConsume.addAtblUserLvTwo(userObj2);
        System.out.println("打印出新增用户的ID值:"+newUserTwo.getId());
    }
}
三. 使用原生 javascript 和 jquery js库消费REST API 1. 使用原生 js 消费REST API



    
    Title
  






2. 使用jquery js库消费REST API



  
  Title
  
  









添加用户

用户名:

密    码:



总结

创建RESTful控制器需要使用@RestController注解,此注解会告诉Spring,控制器中的所有处理器方法的返回值都要直接写入响应体中,而不是将值放到模型中并传递给一个视图以便于进行渲染。@RestController注解相当于@ResponseBody + @Controller合在一起的作用,方法返回字符串值。

@Controller 这个注解可返回显示视图页面,将值放到模型中并传递给一个视图以便于进行渲染。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号