springboot 使用 SprignSecurity 后无法 POST 提交数据

问题描述

在 Springboot 中使用 SpringSecurity 后会出现使用 POST 无法提交请求的问题,原因是因为 SpringSecurity 为了防止跨域请求伪造,于是拦截了 POST 请求,而使用 GET 请求则不会出现这种问题。于是百度了一下,总结出如下办法解决 POST 无法提交的问题

解决办法

1). 如果是使用表单提交,在表单中添加隐藏域即可。

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>  

2). 如果是使用Ajax提交。
html 页面

<head>
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    ...
</head>

ajax 的 js 中添加如下代码

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});

3). 直接关闭防跨域攻击功能。(该方法暴力不推荐使用)

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
                http.csrf().disable();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,使用 axios 将表单数据提交Spring Boot 后端的实现步骤如下: 1. 在前端,获取表单数据可以使用 jQuery 的 serialize 方法,将表单中的数据序列化为 URL 编码的字符串。 2. 使用 axios 发送 POST 请求到 Spring Boot 后端,将序列化后的表单数据作为请求体发送。 3. 在 Spring Boot 后端,定义一个 POST 接口,使用 @RequestBody 注解将请求体中的数据映射为 Java 对象。 下面是一个基本的示例代码: ```javascript // HTML 表单 <form id="my-form"> <input type="text" name="username" value="" /> <input type="password" name="password" value="" /> <button type="submit">Submit</button> </form> // JavaScript 代码 $('#my-form').on('submit', function(event) { event.preventDefault(); // 阻止表单默认提交行为 var formData = $(this).serialize(); // 序列化表单数据 axios.post('url/to/springboot/api', formData) .then(function(response) { console.log(response.data); }) .catch(function(error) { console.log(error); }); }); // Spring Boot 后端代码 @RestController @RequestMapping("/api") public class MyController { @PostMapping("/submit") public String handleSubmit(@RequestBody MyForm form) { // 处理表单数据,form 对象中包含表单中的数据 return "success"; } } // 表单数据的 Java 对象定义 public class MyForm { private String username; private String password; // getter 和 setter 方法省略 } ``` 其中,`url/to/springboot/api` 是 Spring Boot 后端接口的 URL 地址,需要替换为实际的地址。`MyForm` 类是表单数据的 Java 对象定义,可以根据表单的实际情况进行修改。在后端,使用 @RequestBody 注解将请求体中的数据映射为 Java 对象,可以方便地进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值