基本代码(springboot+html+vue)
前端请求后台的login:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试contenttype</title> <link type="text/css" href="/test.css" rel="stylesheet"></link> <style> /*body{*/ /* background-color: #2b542c;*/ /*}*/ </style> </head> <body> <div id="app"> <input type="text" name="username" placeholder="请输入用户名" v-model="formData.username"/> <button @click='submit'>按钮</button> </div> <script src="/js/jquery.min.js"></script> <script src="/js/vue.js"></script> <script> var app = new Vue({ el:'#app', data:{ formData:{ username:'你好啊,vue', }, }, methods:{ submit() { alert(this.formData.username); var data = JSON.stringify(this.formData); console.log(data); $.ajax({ url: '/login', data: data, type: 'POST', contentType: 'application/json;charset=UTF-8',//后台用@requestBody获取数据并用对象接收 // contentType:'', dataType: 'JSON', // cache: false, processData: false,// 告诉jQuery不要去处理发送的数据 // contentType: false,// 告诉jQuery不要去设置Content-Type请求头 success: function (data) { console.log('返回值'+data) }, error: function (data) { console.log('请求失败'); } }) } } }); </script> </body> </html>
后台controller
package com.lizhi.login.controller; import com.lizhi.login.entity.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller //@ResponseBody public class LoginController { @RequestMapping({"","/"}) String welcome(){ return "test"; } @RequestMapping(value = "/login") public void login(@RequestBody User user){ System.out.println("用户名:"+user); // System.out.println("密码:"+psd); System.out.println("请求成功"); } }
情景一
前端:contentType: 'application/json;charset=UTF-8',
情景二
前端:contentType:'application/x-www-form-urlencoded',//模仿表单提交的形式