0
点赞
收藏
分享

微信扫一扫

【Spring MVC】URI解析错误

yellowone 2022-08-12 阅读 75


报错

【Spring MVC】URI解析错误_html

源码

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JsonTest</title>
</head>
<body>
<form onsubmit="return false">
<input type="text" id="age" placeholder="请输入年龄~" />
<br />
<input type="text" id="id" placeholder="请输入编号~" />
<br />
<input type="text" id="name" placeholder="请输入姓名~" />
<br />
<button>提交</button>
</form>
<script>// 构建json
let json = {}
let list = []

document.getElementsByTagName("button")[0].onclick = function() {
// 获取input标签对应的值
let ageval = document.getElementById("age").value
let idval = document.getElementById("id").value
let nameval = document.getElementById("name").value

// 拼接json
json['age'] = 21
json['id'] = 22
json['name'] = 'zyx'

// jsonArray操作
let jsonObj = {
'name': nameval,
'age': parseInt(ageval),
'id': parseInt(idval)
}
list.push(jsonObj)
json['list'] = list

// 控制台打印输出
//console.log(json)

// JSON.stringify(json) 将json值转换为相应的JSON格式
requestOper2(JSON.stringify(json))
}

function requestOper2(json) {
/*
最通用的定义为:
XmlHttp是一套可以在Javascript、VbScript、Jscript等脚本语言中通过http协议传送或从接收XML及其他数据的一套API。
XmlHttp最大的用处是可以更新网页的部分内容而不需要刷新整个页面。
使用XMLHttpRequest (XHR)对象可以与服务器交互。
可以从URL获取数据,而无需让整个的页面刷新。
这使得Web页面可以只更新页面的局部,而不影响用户的操作
*/
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+,Firefox,Chorm,Opera,Safari
xmlhttp = new XMLHttpRequest();
} else {
// IE 5,IE 6
xmlhttp = new ActiveXObject("Microsoft XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
// 判断状态码
if(xmlhttp.readyState == 4 && xmlhttp.readyState == 200){
// 打印服务器返回的数据
console.log(xmlhttp.responseText);
}
}
// 发送get请求,路径,false
console.log(json)
let url = "<%=request.getContextPath()%>/Json/test2?json="+json
xmlhttp.open("GET", url ,false);
// 发送
xmlhttp.send()
}</script>
</body>
</html>

分析

​​http://localhost:8080/jyspringdemo/Json/test2?json={%22age%22:21,%22id%22:22,%22name%22:%22zyx%22,%22list%22:[{%22name%22:%221%22,%22age%22:1,%22id%22:1},{%22name%22:%221%22,%22age%22:1,%22id%22:1}]}​​

问题就出在这里的URI部分,这一步获取到的url会传到后端进一步处理。主要后端是获取uri中的json值,但是由于 %22被进行了编译,所以后端无法识别,需要我们进行处理。这里的做法是在前端获取到uri的时候就解码一下:

// 发送get请求,路径,false
console.log(json)
let url = "<%=request.getContextPath()%>/Json/test2?json="+json
//
xmlhttp.open("GET", encodeURI(url) ,false);
// 发送
xmlhttp.send()

  • encodeURI() 函数可把字符串作为 URI 进行编码。
  • 该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( ) 。
  • 该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/??&=+$,#

【Spring MVC】URI解析错误_xml_02


举报

相关推荐

0 条评论