将数据从ajax发送到Spring控制器:所需的字符串参数不存在。

huangapple go评论73阅读模式
英文:

sending data from ajax to spring controller: Required String parameter is not present

问题

我知道关于这个错误信息已经有很多问题了,但是没有什么能帮助我解决问题。

我正在尝试通过包含电子邮件、名字和姓氏以及每个条目的复选框的表格来激活用户帐户。
首先,您勾选要解锁的用户的复选框,然后按下一个按钮发送请求,控制器将只是将所选用户的“已激活”状态从0更改为1。

我有一个HTML、一个JavaScript和一个Java控制器文件。
请注意,我目前正在本地主机上尝试这个,并且已经通过在命令提示符下启动Chrome来关闭了Google Chrome的跨域访问,命令为chrome.exe --disable-web-security --allow-file-access-from-files

我想通过MainController.java中的电子邮件地址来解锁用户,该文件目前只执行sysout,因为迄今为止,由于错误,我甚至还没有进入该方法。

我已经尝试将@RequestParam更改为@RequestBody,但它只是给我一个所需的请求体缺失的错误。

所以我猜主要问题是我从表格中获取的电子邮件地址没有传递给控制器,但是我该如何正确地做呢?

表格的样子如下:
表格的屏幕截图

unlock.html

<div id="background">
  <div id="scroll-horizontal">
    <form id="table-form" method="POST" action="http://localhost:8080/mitglied/unlockUpdate">
      <table id="table">
        <tr>
          <th>E-Mail</th>
          <th>Vorname</th>
          <th>Nachname</th>
          <th><input id="unlock-all" type="checkbox"></th>
        </tr>
       </table>
       <input id="unlock-btn" type="submit" value="Freischalten"></input>
      </form>
    </div>
</div>

<script src="../static/js/unlock.js"></script>

JavaScript文件unlock.js

jQuery(document).ready(function() {

    $.getJSON("http://localhost:8080/mitglied/unlock", function(data) {
        var table_data = "";
        $.each(data, function(key, value) {
            table_data += "<tr>";
            table_data += "<td>" + value.email + "</td>";
            table_data += "<td>" + value.vorname + "</td>";
            table_data += "<td>" + value.nachname + "</td>";
            table_data += "<td class="unlock-checkbox" style="text-align:center"><input type="checkbox"></input></td>";
            table_data += "</tr>";
        });

        $("#table").append(table_data);
    });

    jQuery('#table-form').submit(function() {
        var rows = document.getElementsByTagName("tr");

        for (var i = 1; i < rows.length; i++) {
            var cols = rows[i].getElementsByTagName("td");
            var checkbox = cols[3].getElementsByTagName("input")[0];

            if (checkbox.checked) {
                var email = cols[0].innerHTML;

                $.ajax({
                    url: $(this).attr('action'),
                    method: 'POST',
                    data: { email: email },

                    success: function(data) {
                        console.log("success, email: " + email);
                        alert("success");
                    },
                    error: function() {
                        alert("error");
                    }
                });
            }
            console.log(checkbox.checked);
        }
    });
});

还有MainController.java

@CrossOrigin
@Controller
@RequestMapping(path="/mitglied")
public class MainController {
    @Autowired
    private MitgliederRepository mitgliedRepository;

    @PostMapping(path="/unlockUpdate")
    public @ResponseBody void unlockSelectedUsers(@RequestParam String email) {
        System.out.println(email);
    }
}

完整的错误消息(在localhost:8080/mitglied/unlockUpdates)是:

Whitelabel错误页面
该应用程序没有显式映射到/error,因此您正在看到它作为回退。

Fri Apr 10 13:43:42 CEST 2020
发生了意外错误(类型=错误请求,状态=400)。
所需的String参数'email'不存在

英文:

I know there are already a lot questions about this error message, but nothing helped me to fix my problem.

I'm trying to activate a User account through a table which contains the email, first and last name and a checkbox for each entry.
First you check the checkboxes for which user(s) you want to unlock and then you press a button to send your request, the Controller would then just change the "activated" status from the selected user(s) from 0 for deactivated to 1 for activated.

I have a HTML, a JavaScript and a Java Controller file.
Note that I'm currently trying this on localhost and have turned of google chromes cross origin by launching Chrome per cmd with chrome.exe --disable-web-security --allow-file-access-from-files

I want to unlock the user by their email adress in the MainController.java which currently only does a sysout because so far I don't even get to that method because of the error.

I already tried changing the @RequestParam to @RequestBody but it just gives me the error Required request body is missing.

So I quess the main problem is that the email adress I'm getting from the table is not passed on to the Controller, but how do I do that correctly?

what the table looks like:
screenshot of the table

the unlock.html

&lt;div id=&quot;background&quot;&gt;
&lt;div id=&quot;scroll-horizontal&quot;&gt;
&lt;form id=&quot;table-form&quot; method=&quot;POST&quot; action=&quot;http://localhost:8080/mitglied/unlockUpdate&quot;&gt;
&lt;table id=&quot;table&quot;&gt;
&lt;tr&gt;
&lt;th&gt;E-Mail&lt;/th&gt;
&lt;th&gt;Vorname&lt;/th&gt;
&lt;th&gt;Nachname&lt;/th&gt;
&lt;th&gt;&lt;input id=&quot;unlock-all&quot; type=&quot;checkbox&quot;&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;input id=&quot;unlock-btn&quot; type=&quot;submit&quot; value=&quot;Freischalten&quot;&gt;&lt;/input&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;../static/js/unlock.js &quot;&gt;&lt;/script&gt;

the JavaScript file unlock.js

jQuery(document).ready(function() {
$.getJSON(&quot;http://localhost:8080/mitglied/unlock&quot;, function(data) {
var table_data = &quot;&quot;;
$.each(data, function(key, value) {
table_data += &quot;&lt;tr&gt;&quot;;
table_data += &quot;&lt;td&gt;&quot; + value.email + &quot;&lt;/td&gt;&quot;;
table_data += &quot;&lt;td&gt;&quot; + value.vorname + &quot;&lt;/td&gt;&quot;;
table_data += &quot;&lt;td&gt;&quot; + value.nachname + &quot;&lt;/td&gt;&quot;;
table_data += &quot;&lt;td class=&quot; + &quot;unlock-checkbox&quot; + &quot; style=&quot; + &quot;text-align:center&quot; + &quot;&gt;&lt;input type=&quot; + &quot;checkbox&quot; + &quot;&gt;&lt;/input&gt;&lt;/td&gt;&quot;;
table_data += &quot;&lt;/tr&gt;&quot;;
});
$(&quot;#table&quot;).append(table_data);
});
jQuery(&#39;#table-form&#39;).submit(function() {
var rows = document.getElementsByTagName(&quot;tr&quot;);
for (var i = 1; i &lt; rows.length; i++) {
var cols = rows[i].getElementsByTagName(&quot;td&quot;);
var checkbox = cols[3].getElementsByTagName(&quot;input&quot;)[0];
if (checkbox.checked) {
var email = cols[0].innerHTML;
$.ajax({
url: $(this).attr(&#39;action&#39;),
method: &#39;POST&#39;,
data: { email: email },
success: function(data) {
console.log(&quot;success, email: &quot; + email);
alert(&quot;success&quot;);
},
error: function() {
alert(&quot;error&quot;);
}
});
}
console.log(checkbox.checked);
}
});
});

and the MainController.java

@Controller
@RequestMapping(path=&quot;/mitglied&quot;) public class MainController {
@Autowired
private MitgliederRepository mitgliedRepository;
@PostMapping(path=&quot;/unlockUpdate&quot;)
public @ResponseBody void unlockSelectedUsers(@RequestParam String email) {
System.out.println(email);
}

the complete error message (on localhost:8080/mitglied/unlockUpdates) is:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Apr 10 13:43:42 CEST 2020
There was an unexpected error (type=Bad Request, status=400).
Required String parameter 'email' is not present

答案1

得分: 0

以下是已翻译的内容:

unlock.html

<div id="background">
    <div id="frame">
        <h1 id="table-title">Freischaltung</h1>
        <div id="scroll">
            <table id="table">
                <thead>
                    <tr>
                        <th>E-Mail</th>
                        <th>Vorname</th>
                        <th>Nachname</th>
                        <th><input id="unlock-all" type="checkbox"></th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <div id="btn-container">
            <button id="unlock-btn" onclick="submit()">Freischalten</button>
        </div>
    </div>
</div>
<script src="../static/js/unlock.js"></script>

unlock.js

jQuery(document).ready(function() {
    updateTable();
});

function updateTable() {
    $.getJSON("http://localhost:8080/mitglied/unlock", function(data) {
        var table_data = "";
        $.each(data, function(key, value) {
            table_data += "<tr>";
            table_data += "<td>" + value.email + "</td>";
            table_data += "<td>" + value.vorname + "</td>";
            table_data += "<td>" + value.nachname + "</td>";
            table_data += "<td class=" + "unlock-checkbox" + "><input type=" + "checkbox" + "></input></td>";
            table_data += "</tr>";
        });
        $("#table").append(table_data);
    });
}

function submit() {
    var rows = document.getElementsByTagName("tr");

    //get the checked value for each table row
    for (var i = 1; i < rows.length; i++) {
        var cols = rows[i].getElementsByTagName("td");
        var checkbox = cols[3].getElementsByTagName("input")[0];

        if (checkbox.checked) {
            var email = cols[0].innerHTML;

            $.ajax({
                type: 'POST',
                url: 'http://localhost:8080/mitglied/unlockUpdate',
                data: { 'email': email },
                success: function(msg) {
                    alert("success");
                    window.location.reload();
                }
            });
        }
    }
}

MainController.java

@Controller
@RequestMapping(path="/mitglied")
public class MainController {
    @Autowired
    private MitgliederRepository mitgliedRepository;

    @RequestMapping(path="/unlockUpdate", method = RequestMethod.POST)
    public @ResponseBody void unlockSelectedUsers(@RequestParam (required=false) String email) {
        Iterable<Mitglied> mitglieder = mitgliedRepository.findAll();
        List<Mitglied> mitgliederListe = new ArrayList();
        mitglieder.iterator().forEachRemaining(mitgliederListe::add);

        for (Mitglied m : mitgliederListe) {
            if (m.getEmail().equals(email)) {
                m.setFreigeschaltet(true);
                mitgliedRepository.save(m);
                break;
            }
        }
        System.out.println(email);
    }
}
英文:

After trying a lot of stuff this is the solution I landed on and works for me

Note that the divs changed and it's no longer a form, the action is now handled via an onclick function. And I already styled it so divs are different now.

the unlock.html

&lt;div id=&quot;background&quot;&gt;
&lt;div id=&quot;frame&quot;&gt;
&lt;h1 id=&quot;table-title&quot;&gt;Freischaltung&lt;/h1&gt;
&lt;div id=&quot;scroll&quot;&gt;
&lt;table id=&quot;table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;E-Mail&lt;/th&gt;
&lt;th&gt;Vorname&lt;/th&gt;
&lt;th&gt;Nachname&lt;/th&gt;
&lt;th&gt;&lt;input id=&quot;unlock-all&quot; type=&quot;checkbox&quot;&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;div id=&quot;btn-container&quot;&gt;
&lt;button id=&quot;unlock-btn&quot; onclick=&quot;submit()&quot;&gt;Freischalten&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;../static/js/unlock.js &quot;&gt;&lt;/script&gt;

the JavaScript file unlock.js

jQuery(document).ready(function() {
updateTable();
});
function updateTable() {
$.getJSON(&quot;http://localhost:8080/mitglied/unlock&quot;, function(data) {
var table_data = &quot;&quot;;
$.each(data, function(key, value) {
table_data += &quot;&lt;tr&gt;&quot;;
table_data += &quot;&lt;td&gt;&quot; + value.email + &quot;&lt;/td&gt;&quot;;
table_data += &quot;&lt;td&gt;&quot; + value.vorname + &quot;&lt;/td&gt;&quot;;
table_data += &quot;&lt;td&gt;&quot; + value.nachname + &quot;&lt;/td&gt;&quot;;
table_data += &quot;&lt;td class=&quot; + &quot;unlock-checkbox&quot; + &quot;&gt;&lt;input type=&quot; + &quot;checkbox&quot; + &quot;&gt;&lt;/input&gt;&lt;/td&gt;&quot;;
table_data += &quot;&lt;/tr&gt;&quot;;
});
$(&quot;#table&quot;).append(table_data);
});
}
function submit() {
var rows = document.getElementsByTagName(&quot;tr&quot;);
//get the checked value for each table row
for (var i = 1; i &lt; rows.length; i++) {
var cols = rows[i].getElementsByTagName(&quot;td&quot;);
var checkbox = cols[3].getElementsByTagName(&quot;input&quot;)[0];
if (checkbox.checked) {
var email = cols[0].innerHTML;
$.ajax({
type: &#39;POST&#39;,
url: &#39;http://localhost:8080/mitglied/unlockUpdate&#39;,
data: { &#39;email&#39;: email },
success: function(msg) {
alert(&quot;success&quot;);
window.location.reload();
}
});
}
}
}

and the MainController.java

@Controller
@RequestMapping(path=&quot;/mitglied&quot;) public class MainController {
@Autowired
private MitgliederRepository mitgliedRepository;
@RequestMapping(path=&quot;/unlockUpdate&quot;, method = RequestMethod.POST)
public @ResponseBody void unlockSelectedUsers(@RequestParam (required=false) String email) {
Iterable&lt;Mitglied&gt; mitglieder = mitgliedRepository.findAll();
List&lt;Mitglied&gt; mitgliederListe = new ArrayList();
mitglieder.iterator().forEachRemaining(mitgliederListe::add);
for (Mitglied m : mitgliederListe) {
if (m.getEmail().equals(email)) {
m.setFreigeschaltet(true);
mitgliedRepository.save(m);
break;
}
}
System.out.println(email);
}

huangapple
  • 本文由 发表于 2020年4月10日 19:30:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61139393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定