文章目录

  • html小Demo: js调用java后端提供的接口
    • html常用的一些标签(初级版)以及对html的一些理解的笔记
      • head常用标签
      • body常用标签
    • JavaScript
    • Java springboot
    • 代码
      • java后端:
      • 前端
        • test.js
        • test.html
    • 遇到的问题以及解决
      • 1. Cannot read property 'addEventListener' of null
      • 2. 跨域问题
        • 3.POST请求报“status 400 bad request”的问题
    • 最后放个效果图

html小Demo: js调用java后端提供的接口

  • 描述:springboot提供接口,ajax调用调用接口,html显示页面
  • 今晚困了,不知道写不写得完,有参的还没写,先放个未完成版的。
  • 2020/08/22 填上了上周的坑。使用原生ajax还是有些不太满意,使用了jQuery。只需在html中引入两个相应的js文件。那两个js文件的代码太长了,不能往博客上贴,我直接传GitHub了。于是干脆全部代码都扔GitHub算了。
  • WebDemo前后端代码

html常用的一些标签(初级版)以及对html的一些理解的笔记

  • 参考博客:

    html常用标签整理

  • <!doctype html>声明为html5文件,必须是html文档的第一行,在<html>标签之前;

  • <html>、</html>是文档开始和结束的标记,是HTML页面的根元素,在它们之间是文档的头部(head)和主体(body);

  • <head>、</head>定义HTML文档开头部分,内容不会在浏览器窗口显示,包含文档元(meta)数据,配置信息等,是给浏览器看的;

  • <title>、</title>定义了网页标题,在浏览器标题栏显示(修改一下title中的内容,然后看一下浏览器,你就会发现title是什么了);

    • 这个标签修改的是浏览器标题栏,就是地址栏上面那个。改了之后ctrl+s,标题栏会变
  • <body>、</body>之间的内容是可见的网页主体内容;

  • 注意:中文网页需要使用 <meta charset=“utf-8”> 声明编码,否则会出现乱码;有些浏览器是gbk,需手动设置为 <meta charset=“gbk”>;

head常用标签

  • 不是很懂,先放着吧。看着上面写的应该差不多了。

  • meta标签:(忽然看到这里有一个关于http头的说明,就是Header,这个在和后端交互中是用到的,先写下来吧)

    • <meta>元素可提供有关页面的元信息(meta-information),针对搜索引擎和更新频度的描述和关键词;
    • 标签位于文档的头部,不包含任何内容,提供的信息用户是看不见的;
    • meta标签组成:
      • http-equiv属性和name属性:
      • http-equiv属性:相当于http的文件头作用,向浏览器传回一些有用的信息,正确显示网页内容,与之对应的属性值content,content中的内容是各个参数的变量值;
      • 至于怎么用,后面用到再查,先知道在这配置就行了。
  • 对了,还有一个很重要的。html要定义相应的js,不然去哪儿调用接口呀。

    • 使用<script></script>标签

    • eg.

      <script type="text/javascript" src="test.js"></script>
      

body常用标签

  • 先记几个现在用到的

  • <b>加粗</b>
    <i>斜体</i>
    <u>下划线</u>
    <s>删除</s>
    
  • <p>段落标签</p> #独占一个段落
    
  • <h1>标题1</h1>
    <h2>标题2</h2>
    <h3>标题3</h3>
    <h4>标题4</h4>
    <h5>标题5</h5>
    <h6>标题6</h6>
    
  • <!--换行-->
    <br>
    
  • <!--水平线--><hr> #就是单独个一个水平线
    

JavaScript

  • 没什么好说的,放一个网易云视频的链接
    快速入门JavaScript原生Ajax

Java springboot

  • 也没什么好说的,提供了一个不需要参数的接口,http方法是GET;和一个需要参数的接口,http方法是POST
  • 放一个IDEA创建一个springboot项目的链接(用eclipse的自查教程):
    idea新建springboot项目
  • 随便找的一篇博客,如果要深入学习的话,自己查一下其他资料和视频。另外创建时可以用这个地址,会更快

代码

java后端:

jdk 1.8
IDEA
springboot 2.x
  • package com.chenxp.webdemo.Utils.JsonUtils
package com.chenxp.webdemo.Utils;import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;import java.util.List;/*** @Description:* @author: chenxp* @date: 2020/8/17 14:29* json工具类*/
public class JsonUtils {// 定义jackson对象private static final ObjectMapper MAPPER = new ObjectMapper();/*** 响应业务状态*  200:表示成功*  400:表示错误,错误信息在msg字段中*  501:bean验证错误,不管多少个错误都以map形式返回*  502:拦截器拦截到用户token出错*  555:异常抛出信息*/private Integer status;// 响应消息private String msg;// 响应中的数据private Object data;public static JsonUtils build(Integer status, String msg, Object data) {return new JsonUtils(status, msg, data);}public static JsonUtils ok(Object data) {return new JsonUtils(data);}public static JsonUtils ok() {return new JsonUtils(null);}public static JsonUtils errorMsg(String msg) {return new JsonUtils(400, msg, null);}public static JsonUtils errorMap(Object data) {return new JsonUtils(501, "error", data);}public static JsonUtils errorTokenMsg(String msg) {return new JsonUtils(502, msg, null);}public static JsonUtils errorException(String msg) {return new JsonUtils(555, msg, null);}public JsonUtils() {}public JsonUtils(Integer status, String msg, Object data) {this.status = status;this.msg = msg;this.data = data;}public JsonUtils(Object data) {this.status = 200;this.msg = "OK";this.data = data;}/*** @Author chenxp* @Description 将json结果集转化为JsonUtils对象*                需要转换的对象是一个类* @Date 14:51 2020/8/17* @Param* @return*/public static JsonUtils formatToPojo(String jsonData, Class<?> clazz) {try {if (clazz == null) {return MAPPER.readValue(jsonData, JsonUtils.class);}JsonNode jsonNode = MAPPER.readTree(jsonData);JsonNode data = jsonNode.get("data");Object obj = null;if (clazz != null) {if (data.isObject()) {obj = MAPPER.readValue(data.traverse(), clazz);} else if (data.isTextual()) {obj = MAPPER.readValue(data.asText(), clazz);}}return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);} catch (Exception e) {return null;}}/*** @Author chenxp* @Description 没有object对象的转化* @Date 14:52 2020/8/17* @Param* @return*/public static JsonUtils format(String json) {try {return MAPPER.readValue(json, JsonUtils.class);} catch (Exception e) {e.printStackTrace();}return null;}/*** @Author chenxp* @Description //Object是集合转化*              需要转换的对象是一个list* @Date 14:53 2020/8/17* @Param* @return**/public static JsonUtils formatToList(String jsonData, Class<?> clazz) {try {JsonNode jsonNode = MAPPER.readTree(jsonData);JsonNode data = jsonNode.get("data");Object obj = null;if (data.isArray() && data.size() > 0) {obj = MAPPER.readValue(data.traverse(),MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));}return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);} catch (Exception e) {return null;}}public Boolean isOK() {return this.status == 200;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}}
  • package com.chenxp.webdemo.Utils.WebAppConfigurer ;
package com.chenxp.webdemo.Utils;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*** @Description:* @author: chenxp* @date: 2020/8/16 19:02解决跨域问题 配置类*/
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS").maxAge(3600);}
}
  • package com.chenxp.webdemo.Utils.SwaggerApp;
package com.chenxp.webdemo.Utils;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;/*** @Description:* @author: chenxp* @date: 2020/8/14 17:25*/
@Configuration
@EnableSwagger2
public class SwaggerApp {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()//为当前包路径.apis(RequestHandlerSelectors.basePackage("com.chenxp.webdemo.Controller")).paths(PathSelectors.any()).build();
//        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();}//构建 api文档的详细信息函数,注意这里的注解引用的是哪个private ApiInfo apiInfo() {return new ApiInfoBuilder()//页面标题.title("Spring Boot 使用 Swagger2 构建RESTful API")//创建人.contact(new Contact("chenxp", "https://chenxp38.github.io/", ""))//版本号.version("1.0")//描述.description("API 描述").build();}
}
  • package com.chenxp.webdemo.pojo.User;
package com.chenxp.webdemo.pojo;import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;/*** @Description:* @author: chenxp* @date: 2020/8/17 17:04*/
public class User {private String uid;private String openid;@JsonInclude(JsonInclude.Include.NON_NULL)private String name;/*** @JsonIgnore在post返回user时,忽略password的属性*/@JsonIgnoreprivate String password;private Integer balance;@JsonInclude(JsonInclude.Include.NON_NULL)private String sex;private String phone;//@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a", locale="zh", timezone="GMT+8")//private Date birthday;public String getUid() {return uid;}public void setUid(String uid) {this.uid = uid;}public String getOpenid() {return openid;}public void setOpenid(String openid) {this.openid = openid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getBalance() {return balance;}public String getSex() {return sex;}public void setBalance(Integer balance) {this.balance = balance;}public void setSex(String sex) {this.sex = sex;}public void setPhone(String phone) {this.phone = phone;}public String getPhone() {return phone;}}
  • package com.chenxp.webdemo.Controller.HelloController;
package com.chenxp.webdemo.Controller;import com.chenxp.webdemo.Utils.JsonUtils;
import com.chenxp.webdemo.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;/*** @Description:* @author: chenxp* @date: 2020/8/1416:54*/
@Api(value = "测试返回数据")
@RestController
@RequestMapping("/value")
public class HelloController {@ApiOperation("获取测试返回String类型数据")@GetMapping("/string")public JsonUtils getHello() {int count = 0;System.out.println("count: " + count++);return JsonUtils.ok("HelloWorld");}@ApiOperation("测试有参数的接口swagger")@PostMapping("/sum")public JsonUtils getSum(@ApiParam @RequestParam(value = "integer1") int integer1,@ApiParam @RequestParam(value = "integer2") int integer2) {return JsonUtils.ok(integer1 + integer2);}@ApiOperation("测试有参数的接口2-swagger")@PostMapping("/object")public JsonUtils get(@ApiParam @RequestBody User user) {System.out.println("hhh");return JsonUtils.ok(user);}}
  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.chenxp</groupId><artifactId>webdemo</artifactId><version>1.0.0-SNAPSHOT</version><name>webdemo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.0.RELEASE</spring-boot.version></properties><dependencies><!-- swagger --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.5.0</version></dependency><!-- swagger-ui --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.5.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.0.RELEASE</version><configuration><mainClass>com.chenxp.webdemo.WebdemoApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build></project>

前端

  • 只写了html和js,没有写css
test.js

// //import是ES6的功能,Node.js尚未完全支持它,您应该使用require
// const express = require('express')
// //var express = express('./express.js')
// var app = express()
// //设置跨域请求
// app.all('*', function (req, res, next) {//     res.header("Access-Control-Allow-Origin", "*");
//     res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
//     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//     res.header("X-Powered-By", ' 3.2.1')
//     res.header("Content-Type", "application/json;charset=utf-8");
//     next();
//   });
/*** window.onload = function() {}是页面的加载函数*
*/
window.onload = function() {var head1 = document.getElementById('head1')var content1 = document.getElementById('content1')var title = document.getElementById('title')head1.innerText = "text1"content1.innerText = "text2"// title.innerText = "text_title"// alert("js已生效")function createXHR() {if (typeof XMLHttpRequest != 'undefined') {return new XMLHttpRequest();} else if (typeof ActiveXObject != 'undefined') {var version = ['MSXML2.XMLHttp.6.0','MSXML2.XMLHttp.3.0','MSXML2.XMLHttp'];for (var i = 0; version.length; i++) {try {return new ActiveXObject(version[i]);} catch (e) {throw new Error();}}} else{throw new Error('系统或浏览器不支持XHR对象');}}//Get
document.getElementById('button1').addEventListener('click', loadText)function loadText() {var xhr = new createXHR();xhr.onreadystatechange = function () {if(xhr.readyState == 4){if(xhr.status >= 200 && xhr.status < 304 || xhr.status == 304){console.log(JSON.parse(xhr.responseText));}}}xhr.open('get', 'http://localhost:8080/value/string');xhr.send(null);
}// 有参1
document.getElementById('button2').addEventListener('click', loadSum)
function loadSum() {var params = {"integer1": 4,"integer2": 5,}$.ajax({type : 'POST',url : 'http://localhost:8080/value/sum',contentType : "application/x-www-form-urlencoded",data : params,dataType : 'JSON',success : function(data, status) {var rstate = data.result;alert(data.data)if (rstate == "0") {if (rstate == "0") {alert('接口调用成功!');} else {alert('接口调用失败!');}}},error : function(data, status, e) {alert('接口调用错误!');}});
}// 有参2
document.getElementById('button3').addEventListener('click', loadUser)
function loadUser() {var params = {"uid":"16340000","opid":"openid","name":"xiaoming","password": "password","balance":0,"sex": "man","phone": "12315"}$.ajax({type : 'POST',url : 'http://localhost:8080/value/object',contentType : "application/json",data : JSON.stringify(params),dataType : 'JSON',success : function(data, status) {var rstate = data.result;alert(data.data.uid)if (rstate == "0") {if (rstate == "0") {alert('接口调用成功!');} else {alert('接口调用失败!');}}},error : function(data, status, e) {alert('接口调用错误!');}});
}}
test.html
<!DOCTYPE html>
<!--lang表示语言,en表示页面以英文为主,zh-CN表示以中文为主-->
<html lang="zh-CN">
<head><!--<head></head>定义HTML文档开头部分,内容不会在浏览器窗口显示,包含文档元(meta)数据,配置信息等,是给浏览器看的--><!--中文网页需要使用 <meta charset="utf-8"> 声明编码,否则会出现乱码;有些浏览器是gbk,需手动设置为 <meta charset="gbk">--><meta charset="UTF-8"><!--meta标签组成:--><!--http-equiv属性:相当于http的文件头作用,向浏览器传回一些有用的信息,正确显示网页内容,与之对应的属性值content,content中的内容是各个参数的变量值--><!--name属性:主要用于描述网页,与之对应的属性值为content,content中的内容主要是便于搜索引擎查找信息和分类信息用的--><meta name="viewport" content="width=device-width, initial-scale=1.0"><title id="title">Html Learning</title><script type="text/javascript" src="../js/test.js"></script><script type="text/javascript" src="../js/jquery.min.js"></script><script type="text/javascript" src="../js/jquery.easyui.min.js"></script>
</head>
<body><div id="div1"><h1 id="head1"></h1><br><hr><p id="content1"></p><hr><button id="button1">无参</button><button id="button2">有参1</button><button id="button3">有参2</button></div>
</body>
</html>

遇到的问题以及解决

1. Cannot read property ‘addEventListener’ of null

解决方案:Cannot read property ‘addEventListener’ of null

2. 跨域问题

  • 第一个博客是我解决了这个问题所用的方法,跨域问题是安全问题,建议在后端解决。至于前端能不能处理,我不知道,我查了两天了,太菜了,也没能在前端解决,早知道何必钻牛角尖搞什么前端解决,后端解决分分钟。其他后端比如python什么的,也是后端解决,自行寻找教程。
  • 第二个是关于跨域问题的一些介绍
    前后端分离项目 遇到请求跨域问题
    前端常见跨域解决方案(全)
3.POST请求报“status 400 bad request”的问题
  • 原因1: 参数格式不对(有参2调用),需要调用JSON.stringify(params)。

    • 解决方法1:data传的数据需要JSON化处理,使用JSON.stringify(params)
  • 原因2: contentType不对(有参1调用),需要注意自己对应的是哪个contentType
    • 解决方法2:后端是@RequestBody这种的,一般是要"application/json"。若是@RequestParam这种的,一般是要"application/x-www-form-urlencoded"

最后放个效果图

  • 三个接口的调用都是 200的状态码

html小Demo: js调用java后端提供的接口相关推荐

  1. ajax调用java程序,从微信小程序到鸿蒙JS开发-JS调用Java

    除轻量级智能穿戴设备,现鸿蒙支持的手机.汽车.TV.手表.平板等属于富鸿蒙,在JS语言的项目中也有Java模块,并提供了JS跨语言调用Java方法的技术.现需要实现查看商品评论时,统计出长评.中评和短 ...

  2. Java调用JS,JS调用JAVA

    JAVA 调用 JS //Java端 //带参数的函数调用 final String exes = "cc.Global.setEcADVal('"+ var1 + "' ...

  3. JavaFX下的WebView中js调用java注入方法提示undefined?

    关键词: java注入无效 js无法调用java方法 java上下文注入未生效 背景: 官方提供的demo是直接new JavaApp(),但实际使用不行,需要刷新页面后才生效 解决方案: 主要修改的 ...

  4. js调用java代码返回解决方案

    版权声明:本文为楼主原创文章,未经楼主允许不得转载,如要转载请注明来源. 今天封装一个加密标签,遇到一个问题,我需要对页面上的数据调用java后台代码进行解密,而标签里只能通过js获取到数据,所以就遇 ...

  5. rn在java中什么意思_[React Native Android 安利系列]RN中使用js调用java代码

    欢迎大家收看react-native-android系列教程,跟着本系列教程学习,可以熟练掌握react-native-android的开发,你值得拥有: 书接上节,我们上节说道,如何控制原生andr ...

  6. 如何实现js调用java函数

    思路 1.java端建立servlet服务,js通过ajax等方式调用servlet 2.可以通过dwr等第三方方式集成,然后调用java方法 3.用jsp,使用<%%>的方式进行脚本执行 ...

  7. java后端请求第三方接口并处理HttpEntity类转换成实体类对象

      最近在写使用java后端去请求第三方接口的代码,给大家分享关于HttpEntity类的处理方式,而处理请求是需要根据第三方的要求来处理的,所以这里着重展示HttpEntity的处理.   在开始代 ...

  8. DWR框架--让前端JS代码调用JAVA后端的方法

    目录 1.DWR框架简介 2.使用步骤 2.1.pom.xml导入包 2.2.配置web.xml文件 2.2.1.先了解dwr的jar包(不同版本不一样,需注意) 2.2.2.在web.xml中增加d ...

  9. jsencrypt.js加密java后端解密

    文章目录 1.什么是RSA? 2.RSA算法 2.1 生成公钥和私钥 2.2 使用公钥加密信息 2.3 使用私钥解密信息 4.RSA的应用:数字签名 5.RSA的安全性 6.为什么要写这文章? 7.前 ...

最新文章

  1. easyui table 数据表筛选条件
  2. 进程(process)和线程(thread)
  3. 闽江学院2015-2016学年下学期《软件测试》课程-第三次博客作业
  4. SAP OData编程指南
  5. Java 异常处理机制
  6. 前端学习(177):定义列表
  7. Apache 虚拟主机的配置[Ubuntu]
  8. 关于管理,这5大误区你越早知道越好
  9. 招兵买马,亚马逊再次补强人工智能
  10. iOS开发 IAP苹果内购
  11. Python 定义源码编码 (Source Encoding)
  12. RHCA红帽认证架构师考试分享
  13. 《卓有成效的管理者》读书笔记
  14. AndroidSDK和ADT下载地址
  15. PyTorch的参数固定以及detach clone
  16. debian 7 安装 rz sz lrzsz
  17. C语言之“输出100~200之间的素数”
  18. pygame外星人入侵
  19. 收集的JS常用正则表达式等
  20. 【测试用例练习】八、淘宝网站测试用例

热门文章

  1. 股市精忠社杨忠国在线体验:华为“全家桶”补全
  2. 安徽省宣城市住房公积金管理中心的数据安全建设实践
  3. DFS模板 SDNU 1015
  4. exynos4412启动流程
  5. Java面试之画出HashMap结构图,并说说HashMap和HashTable的区别
  6. 【C语言】函数指针、函数指针数组、函数指针数组的指针
  7. 可禁用计算机服务,台式电脑哪些服务不能禁用?或者哪些服务必须禁用?
  8. 从0-1做产品快速启动,大型干货案例分享
  9. Javaweb--Filter过滤器的基本使用
  10. 你可以提要求,别人也可以拒绝