Failed to bind request element:

本文详细解析了Spring框架中因URL参数类型不匹配导致的MethodArgumentTypeMismatchException异常,阐述了如何避免将字符串类型URL误识别为整型参数的问题,并提供了两种有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误的具体内容是:2018-12-03 12:40:06.850 [http-nio-80-exec-3] WARN  o.s.w.s.m.support.DefaultHandlerExceptionResolver - Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "orderBook"。

检查了半天,感觉自己程序上没写错,但是后来通过自己的检查发现了自己的错误!我这里的逻辑的是同一个带参的url去请求一个页面,然后在页面中有通过ajax提交数据。

错误代码:

@RequestMapping("/bookinfo/{id}")
	public String deGet(HttpServletRequest request,
			HttpServletResponse response, @PathVariable(name = "id") int id,
			Model model) throws ServletException, IOException {
 $.ajax({
    	   type:"post",
    	   contentType:"application/json",
    	   data:data,
           url:"/borrow/book",
		   dataType:"json",
           success: function (datas) {
      
        	 if(datas==1){
                 alert("请将书自己取出");
                 }
        	 else if(datas==2){
        		 alert("您最多借三本书");
        	 }
                 else{
                     var m=confirm("其他人已经借走,你要预定吗?");
                     if(m==true){
                         var a="[[${bookinfo1.id}]]";
                         var b="[[${bookinfo1.bookname}]]";
                         var c="[[${bookinfo1.book}]]";
                         var d=$("#time").val();

                         dldata={"time":d,"id":a,"openid":b,"book":c};
                         var data=JSON.stringify(dldata);

                         $.ajax({
                             url:"/orderBook",
                             type:"post",
                             data:data,
                             contentType:"application/json",
                             dataType:"json",
                             success:function(datas){
                                 /*执行的函数*/
                                ....

我这两次上传,第一个ajax上传的url并不会出错,但是第二个就会出错,原因是因为我的第一个映射是:/bookinfo/{id},而后面的都是没有/{id}的,也就是没有这个参数,程序会把我的url当成int类型的参数,而我的url是String类型的,因此就会出现这个错误。其实解决方法有两种,第一种是在/bookinfo/{id}的后面再加上一个/name,这个加上什么都行,这里只是个例子。

或者就是在我其他url后面加上带参数的url:如一下代码所示:

 $.ajax({
                             url:"/orderBook/1",
                             type:"post",
                             data:data,
                             contentType:"application/json",
                             dataType:"json",

虽然带上了一个参数,但是你在controller层可以不用传递过去的参数,之后就会发现,错误已经解决!。

:8081/#/user:1 Access to XMLHttpRequest at 'http://localhost:8080/user/list' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js:175 POST http://localhost:8080/user/list net::ERR_FAILED dispatchXhrRequest @ xhr.js:175 xhrAdapter @ xhr.js:12 dispatchRequest @ dispatchRequest.js:52 Promise.then request @ Axios.js:57 Axios.<computed> @ Axios.js:77 wrap @ bind.js:9 getTableData @ User.vue:141 mounted @ User.vue:225 invokeWithErrorHandling @ vue.esm.js:1872 callHook @ vue.esm.js:4244 insert @ vue.esm.js:3167 invokeWithErrorHandling @ vue.esm.js:1872 invoker @ vue.esm.js:2193 invokeInsertHook @ vue.esm.js:6401 patch @ vue.esm.js:6620 Vue._update @ vue.esm.js:3972 updateComponent @ vue.esm.js:4090 get @ vue.esm.js:4504 run @ vue.esm.js:4579 flushSchedulerQueue @ vue.esm.js:4335 eval @ vue.esm.js:1998 flushCallbacks @ vue.esm.js:1924 Promise.then timerFunc @ vue.esm.js:1951 nextTick @ vue.esm.js:2008 queueWatcher @ vue.esm.js:4427 update @ vue.esm.js:4569 notify @ vue.esm.js:739 reactiveSetter @ vue.esm.js:1064 proxySetter @ vue.esm.js:4653 handleItemClick @ element-ui.common.js:3358 invokeWithErrorHandling @ vue.esm.js:1872 Vue.$emit @ vue.esm.js:3912 dispatch @ emitter.js:29 handleClick @ element-ui.common.js:4090 invokeWithErrorHandling @ vue.esm.js:1872 invoker @ vue.esm.js:2197 original._wrapper @ vue.esm.js:7609 createError.js:15 Uncaught (in promise) Error: Network Error at createError (createError.js:15:1) at XMLHttpRequest.handleError (xhr.js:87:1)
05-14
Strophe = { /** Constants: XMPP Namespace Constants * Common namespace constants from the XMPP RFCs and XEPs. * * NS.HTTPBIND - HTTP BIND namespace from XEP 124. * NS.BOSH - BOSH namespace from XEP 206. * NS.CLIENT - Main XMPP client namespace. * NS.AUTH - Legacy authentication namespace. * NS.ROSTER - Roster operations namespace. * NS.PROFILE - Profile namespace. * NS.DISCO_INFO - Service discovery info namespace from XEP 30. * NS.DISCO_ITEMS - Service discovery items namespace from XEP 30. * NS.MUC - Multi-User Chat namespace from XEP 45. * NS.SASL - XMPP SASL namespace from RFC 3920. * NS.STREAM - XMPP Streams namespace from RFC 3920. * NS.BIND - XMPP Binding namespace from RFC 3920. * NS.SESSION - XMPP Session namespace from RFC 3920. */ NS: { HTTPBIND: "http://jabber.org/protocol/httpbind", BOSH: "urn:xmpp:xbosh", CLIENT: "jabber:client", AUTH: "jabber:iq:auth", ROSTER: "jabber:iq:roster", PROFILE: "jabber:iq:profile", DISCO_INFO: "http://jabber.org/protocol/disco#info", DISCO_ITEMS: "http://jabber.org/protocol/disco#items", MUC: "http://jabber.org/protocol/muc", SASL: "urn:ietf:params:xml:ns:xmpp-sasl", STREAM: "http://etherx.jabber.org/streams", BIND: "urn:ietf:params:xml:ns:xmpp-bind", SESSION: "urn:ietf:params:xml:ns:xmpp-session", VERSION: "jabber:iq:version" }, /** Constants: Connection Status Constants * Connection status constants for use by the connection handler * callback. * * Status.ERROR - An error has occurred * Status.CONNECTING - The connection is currently being made * Status.CONNFAIL - The connection attempt failed * Status.AUTHENTICATING - The connection is authenticating * Status.AUTHFAIL - The authentication attempt failed * Status.CONNECTED - The connection has succeeded * Status.DISCONNECTED - The connection has been terminated * Status.DISCONNECTING - The connection is currently being terminated */ Status: { ERROR: 0, CONNECTING: 1, CONNFAIL: 2, AUTHENTICATING: 3, AUTHFAIL: 4, CONNECTED: 5, DISCONNECTED: 6, DISCONNECTING: 7 }, /** Constants: Log Level Constants * Logging level indicators. * * LogLevel.DEBUG - Debug output * LogLevel.INFO - Informational output * LogLevel.WARN - Warnings * LogLevel.ERROR - Errors * LogLevel.FATAL - Fatal errors */ LogLevel: { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, FATAL: 4 }, /** PrivateConstants: DOM Element Type Constants * DOM element types. * * ElementType.NORMAL - Normal element. * ElementType.TEXT - Text data element. */ ElementType: { NORMAL: 1, TEXT: 3 }, /** PrivateConstants: Timeout Values * Timeout values for error states. These values are in seconds. * These should not be changed unless you know exactly what you are * doing. * * TIMEOUT - Time to wait for a request to return. This defaults to * 70 seconds. * SECONDARY_TIMEOUT - Time to wait for immediate request return. This * defaults to 7 seconds. */ TIMEOUT: 70, SECONDARY_TIMEOUT: 7, /** Function: forEachChild * Map a function over some or all child elements of a given element. * * This is a small convenience function for mapping a function over * some or all of the children of an element. If elemName is null, all * children will be passed to the function, otherwise only children * whose tag names match elemName will be passed. * * Parameters: * (XMLElement) elem - The element to operate on. * (String) elemName - The child element tag name filter. * (Function) func - The function to apply to each child. This * function should take a single argument, a DOM element. */ forEachChild: function (elem, elemName, func) { var i, childNode; for (i = 0; i < elem.childNodes.length; i++) { childNode = elem.childNodes[i]; if (childNode.nodeType == Strophe.ElementType.NORMAL && (!elemName || this.isTagEqual(childNode, elemName))) { func(childNode); } } }, /** Function: isTagEqual * Compare an element's tag name with a string. * * This function is case insensitive. * * Parameters: * (XMLElement) el - A DOM element. * (String) name - The element name. * * Returns: * true if the element's tag name matches _el_, and false * otherwise. */ isTagEqual: function (el, name) { return el.tagName.toLowerCase() == name.toLowerCase(); }, /** Function: xmlElement * Create an XML DOM element. * * This function creates an XML DOM element correctly across all * implementations. Specifically the Microsoft implementation of * document.createElement makes DOM elements with 43+ default attributes * unless elements are created with the ActiveX object Microsoft.XMLDOM. * * Most DOMs force element names to lowercase, so we use the * _realname attribute on the created element to store the case * sensitive name. This is required to generate proper XML for * things like vCard avatars (XEP 153). This attribute is stripped * out before being sent over the wire or serialized, but you may * notice it during debugging. * * Parameters: * (String) name - The name for the element. * (Array) attrs - An optional array of key/value pairs to use as * element attributes in the following format [['key1', 'value1'], * ['key2', 'value2']] * (String) text - The text child data for the element. * * Returns: * A new XML DOM element. */ xmlElement: function (name) { // FIXME: this should also support attrs argument in object notation if (!name) { return null; } var node = null; if (window.ActiveXObject) { node = new ActiveXObject("Microsoft.XMLDOM").createElement(name); } else { node = document.createElement(name); } // use node._realname to store the case-sensitive version of the tag // name, since some browsers will force tagnames to all lowercase. // this is needed for the <vCard/> tag in XMPP specifically. if (node.tagName != name) node.setAttribute("_realname", name); // FIXME: this should throw errors if args are the wrong type or // there are more than two optional args var a, i; for (a = 1; a < arguments.length; a++) { if (!arguments[a]) { continue; } if (typeof(arguments[a]) == "string" || typeof(arguments[a]) == "number") { node.appendChild(Strophe.xmlTextNode(arguments[a])); } else if (typeof(arguments[a]) == "object" && typeof(arguments[a]['sort']) == "function") { for (i = 0; i < arguments[a].length; i++) { if (typeof(arguments[a][i]) == "object" && typeof(arguments[a][i]['sort']) == "function") { node.setAttribute(arguments[a][i][0], arguments[a][i][1]); } } } } return node; },
最新发布
08-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值